|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Infrastructure-only memory-safe embedding transport for frozen V121. |
| 3 | +
|
| 4 | +No scientific representation, model, sample, ordering, folds, controls, or gates |
| 5 | +are changed. Each text is embedded independently with the same frozen Jina model; |
| 6 | +batch_size=1 only lowers peak ONNX attention memory. |
| 7 | +""" |
| 8 | +from __future__ import annotations |
| 9 | +import argparse, json |
| 10 | +from pathlib import Path |
| 11 | +import numpy as np |
| 12 | +from fastembed import TextEmbedding |
| 13 | + |
| 14 | +MODEL_NAME = "jinaai/jina-embeddings-v2-small-en" |
| 15 | + |
| 16 | +def embed1(model, seq): |
| 17 | + arr = np.vstack(list(model.embed(seq, batch_size=1))).astype(np.float32) |
| 18 | + if not np.isfinite(arr).all(): |
| 19 | + raise RuntimeError("non-finite embedding") |
| 20 | + return arr |
| 21 | + |
| 22 | +def main(a): |
| 23 | + d=Path(a.dir) |
| 24 | + texts=json.loads((d/'texts.json').read_text()) |
| 25 | + n=len(texts['semantic']); shard=int(a.shard); shards=int(a.shards) |
| 26 | + if shards < 1 or not (0 <= shard < shards): raise ValueError(f'invalid shard {shard}/{shards}') |
| 27 | + start=(n*shard)//shards; end=(n*(shard+1))//shards |
| 28 | + obj=texts['objective'][start:end]; sem=texts['semantic'][start:end] |
| 29 | + print('frozen shard',shard,'of',shards,'rows',start,end,flush=True) |
| 30 | + model=TextEmbedding(model_name=MODEL_NAME, threads=4) |
| 31 | + E_obj=embed1(model,obj) |
| 32 | + E_sem=embed1(model,sem) |
| 33 | + if E_obj.shape[0] != end-start or E_sem.shape[0] != end-start: raise RuntimeError('row mismatch') |
| 34 | + np.savez_compressed(Path(a.out),E_obj=E_obj,E_sem=E_sem,start=np.array(start),end=np.array(end),total=np.array(n),shard=np.array(shard),shards=np.array(shards)) |
| 35 | + print('complete',shard,E_obj.shape,E_sem.shape,flush=True) |
| 36 | + |
| 37 | +if __name__=='__main__': |
| 38 | + p=argparse.ArgumentParser(); p.add_argument('--dir',required=True); p.add_argument('--out',required=True); p.add_argument('--shard',type=int,required=True); p.add_argument('--shards',type=int,required=True); main(p.parse_args()) |
0 commit comments