File size: 13,288 Bytes
067ccf9
 
 
 
 
 
 
 
 
 
 
 
 
4afb49d
 
 
067ccf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4afb49d
 
 
 
 
067ccf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4afb49d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
067ccf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4afb49d
067ccf9
 
 
 
 
 
 
 
 
 
 
4afb49d
067ccf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4afb49d
 
067ccf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4afb49d
067ccf9
 
 
 
 
4afb49d
067ccf9
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""HF Job (a100-large): zero-shot intfloat/multilingual-e5-large embeddings for all 24.2M normalised records.

Spec (matches the validated zero-shot evaluation):
  * sentence-transformers, model loaded in float16 on CUDA, prompt "query: " on every text, normalize_embeddings=True
  * variant "full": raw_name.strip() + " | " + raw_address.strip() (just the name when the address is empty), max_seq_length=80
  * variant "name": raw_name.strip(), max_seq_length=32
  * batch_size 512; sentence-transformers length-sorts inside each encode() call and restores the original order.
    Each table is fed to encode() in contiguous chunks of CHUNK rows (for progress logging and bounded host memory);
    rows are never reordered.
  * output per table: emb/e5_{variant}/{table}.npy (float16, shape (n_rows, 1024), parquet row order)
                      emb/e5_{variant}/{table}_ids.parquet (entity_id, same order)
  * order: variant "full" for s1,s2,s3,t1,t2,t3, then variant "name"; each table is committed to the Hub
    (Arushhh/amlc-work, dataset) as soon as it is written, in a background thread so the GPU keeps working.
Job splitting (env): TABLES=s1,s2,s3 restricts the job to those tables (default: all six, in the order above);
JOB_TAG names this job's manifest emb/e5_manifest_{JOB_TAG}.json (default emb/e5_manifest.json);
SKIP_EXISTING=1 (default) skips a variant/table whose .npy (exact expected byte size) and _ids.parquet are already on the Hub.
In-job integrity checks per table: shape/dtype via np.load(mmap), non-finite count, min/max L2 norm over all rows,
and an order check (256 random rows re-encoded on their own must have cosine > 0.99 with the stored rows).
"""
import os, sys, time, json, shutil, threading
from concurrent.futures import ThreadPoolExecutor

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import torch
from huggingface_hub import HfApi, snapshot_download, CommitOperationAdd

REPO = 'Arushhh/amlc-work'
MODEL = 'intfloat/multilingual-e5-large'
PROMPT = 'query: '
BATCH = 512
CHUNK = int(os.environ.get('CHUNK', 262144))
DIM = 1024
ALL_TABLES = ['s1', 's2', 's3', 't1', 't2', 't3']
TABLES = [t for t in ALL_TABLES if t in os.environ.get('TABLES', ','.join(ALL_TABLES)).split(',')]
JOB_TAG = os.environ.get('JOB_TAG', '')
MANIFEST = f'emb/e5_manifest_{JOB_TAG}.json' if JOB_TAG else 'emb/e5_manifest.json'
SKIP_EXISTING = os.environ.get('SKIP_EXISTING', '1') == '1'
VARIANTS = [('full', 80), ('name', 32)]
EXPECTED_ROWS = {'s1': 2206821, 's2': 5034616, 's3': 5285603, 't1': 1732544, 't2': 4887273, 't3': 5082316}
WORK = os.environ.get('WORKDIR', '/workspace/e5')
TOKEN = os.environ['HF_TOKEN']
T0 = time.time()


def log(*a):
    print(f"[{time.strftime('%H:%M:%S', time.gmtime())} +{time.time() - T0:7.0f}s]", *a, flush=True)


def build_texts(names, addrs, variant):
    out = []
    n_empty_name = n_empty_addr = 0
    for n, a in zip(names, addrs):
        n = (n or '').strip()
        if not n:
            n_empty_name += 1
        if variant == 'name':
            out.append(n)
            continue
        a = (a or '').strip()
        if a:
            out.append(n + ' | ' + a)
        else:
            n_empty_addr += 1
            out.append(n)
    return out, n_empty_name, n_empty_addr


def main():
    os.makedirs(WORK, exist_ok=True)
    api = HfApi(token=TOKEN)
    log('python', sys.version.split()[0], 'torch', torch.__version__, 'cuda', torch.version.cuda)
    import sentence_transformers, transformers, huggingface_hub
    log('sentence-transformers', sentence_transformers.__version__, 'transformers', transformers.__version__,
        'huggingface_hub', huggingface_hub.__version__)
    assert torch.cuda.is_available(), 'CUDA not available'
    gpu = torch.cuda.get_device_name(0)
    log('GPU:', gpu, f'{torch.cuda.get_device_properties(0).total_memory / 2**30:.1f} GiB', 'CPUs:', os.cpu_count())
    du = shutil.disk_usage(WORK)
    log(f'disk at {WORK}: free {du.free / 2**30:.0f} GiB of {du.total / 2**30:.0f} GiB')
    log(f'TABLES={TABLES} JOB_TAG={JOB_TAG!r} manifest={MANIFEST} SKIP_EXISTING={SKIP_EXISTING}')
    assert TABLES, 'no tables selected'
    on_hub = {}
    if SKIP_EXISTING:
        try:
            for f in api.list_repo_tree(REPO, path_in_repo='emb', recursive=True, repo_type='dataset'):
                if getattr(f, 'size', None) is not None:
                    on_hub[f.path] = f.size
        except Exception as ex:  # noqa: BLE001  (no emb/ folder yet)
            log('list_repo_tree emb/:', repr(ex))
    skip = set()
    for variant, _ in VARIANTS:
        for table in TABLES:
            npy_p, ids_p = f'emb/e5_{variant}/{table}.npy', f'emb/e5_{variant}/{table}_ids.parquet'
            if on_hub.get(npy_p) == 128 + EXPECTED_ROWS[table] * DIM * 2 and ids_p in on_hub:
                skip.add((variant, table))
                log(f'SKIP {variant}/{table}: already on the Hub ({npy_p} {on_hub[npy_p]} bytes, {ids_p} present)')

    t = time.time()
    snapshot_download(REPO, repo_type='dataset', allow_patterns=['norm/*'], local_dir=f'{WORK}/hub', token=TOKEN)
    log(f'downloaded norm/* in {time.time() - t:.0f}s:',
        {f: os.path.getsize(f'{WORK}/hub/norm/{f}') for f in sorted(os.listdir(f'{WORK}/hub/norm'))})

    from sentence_transformers import SentenceTransformer
    t = time.time()
    model = SentenceTransformer(MODEL, device='cuda', model_kwargs={'torch_dtype': torch.float16})
    model.eval()
    pdt = next(model.parameters()).dtype
    if pdt != torch.float16:
        log('params loaded as', pdt, '-> casting with .half()')
        model.half()
    pdt = next(model.parameters()).dtype
    assert pdt == torch.float16, pdt
    am = getattr(model[0].auto_model.config, '_attn_implementation', '?')
    log(f'MODEL LOADED {MODEL} in {time.time() - t:.0f}s: param dtype {pdt}, attn {am}, modules',
        [type(m).__name__ for m in model], 'dim', model.get_sentence_embedding_dimension())
    assert model.get_sentence_embedding_dimension() == DIM

    pool = ThreadPoolExecutor(max_workers=1)
    futures = []
    manifest = {'model': MODEL, 'prompt': PROMPT, 'normalize_embeddings': True, 'dtype': 'float16', 'batch_size': BATCH,
                'chunk_rows': CHUNK, 'job_tables': TABLES, 'skipped_already_on_hub': sorted(f'{v}/{t}' for v, t in skip), 'gpu': gpu, 'torch': torch.__version__,
                'sentence_transformers': sentence_transformers.__version__, 'transformers': transformers.__version__,
                'tables': {}}
    mlock = threading.Lock()

    def upload(variant, table, npy, ids, manifest_bytes):
        dest = f'emb/e5_{variant}'
        for attempt in range(1, 6):
            try:
                t = time.time()
                ops = [CommitOperationAdd(path_in_repo=f'{dest}/{table}.npy', path_or_fileobj=npy),
                       CommitOperationAdd(path_in_repo=f'{dest}/{table}_ids.parquet', path_or_fileobj=ids),
                       CommitOperationAdd(path_in_repo=MANIFEST, path_or_fileobj=manifest_bytes)]
                api.create_commit(repo_id=REPO, repo_type='dataset', operations=ops,
                                  commit_message=f'e5-large zero-shot {variant}/{table}')
                sz = os.path.getsize(npy)
                log(f'UPLOADED {dest}/{table}.npy ({sz} bytes) + {table}_ids.parquet in {time.time() - t:.0f}s '
                    f'({sz / 2**20 / max(time.time() - t, 1e-6):.0f} MiB/s)')
                os.remove(npy)
                return sz
            except Exception as ex:  # noqa: BLE001
                log(f'upload {dest}/{table} attempt {attempt} FAILED: {ex!r}')
                time.sleep(30 * attempt)
        raise RuntimeError(f'upload of {dest}/{table} failed 5 times')

    grand_n = 0
    grand_t = 0.0
    rng = np.random.default_rng(20260925)
    for variant, max_len in VARIANTS:
        model.max_seq_length = max_len
        log(f'===== variant {variant}: max_seq_length={model.max_seq_length}, prompt={PROMPT!r}, batch={BATCH}')
        os.makedirs(f'{WORK}/out/e5_{variant}', exist_ok=True)
        var_n = 0
        var_t = 0.0
        for table in TABLES:
            if (variant, table) in skip:
                continue
            tb = pq.read_table(f'{WORK}/hub/norm/{table}.parquet', columns=['entity_id', 'raw_name', 'raw_address'])
            n = tb.num_rows
            if n != EXPECTED_ROWS[table]:
                log(f'WARNING {table}: {n} rows, expected {EXPECTED_ROWS[table]}')
            texts, e_name, e_addr = build_texts(tb.column('raw_name').to_pylist(), tb.column('raw_address').to_pylist(),
                                                variant)
            log(f'{variant}/{table}: {n} rows, empty names {e_name}, empty addresses {e_addr}; examples: {texts[:2]}')
            npy = f'{WORK}/out/e5_{variant}/{table}.npy'
            ids = f'{WORK}/out/e5_{variant}/{table}_ids.parquet'
            pq.write_table(pa.table({'entity_id': tb.column('entity_id')}), ids)
            ids_arr = tb.column('entity_id')
            del tb
            out = np.lib.format.open_memmap(npy, mode='w+', dtype=np.float16, shape=(n, DIM))
            t = time.time()
            for s in range(0, n, CHUNK):
                tc = time.time()
                chunk = texts[s:s + CHUNK]
                e = model.encode(chunk, batch_size=BATCH, prompt=PROMPT, normalize_embeddings=True,
                                 convert_to_numpy=True, show_progress_bar=False)
                assert e.shape == (len(chunk), DIM), e.shape
                out[s:s + len(chunk)] = e.astype(np.float16, copy=False)
                done = s + len(chunk)
                el = time.time() - t
                log(f'  {variant}/{table} rows {done}/{n}: chunk {len(chunk) / (time.time() - tc):.0f} rec/s, '
                    f'table {done / el:.0f} rec/s, ETA table {(n - done) / (done / el) / 60:.1f} min')
            enc_s = time.time() - t
            out.flush()
            del out
            # ---- integrity checks
            arr = np.load(npy, mmap_mode='r')
            assert arr.shape == (n, DIM) and arr.dtype == np.float16, (arr.shape, arr.dtype)
            hdr = int(arr.offset)
            nmin, nmax, nonfin = 9.0, 0.0, 0
            for s in range(0, n, 1 << 20):
                blk = np.asarray(arr[s:s + (1 << 20)], dtype=np.float32)
                nonfin += int((~np.isfinite(blk)).sum())
                nr = np.linalg.norm(blk, axis=1)
                nmin = min(nmin, float(nr.min()))
                nmax = max(nmax, float(nr.max()))
            idx = np.sort(rng.choice(n, size=min(256, n), replace=False))
            chk = model.encode([texts[i] for i in idx], batch_size=BATCH, prompt=PROMPT, normalize_embeddings=True,
                               convert_to_numpy=True, show_progress_bar=False).astype(np.float32)
            cos = (np.asarray(arr[idx], dtype=np.float32) * chk).sum(1)
            ids_back = pq.read_table(ids).column('entity_id')
            ids_ok = ids_back.equals(ids_arr) if hasattr(ids_back, 'equals') else None
            del arr
            fsize = os.path.getsize(npy)
            rps = n / enc_s
            var_n += n
            var_t += enc_s
            grand_n += n
            grand_t += enc_s
            log(f'TABLE DONE {variant}/{table}: n={n} encode {enc_s:.0f}s = {rps:.0f} rec/s | variant so far '
                f'{var_n} rows {var_n / var_t:.0f} rec/s | ALL so far {grand_n} rows {grand_n / grand_t:.0f} rec/s | '
                f'norm min {nmin:.4f} max {nmax:.4f} nonfinite {nonfin} | order check cos min {cos.min():.5f} '
                f'mean {cos.mean():.5f} | ids equal {ids_ok} | file {fsize} bytes (expected {128 + n * DIM * 2})')
            if cos.min() < 0.99 or nonfin > 0 or not ids_ok or fsize != hdr + n * DIM * 2:
                log(f'FATAL integrity failure on {variant}/{table}; aborting')
                sys.exit(3)
            with mlock:
                manifest['tables'][f'{variant}/{table}'] = dict(
                    rows=n, max_seq_length=max_len, encode_seconds=round(enc_s, 1), rec_per_s=round(rps, 1),
                    npy_bytes=fsize, norm_min=nmin, norm_max=nmax, nonfinite=nonfin,
                    order_check_cos_min=float(cos.min()), empty_names=e_name, empty_addresses=e_addr)
                mb = json.dumps(manifest, indent=1).encode()
            # surface any earlier upload failure before queueing more work
            for f in futures:
                if f.done() and f.exception() is not None:
                    raise f.exception()
            futures.append(pool.submit(upload, variant, table, npy, ids, mb))
            del texts, ids_arr
        log(f'===== variant {variant} encoded: {var_n} rows in {var_t:.0f}s = {var_n / max(var_t, 1e-9):.0f} rec/s')

    log('all encoding done; waiting for uploads')
    for f in futures:
        f.result()
    pool.shutdown()
    log(f'ALL DONE: {grand_n} row-encodings in {grand_t:.0f}s encode time ({grand_n / max(grand_t, 1e-9):.0f} rec/s), '
        f'wall {time.time() - T0:.0f}s')
    log(f'GPU {torch.cuda.get_device_name(0)} max_memory_allocated '
        f'{torch.cuda.max_memory_allocated() / 2**30:.2f} GiB ({torch.cuda.max_memory_allocated()} bytes)')
    print(json.dumps(manifest, indent=1), flush=True)


if __name__ == '__main__':
    main()