Views
No views yet
mlx-llm from GitHub.1git clone https://github.com/riccardomusmeci/mlx-llm
2cd mlx-llm
3pip install .1import mlx.core as mx
2import numpy as np
3from mlx_llm.model import create_model
4from transformers import AutoTokenizer
5
6model = create_model(
7 "e5-mistral-7b-instruct",
8 weights_path="path/to/weights.npz",
9 strict=False
10)
11
12def get_detailed_instruct(task_description: str, query: str) -> str:
13 return f'Instruct: {task_description}\nQuery: {query}'
14
15def last_token_pool(embeds: mx.array, attn_mask: mx.array) -> mx.array:
16 left_padding = (attn_mask[:, -1].sum() == attn_mask.shape[0])
17 if left_padding:
18 return embeds[:, -1]
19 else:
20 sequence_lengths = attn_mask.sum(axis=1) - 1
21 batch_size = embeds.shape[0]
22 return embeds[mx.arange(batch_size), sequence_lengths]
23
24task = 'Given a web search query, retrieve relevant passages that answer the query'
25
26input_texts = [
27 get_detailed_instruct(task, 'how much protein should a female eat'),
28 # get_detailed_instruct(task, 'summit define'),
29 "As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",
30 "Definition of summit for English Language Learners. : 1 the highest point of a mountain : the top of a mountain. : 2 the highest level. : 3 a meeting or series of meetings between the leaders of two or more governments."
31]
32
33tokenizer = AutoTokenizer.from_pretrained('intfloat/e5-mistral-7b-instruct')
34
35# prepare input and attn_mask
36max_length = 4096
37batch_dict = tokenizer(
38 input_texts,
39 max_length=max_length - 1,
40 return_attention_mask=False,
41 padding=False,
42 truncation=True
43)
44
45batch_dict['input_ids'] = [
46 input_ids + [tokenizer.eos_token_id] for input_ids in batch_dict['input_ids']
47]
48
49batch_dict = tokenizer.pad(
50 batch_dict,
51 padding=True,
52 return_attention_mask=True,
53 return_tensors='np'
54)
55
56x = mx.array(batch_dict["input_ids"].tolist())
57attn_mask = mx.array(batch_dict["attention_mask"].tolist())
58
59# compute embed
60embeds = model.embed(x)
61mx.eval(embeds)
62
63embeds = np.array(last_token_pool(embeds, attn_mask))
64
65# Normalize embeds
66norm_den = np.linalg.norm(embeds, axis=-1)
67norm_embeds = embeds / norm_den[:, None]
68
69scores = (norm_embeds @ norm_embeds.T) * 100
70print(scores)