nexaai 1.0.9__cp310-cp310-macosx_14_0_universal2.whl → 1.0.11rc1__cp310-cp310-macosx_14_0_universal2.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of nexaai might be problematic. Click here for more details.
- nexaai/_stub.cpython-310-darwin.so +0 -0
- nexaai/_version.py +1 -1
- nexaai/binds/common_bind.cpython-310-darwin.so +0 -0
- nexaai/binds/embedder_bind.cpython-310-darwin.so +0 -0
- nexaai/binds/libnexa_bridge.dylib +0 -0
- nexaai/binds/llm_bind.cpython-310-darwin.so +0 -0
- nexaai/binds/nexa_llama_cpp/libggml-base.dylib +0 -0
- nexaai/binds/nexa_llama_cpp/libggml-cpu.so +0 -0
- nexaai/binds/nexa_llama_cpp/libggml-metal.so +0 -0
- nexaai/binds/nexa_llama_cpp/libggml.dylib +0 -0
- nexaai/binds/nexa_llama_cpp/libllama.dylib +0 -0
- nexaai/binds/nexa_llama_cpp/libmtmd.dylib +0 -0
- nexaai/binds/nexa_llama_cpp/libnexa_plugin.dylib +0 -0
- nexaai/binds/nexa_mlx/libnexa_plugin.dylib +0 -0
- nexaai/embedder_impl/mlx_embedder_impl.py +5 -6
- nexaai/mlx_backend/embedding/generate.py +16 -219
- nexaai/mlx_backend/embedding/interface.py +41 -346
- nexaai/mlx_backend/embedding/main.py +35 -126
- nexaai/utils/model_manager.py +87 -103
- nexaai/utils/progress_tracker.py +8 -12
- {nexaai-1.0.9.dist-info → nexaai-1.0.11rc1.dist-info}/METADATA +1 -2
- {nexaai-1.0.9.dist-info → nexaai-1.0.11rc1.dist-info}/RECORD +24 -27
- nexaai/utils/manifest_utils.py +0 -280
- nexaai/utils/model_types.py +0 -47
- nexaai/utils/quantization_utils.py +0 -239
- {nexaai-1.0.9.dist-info → nexaai-1.0.11rc1.dist-info}/WHEEL +0 -0
- {nexaai-1.0.9.dist-info → nexaai-1.0.11rc1.dist-info}/top_level.txt +0 -0
|
Binary file
|
nexaai/_version.py
CHANGED
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -3,7 +3,7 @@ import numpy as np
|
|
|
3
3
|
|
|
4
4
|
from nexaai.common import PluginID
|
|
5
5
|
from nexaai.embedder import Embedder, EmbeddingConfig
|
|
6
|
-
from nexaai.mlx_backend.embedding.interface import
|
|
6
|
+
from nexaai.mlx_backend.embedding.interface import Embedder as MLXEmbedderInterface
|
|
7
7
|
from nexaai.mlx_backend.ml import ModelConfig as MLXModelConfig, SamplerConfig as MLXSamplerConfig, GenerationConfig as MLXGenerationConfig, EmbeddingConfig
|
|
8
8
|
|
|
9
9
|
|
|
@@ -27,12 +27,11 @@ class MLXEmbedderImpl(Embedder):
|
|
|
27
27
|
MLXEmbedderImpl instance
|
|
28
28
|
"""
|
|
29
29
|
try:
|
|
30
|
-
#
|
|
31
|
-
instance = cls()
|
|
30
|
+
# MLX interface is already imported
|
|
32
31
|
|
|
33
|
-
#
|
|
34
|
-
|
|
35
|
-
instance._mlx_embedder =
|
|
32
|
+
# Create instance and load MLX embedder
|
|
33
|
+
instance = cls()
|
|
34
|
+
instance._mlx_embedder = MLXEmbedderInterface(
|
|
36
35
|
model_path=model_path,
|
|
37
36
|
tokenizer_path=tokenizer_file
|
|
38
37
|
)
|
|
@@ -23,46 +23,11 @@ from .modeling.nexa_jina_v2 import Model, ModelArgs
|
|
|
23
23
|
from tokenizers import Tokenizer
|
|
24
24
|
from huggingface_hub import snapshot_download
|
|
25
25
|
|
|
26
|
-
|
|
27
|
-
try:
|
|
28
|
-
import mlx_embeddings
|
|
29
|
-
MLX_EMBEDDINGS_AVAILABLE = True
|
|
30
|
-
except ImportError:
|
|
31
|
-
MLX_EMBEDDINGS_AVAILABLE = False
|
|
32
|
-
# Suppress warning during import to avoid interfering with C++ tests
|
|
33
|
-
# The warning will be shown when actually trying to use mlx_embeddings functionality
|
|
34
|
-
pass
|
|
35
|
-
|
|
36
|
-
def detect_model_type(model_path):
|
|
37
|
-
"""Detect if the model is Jina V2 or generic mlx_embeddings model."""
|
|
38
|
-
config_path = os.path.join(model_path, "config.json") if os.path.isdir(model_path) else f"{model_path}/config.json"
|
|
39
|
-
|
|
40
|
-
if not os.path.exists(config_path):
|
|
41
|
-
# Try default modelfiles directory
|
|
42
|
-
config_path = f"{curr_dir}/modelfiles/config.json"
|
|
43
|
-
if not os.path.exists(config_path):
|
|
44
|
-
return "generic"
|
|
45
|
-
|
|
46
|
-
try:
|
|
47
|
-
with open(config_path, "r") as f:
|
|
48
|
-
config = json.load(f)
|
|
49
|
-
|
|
50
|
-
# Check if it's a Jina V2 model
|
|
51
|
-
architectures = config.get("architectures", [])
|
|
52
|
-
if "JinaBertModel" in architectures:
|
|
53
|
-
return "jina_v2"
|
|
54
|
-
|
|
55
|
-
return "generic"
|
|
56
|
-
except Exception:
|
|
57
|
-
return "generic"
|
|
58
|
-
|
|
59
|
-
# ========== Jina V2 Direct Implementation ==========
|
|
60
|
-
|
|
61
|
-
def load_jina_model(model_id):
|
|
26
|
+
def load_model(model_id):
|
|
62
27
|
"""Initialize and load the Jina V2 model with FP16 weights."""
|
|
63
28
|
# Load configuration from config.json
|
|
64
29
|
if not os.path.exists(f"{curr_dir}/modelfiles/config.json"):
|
|
65
|
-
print(f"📥 Downloading
|
|
30
|
+
print(f"📥 Downloading model {model_id}...")
|
|
66
31
|
|
|
67
32
|
# Ensure modelfiles directory exists
|
|
68
33
|
os.makedirs(f"{curr_dir}/modelfiles", exist_ok=True)
|
|
@@ -117,15 +82,15 @@ def load_jina_model(model_id):
|
|
|
117
82
|
|
|
118
83
|
return model
|
|
119
84
|
|
|
120
|
-
def
|
|
121
|
-
"""Load and configure the tokenizer
|
|
85
|
+
def load_tokenizer():
|
|
86
|
+
"""Load and configure the tokenizer."""
|
|
122
87
|
tokenizer = Tokenizer.from_file(f"{curr_dir}/modelfiles/tokenizer.json")
|
|
123
88
|
tokenizer.enable_padding(pad_id=0, pad_token="[PAD]")
|
|
124
89
|
tokenizer.enable_truncation(max_length=512)
|
|
125
90
|
return tokenizer
|
|
126
91
|
|
|
127
|
-
def
|
|
128
|
-
"""Encode a single text
|
|
92
|
+
def encode_text(model, tokenizer, text):
|
|
93
|
+
"""Encode a single text and return its embedding."""
|
|
129
94
|
# Tokenize the text
|
|
130
95
|
encoding = tokenizer.encode(text)
|
|
131
96
|
|
|
@@ -148,186 +113,18 @@ def encode_jina_text(model, tokenizer, text):
|
|
|
148
113
|
|
|
149
114
|
return embeddings
|
|
150
115
|
|
|
151
|
-
# ========== MLX Embeddings Direct Implementation ==========
|
|
152
|
-
|
|
153
|
-
def load_mlx_embeddings_model(model_id):
|
|
154
|
-
"""Load model using mlx_embeddings package."""
|
|
155
|
-
if not MLX_EMBEDDINGS_AVAILABLE:
|
|
156
|
-
print("Warning: mlx_embeddings not available. Please install it to use general embedding models.")
|
|
157
|
-
raise ImportError("mlx_embeddings package is not available. Please install it first.")
|
|
158
|
-
|
|
159
|
-
# Download model if needed
|
|
160
|
-
model_path = f"{curr_dir}/modelfiles"
|
|
161
|
-
|
|
162
|
-
if not os.path.exists(f"{model_path}/config.json"):
|
|
163
|
-
print(f"📥 Downloading model {model_id}...")
|
|
164
|
-
os.makedirs(model_path, exist_ok=True)
|
|
165
|
-
|
|
166
|
-
try:
|
|
167
|
-
snapshot_download(
|
|
168
|
-
repo_id=model_id,
|
|
169
|
-
local_dir=model_path,
|
|
170
|
-
resume_download=True,
|
|
171
|
-
local_dir_use_symlinks=False
|
|
172
|
-
)
|
|
173
|
-
print("✅ Model download completed!")
|
|
174
|
-
except Exception as e:
|
|
175
|
-
print(f"❌ Failed to download model: {e}")
|
|
176
|
-
raise
|
|
177
|
-
|
|
178
|
-
# Load model and tokenizer using mlx_embeddings
|
|
179
|
-
model, tokenizer = mlx_embeddings.load(model_path)
|
|
180
|
-
return model, tokenizer
|
|
181
|
-
|
|
182
|
-
def encode_mlx_embeddings_text(model, tokenizer, texts, model_path=None):
|
|
183
|
-
"""Generate embeddings using mlx_embeddings."""
|
|
184
|
-
if isinstance(texts, str):
|
|
185
|
-
texts = [texts]
|
|
186
|
-
|
|
187
|
-
# Check if this is a Gemma3TextModel by checking config
|
|
188
|
-
# WORKAROUND: Gemma3TextModel has a bug where it expects 'inputs' as positional arg
|
|
189
|
-
# but mlx_embeddings.generate passes 'input_ids' as keyword arg
|
|
190
|
-
# See: https://github.com/ml-explore/mlx-examples/issues/... (bug report pending)
|
|
191
|
-
is_gemma = False
|
|
192
|
-
if model_path:
|
|
193
|
-
config_path = os.path.join(model_path, "config.json") if os.path.isdir(model_path) else f"{model_path}/config.json"
|
|
194
|
-
else:
|
|
195
|
-
config_path = f"{curr_dir}/modelfiles/config.json"
|
|
196
|
-
|
|
197
|
-
if os.path.exists(config_path):
|
|
198
|
-
try:
|
|
199
|
-
with open(config_path, "r") as f:
|
|
200
|
-
config = json.load(f)
|
|
201
|
-
architectures = config.get("architectures", [])
|
|
202
|
-
is_gemma = "Gemma3TextModel" in architectures
|
|
203
|
-
except Exception:
|
|
204
|
-
pass
|
|
205
|
-
|
|
206
|
-
if is_gemma:
|
|
207
|
-
# HARDCODED WORKAROUND for Gemma3TextModel bug
|
|
208
|
-
# Use direct tokenization and model call instead of mlx_embeddings.generate
|
|
209
|
-
# This avoids the bug where generate passes 'input_ids' as keyword arg
|
|
210
|
-
# but Gemma3TextModel.__call__ expects 'inputs' as positional arg
|
|
211
|
-
|
|
212
|
-
# Tokenize using batch_encode_plus for Gemma models
|
|
213
|
-
encoded_input = tokenizer.batch_encode_plus(
|
|
214
|
-
texts,
|
|
215
|
-
padding=True,
|
|
216
|
-
truncation=True,
|
|
217
|
-
return_tensors='mlx',
|
|
218
|
-
max_length=512
|
|
219
|
-
)
|
|
220
|
-
|
|
221
|
-
# Get input tensors
|
|
222
|
-
input_ids = encoded_input['input_ids']
|
|
223
|
-
attention_mask = encoded_input.get('attention_mask', None)
|
|
224
|
-
|
|
225
|
-
# Call model with positional input_ids and keyword attention_mask
|
|
226
|
-
# This matches Gemma3TextModel's expected signature:
|
|
227
|
-
# def __call__(self, inputs: mx.array, attention_mask: Optional[mx.array] = None)
|
|
228
|
-
output = model(input_ids, attention_mask=attention_mask)
|
|
229
|
-
|
|
230
|
-
# Get the normalized embeddings
|
|
231
|
-
return output.text_embeds
|
|
232
|
-
else:
|
|
233
|
-
# Normal path for non-Gemma models
|
|
234
|
-
# Use standard mlx_embeddings.generate approach
|
|
235
|
-
output = mlx_embeddings.generate(
|
|
236
|
-
model,
|
|
237
|
-
tokenizer,
|
|
238
|
-
texts=texts,
|
|
239
|
-
max_length=512,
|
|
240
|
-
padding=True,
|
|
241
|
-
truncation=True
|
|
242
|
-
)
|
|
243
|
-
|
|
244
|
-
return output.text_embeds
|
|
245
|
-
|
|
246
116
|
def main(model_id):
|
|
247
117
|
"""Main function to handle user input and generate embeddings."""
|
|
248
118
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
print(f"Model not found locally. Downloading...")
|
|
258
|
-
os.makedirs(f"{curr_dir}/modelfiles", exist_ok=True)
|
|
259
|
-
try:
|
|
260
|
-
snapshot_download(
|
|
261
|
-
repo_id=model_id,
|
|
262
|
-
local_dir=f"{curr_dir}/modelfiles",
|
|
263
|
-
resume_download=True,
|
|
264
|
-
local_dir_use_symlinks=False
|
|
265
|
-
)
|
|
266
|
-
print("✅ Model download completed!")
|
|
267
|
-
# Re-detect model type after download
|
|
268
|
-
model_type = detect_model_type(f"{curr_dir}/modelfiles")
|
|
269
|
-
except Exception as e:
|
|
270
|
-
print(f"❌ Failed to download model: {e}")
|
|
271
|
-
raise
|
|
272
|
-
|
|
273
|
-
print(f"📦 Detected model type: {model_type}")
|
|
274
|
-
|
|
275
|
-
# Test texts
|
|
276
|
-
test_texts = [
|
|
277
|
-
"Hello, how are you?",
|
|
278
|
-
"What is machine learning?",
|
|
279
|
-
"The weather is nice today."
|
|
280
|
-
]
|
|
281
|
-
|
|
282
|
-
if model_type == "jina_v2":
|
|
283
|
-
print("Using Jina V2 direct implementation")
|
|
284
|
-
|
|
285
|
-
# Load Jina V2 model
|
|
286
|
-
model = load_jina_model(model_id)
|
|
287
|
-
tokenizer = load_jina_tokenizer()
|
|
288
|
-
|
|
289
|
-
print("\nGenerating embeddings for test texts:")
|
|
290
|
-
for text in test_texts:
|
|
291
|
-
embedding = encode_jina_text(model, tokenizer, text)
|
|
292
|
-
print(f"\nText: '{text}'")
|
|
293
|
-
print(f" Embedding shape: {embedding.shape}")
|
|
294
|
-
print(f" Sample values (first 5): {embedding.flatten()[:5].tolist()}")
|
|
295
|
-
print(f" Stats - Min: {embedding.min():.4f}, Max: {embedding.max():.4f}, Mean: {embedding.mean():.4f}")
|
|
296
|
-
|
|
297
|
-
else:
|
|
298
|
-
print("Using mlx_embeddings direct implementation")
|
|
299
|
-
|
|
300
|
-
if not MLX_EMBEDDINGS_AVAILABLE:
|
|
301
|
-
print("❌ mlx_embeddings is not installed. Please install it to use generic models.")
|
|
302
|
-
return
|
|
303
|
-
|
|
304
|
-
# Load generic model using mlx_embeddings
|
|
305
|
-
model, tokenizer = load_mlx_embeddings_model(model_id)
|
|
306
|
-
|
|
307
|
-
print("\nGenerating embeddings for test texts:")
|
|
308
|
-
# Pass model_path to handle Gemma workaround if needed
|
|
309
|
-
embeddings = encode_mlx_embeddings_text(model, tokenizer, test_texts, model_path=f"{curr_dir}/modelfiles")
|
|
310
|
-
|
|
311
|
-
for i, text in enumerate(test_texts):
|
|
312
|
-
embedding = embeddings[i]
|
|
313
|
-
print(f"\nText: '{text}'")
|
|
314
|
-
print(f" Embedding shape: {embedding.shape}")
|
|
315
|
-
print(f" Sample values (first 5): {embedding[:5].tolist()}")
|
|
316
|
-
|
|
317
|
-
# Calculate stats
|
|
318
|
-
emb_array = mx.array(embedding) if not isinstance(embedding, mx.array) else embedding
|
|
319
|
-
print(f" Stats - Min: {emb_array.min():.4f}, Max: {emb_array.max():.4f}, Mean: {emb_array.mean():.4f}")
|
|
320
|
-
|
|
321
|
-
print("\n✅ Direct embedding generation completed!")
|
|
119
|
+
# Load model and tokenizer
|
|
120
|
+
model = load_model(model_id)
|
|
121
|
+
tokenizer = load_tokenizer()
|
|
122
|
+
user_input = "Hello, how are you?"
|
|
123
|
+
embedding = encode_text(model, tokenizer, user_input)
|
|
124
|
+
print(f"Embedding shape: {embedding.shape}")
|
|
125
|
+
print(f"Embedding sample values: {embedding.flatten()[:5].tolist()}")
|
|
126
|
+
print(f"Embedding min: {embedding.min()}, Max: {embedding.max()}, Mean: {embedding.mean()}, Std: {embedding.std()}")
|
|
322
127
|
|
|
323
128
|
if __name__ == "__main__":
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
parser.add_argument(
|
|
327
|
-
"--model_id",
|
|
328
|
-
type=str,
|
|
329
|
-
default="nexaml/jina-v2-fp16-mlx",
|
|
330
|
-
help="Model ID from Hugging Face Hub (e.g., 'nexaml/jina-v2-fp16-mlx' or 'mlx-community/embeddinggemma-300m-bf16')"
|
|
331
|
-
)
|
|
332
|
-
args = parser.parse_args()
|
|
333
|
-
main(args.model_id)
|
|
129
|
+
model_id = "nexaml/jina-v2-fp16-mlx"
|
|
130
|
+
main(model_id)
|