sayqin commited on
Commit
0cdadef
·
verified ·
1 Parent(s): 30b0577

Initial release of BabelCore v0.1

Browse files
Files changed (6) hide show
  1. LICENSES.md +8 -0
  2. README.md +153 -0
  3. benchmark.py +199 -0
  4. benchmarks/azeval_partial_48.json +118 -0
  5. inference.py +72 -0
  6. requirements.txt +6 -0
LICENSES.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Upstream licenses and attribution
2
+
3
+ - K2 Horizon 3.7B GGUF, Institute of Foundation Models: https://huggingface.co/IFM/K2-Horizon-3.7B-GGUF — Apache License 2.0, https://www.apache.org/licenses/LICENSE-2.0
4
+ - NLLB-200 1.3B, Meta: https://huggingface.co/facebook/nllb-200-1.3B — Creative Commons Attribution-NonCommercial 4.0, https://creativecommons.org/licenses/by-nc/4.0/
5
+ - AZ-Eval v2.0.1: https://doi.org/10.5281/zenodo.22695092 — see the original dataset and its license.
6
+ - K2 deployment tools and llama.cpp: see https://github.com/MBZUAI-IFM/k2-local-deploy and https://github.com/ggml-org/llama.cpp for their respective licenses.
7
+
8
+ This repository distributes integration code and a partial benchmark summary only. It does not redistribute upstream model weights or dataset contents. Use of downloaded components is governed by their own licenses. The pipeline depends on a non-commercially licensed translation model. A separate license for the original integration code has not yet been selected; the repository metadata therefore uses `other` rather than suggesting that all components share a permissive license.
README.md ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: mixed-upstream-licenses
4
+ license_link: https://huggingface.co/sayqin/BabelCore-v0.1/blob/main/LICENSES.md
5
+ language:
6
+ - en
7
+ - az
8
+ tags:
9
+ - babelcore
10
+ - multilingual
11
+ - reasoning
12
+ - translation
13
+ - low-resource-languages
14
+ - k2-horizon
15
+ - nllb
16
+ - research
17
+ - model-integration
18
+ base_model:
19
+ - IFM/K2-Horizon-3.7B-GGUF
20
+ - facebook/nllb-200-1.3B
21
+ ---
22
+
23
+ # BabelCore v0.1
24
+
25
+ **Many languages. One intelligence.**
26
+
27
+ Bridging the performance gap between English and low-resource languages in small language models without additional training.
28
+
29
+ ## Motivation
30
+
31
+ While recent advances in small language models have significantly improved their reasoning capabilities, their performance in low-resource languages remains a considerable challenge.
32
+
33
+ K2 Horizon 3.7B was selected as the core reasoning model because of its leading performance among the displayed models under 5 billion parameters in the [Artificial Analysis Intelligence Index v5.0.2](https://artificialanalysis.ai/models/k2-horizon-3-7b), as observed at the time of model selection.
34
+
35
+ However, our preliminary evaluations reveal a substantial performance gap between English and Azerbaijani, even when the model is presented with equivalent questions in both languages.
36
+
37
+ This project explores whether the existing knowledge and reasoning capabilities of small language models can be transferred to low-resource languages through a modular multilingual architecture, without additional pretraining, fine-tuning or reinforcement learning.
38
+
39
+ ## Architecture
40
+
41
+ The system integrates two independent pretrained models:
42
+
43
+ - **K2 Horizon 3.7B:** Core reasoning model.
44
+ - **NLLB-200 1.3B:** Bidirectional multilingual translation component.
45
+
46
+ **Native-language input → English translation → K2 reasoning → Native-language output**
47
+
48
+ English inputs are processed directly by K2 without translation. Neither model's weights have been modified, and no additional parameters have been trained. This is a text-based translation cascade, not a trained mixture of experts, a merged checkpoint or a new foundation model.
49
+
50
+ ## Preliminary benchmark results
51
+
52
+ The initial evaluation uses [AZ-Eval v2.0.1](https://doi.org/10.5281/zenodo.22695092), a public benchmark containing 1,006 parallel English and Azerbaijani questions.
53
+
54
+ To measure cross-lingual performance, we define the original K2 Horizon 3.7B's English accuracy as a normalised reference point of **1.00**.
55
+
56
+ ### Relative Performance Index
57
+
58
+ | Model | English | Azerbaijani |
59
+ |---|---:|---:|
60
+ | K2 Horizon 3.7B | 1.00 (reference) | 0.154 |
61
+ | **BabelCore v0.1** | **1.00** | **0.846** |
62
+
63
+ The original model achieves only 15.4% of its English accuracy when operating in Azerbaijani. BabelCore increases this ratio to **84.6%**, without additional training.
64
+
65
+ These preliminary results are based on 48 paired questions using normalised exact-match scoring against language-specific references and available aliases, not the official benchmark scorer. The English predictions are shared between both systems because English inputs bypass translation.
66
+
67
+ The Relative Performance Index measures the ratio of aggregate accuracy scores. A reference value of 1.00 does not indicate perfect accuracy or question-by-question agreement. These results do not establish state-of-the-art performance.
68
+
69
+ The benchmark results will be updated as further evaluations are completed. Detailed evaluation results, individual model predictions and reproducible benchmark scripts will be publicly released. The initial aggregate snapshot is available in [benchmarks/azeval_partial_48.json](benchmarks/azeval_partial_48.json); raw predictions are not yet included.
70
+
71
+ ## Supported languages
72
+
73
+ The architecture is designed to support approximately 200 languages and language varieties through its NLLB translation component.
74
+
75
+ These include, but are not limited to:
76
+
77
+ | Language group | Languages |
78
+ |---|---|
79
+ | Turkic | Azerbaijani, Turkish, Kazakh, Uzbek, Kyrgyz, Turkmen, Tatar, Uyghur |
80
+ | European | English, French, German, Spanish, Italian, Portuguese, Dutch, Polish, Ukrainian, Russian, Romanian, Greek, Swedish, Norwegian, Finnish |
81
+ | Caucasian | Georgian, Armenian |
82
+ | Middle Eastern | Arabic, Persian, Kurdish, Hebrew, Pashto |
83
+ | South Asian | Hindi, Urdu, Bengali, Punjabi, Tamil, Telugu, Marathi, Nepali |
84
+ | East and Southeast Asian | Chinese, Japanese, Korean, Vietnamese, Thai, Indonesian, Malay, Burmese, Khmer, Lao |
85
+ | African | Swahili, Hausa, Amharic, Somali, Yoruba, Igbo, Zulu, Afrikaans |
86
+
87
+ **Azerbaijani is currently the only non-English language evaluated in this project.** Support for the other listed languages is inherited from NLLB, and their end-to-end performance has yet to be independently evaluated. See the [NLLB model card](https://huggingface.co/facebook/nllb-200-1.3B) for supported language and script codes. The list above is representative rather than exhaustive.
88
+
89
+ The broader objective is to make the knowledge and reasoning capabilities of small language models accessible to speakers of low-resource languages without requiring extensive language-specific training.
90
+
91
+ Whether this architecture can outperform existing multilingual models remains to be established through independent comparative evaluations.
92
+
93
+ ## Ongoing research
94
+
95
+ Future evaluations will focus on:
96
+
97
+ - Completing the AZ-Eval benchmark.
98
+ - Performance across individual knowledge categories.
99
+ - Mathematical and multi-step reasoning.
100
+ - Additional low-resource languages.
101
+ - Comparison with existing multilingual models.
102
+ - Internet-assisted factual question answering.
103
+ - Computational efficiency and inference speed.
104
+
105
+ All completed evaluations will be publicly released, and the model card will be updated accordingly.
106
+
107
+ ## Community evaluations
108
+
109
+ Independent evaluations, benchmark reproductions, suggestions and contributions are encouraged.
110
+
111
+ Researchers and developers are invited to evaluate the architecture in their native languages and share their findings.
112
+
113
+ ## Technical configuration
114
+
115
+ | Component | Configuration |
116
+ |---|---|
117
+ | Reasoning | [IFM/K2-Horizon-3.7B-GGUF](https://huggingface.co/IFM/K2-Horizon-3.7B-GGUF), Q4_K_M |
118
+ | Translation | [facebook/nllb-200-1.3B](https://huggingface.co/facebook/nllb-200-1.3B), FP16, beam size 4 |
119
+ | Runtime | llama.cpp b11619, commit 9cf967a04 |
120
+ | Reasoning settings | Low effort, temperature 0, seed 42, up to 1,024 generated tokens |
121
+ | Translation limit | 512 new tokens |
122
+ | Additional training | None |
123
+
124
+ ## Installation and inference
125
+
126
+ This repository contains the integration and evaluation code, not duplicate pretrained weights. A CUDA-capable Linux environment such as Colab with a T4 is recommended. GPU memory and generation speed depend on the runtime and hardware. The packaged interactive CLI is a reference implementation derived from the benchmark pipeline; it has not yet been end-to-end GPU tested.
127
+
128
+ In a terminal, from a checkout of this repository:
129
+
130
+ ```bash
131
+ python -m pip install -r requirements.txt
132
+ mkdir -p /content/k2
133
+ curl -L https://raw.githubusercontent.com/MBZUAI-IFM/k2-local-deploy/main/k2-horizon-local/scripts/k2local.py -o /content/k2/k2local.py
134
+ python /content/k2/k2local.py --dir /content/k2 install --backend cuda --build b11619
135
+ python /content/k2/k2local.py --dir /content/k2 download --size 3.7B --quant Q4_K_M
136
+ python inference.py --k2-dir /content/k2 --language azj_Latn --question 'Azərbaycanın paytaxtı haradır?' --short-answer
137
+ ```
138
+
139
+ Use `--language eng_Latn` for direct English. Other NLLB language codes are accepted experimentally, but only Azerbaijani has preliminary comparative results. The CLI uses one persistent K2 slot for interactive use; the benchmark uses two concurrent slots. To enter multiple questions in one session, omit `--question`.
140
+
141
+ ## Reproduce the evaluation
142
+
143
+ ```bash
144
+ python benchmark.py --k2-dir /content/k2 --limit 1006 --parallel 2 --batch 8
145
+ ```
146
+
147
+ The benchmark downloads the original AZ-Eval archive and checks its checksum, records model revisions and settings, saves individual responses incrementally, and reports overall and category-level accuracy. Use the same arguments and output directory to resume. This release extends the HTTP timeout to 2,400 seconds to accommodate long responses without changing the generation budget. It does not solve the underlying slow inference. A changed generation budget, scoring protocol or parallel setting should be evaluated in a separate output directory.
148
+
149
+ The published snapshot was produced with a 900-second timeout. The new timeout has not been validated in a complete benchmark run. The requirements are not yet pinned to the original Colab environment; complete version information is saved in the benchmark's results file during execution.
150
+
151
+ ## Licenses and attribution
152
+
153
+ The upstream K2 model is Apache-2.0; NLLB is CC BY-NC 4.0 and restricts commercial use. The complete pipeline is intended for non-commercial research and evaluation. No upstream weights are redistributed here. See [LICENSES.md](LICENSES.md) for attribution and licensing notes. AZ-Eval is credited to its authors and linked at its original DOI. No claim of endorsement by IFM, Meta, Artificial Analysis or the benchmark authors is made.
benchmark.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AZ-Eval v2.0.1 paired short-answer evaluation, no training.
2
+ Official archive: https://doi.org/10.5281/zenodo.22695092 (CC BY 4.0).
3
+ Local normalized exact-match scoring, not the official four-mode scorer.
4
+ English route bypasses translator; its predictions are deliberately shared.
5
+ """
6
+ import argparse, collections, concurrent.futures as cf, csv, hashlib, io, json, os, random, re, subprocess, time, unicodedata, zipfile
7
+ from pathlib import Path
8
+ import requests
9
+
10
+ URL='https://zenodo.org/records/22695092/files/nihatgaribli/AZ-Eval-benchmark-v2.0.1.zip?download=1'
11
+ MD5='d0012917884fbf4f637d9d42d4376953'
12
+ NLLB='facebook/nllb-200-1.3B'
13
+ ARMS=('base_en','base_az','cascade_en','cascade_az')
14
+ INSTRUCTIONS={'en':'Answer with only the short answer, without explanation.','az':'İzah vermədən yalnız qısa cavabı yazın.'}
15
+
16
+ def save(path,obj):
17
+ tmp=path.with_suffix('.tmp'); tmp.write_text(json.dumps(obj,ensure_ascii=False,indent=2),encoding='utf-8'); tmp.replace(path)
18
+
19
+ def read_member(z,name):
20
+ s=z.read(name).decode('utf-8-sig')
21
+ if name.endswith('.jsonl'): return [json.loads(x) for x in s.splitlines() if x.strip()]
22
+ if name.endswith('.csv'): return list(csv.DictReader(io.StringIO(s)))
23
+ if name.endswith('.tsv'): return list(csv.DictReader(io.StringIO(s),delimiter='\t'))
24
+ v=json.loads(s)
25
+ if isinstance(v,dict):
26
+ for k in ('test','data','items','rows','questions'):
27
+ if isinstance(v.get(k),list): return v[k]
28
+ return v
29
+
30
+ def aliases(v):
31
+ if v is None or v=='': return []
32
+ if isinstance(v,str):
33
+ if v.strip().startswith('['):
34
+ try: return aliases(json.loads(v))
35
+ except (ValueError,TypeError): pass
36
+ return [v]
37
+ if isinstance(v,list): return [str(x) for x in v if isinstance(x,(str,int,float))]
38
+ return []
39
+
40
+ def canonical(rows):
41
+ if not isinstance(rows,list) or len(rows)!=1006: raise ValueError('not 1006 rows')
42
+ result=[]
43
+ for x in rows:
44
+ if not isinstance(x,dict): raise ValueError('not record')
45
+ qa,qe=x['question_az'],x['question_en']
46
+ a=x.get('answer_az',x.get('answer')); e=x.get('answer_en')
47
+ if not all(isinstance(v,str) and v.strip() for v in (qa,qe)) or a is None or e is None: raise ValueError('missing parallel gold')
48
+ if 'verified_by' in x and x['verified_by']!='human': raise ValueError('unverified row')
49
+ az=aliases(a)+aliases(x.get('answer_aliases_az',x.get('aliases_az',x.get('answer_aliases'))))
50
+ en=aliases(e)+aliases(x.get('answer_aliases_en',x.get('answer_en_aliases',x.get('aliases_en'))))
51
+ if not az or not en: raise ValueError('empty gold')
52
+ result.append(dict(id=str(x['id']),category=str(x.get('category','unknown')),question_az=qa,question_en=qe,gold_az=list(dict.fromkeys(az)),gold_en=list(dict.fromkeys(en))))
53
+ if len({r['id'] for r in result})!=1006: raise ValueError('duplicate ids')
54
+ return sorted(result,key=lambda r:r['id'])
55
+
56
+ def dataset(out,member):
57
+ p=out/'azeval-v2.0.1.zip'
58
+ if not p.exists():
59
+ r=requests.get(URL,timeout=120); r.raise_for_status(); p.write_bytes(r.content)
60
+ if hashlib.md5(p.read_bytes()).hexdigest()!=MD5: raise RuntimeError('Archive checksum mismatch; remove damaged archive and retry.')
61
+ candidates=[]; inventory=[]
62
+ with zipfile.ZipFile(p) as z:
63
+ for name in z.namelist():
64
+ if not name.endswith(('.jsonl','.json','.csv','.tsv')) or '/data/' not in '/'+name: continue
65
+ if member and name!=member: continue
66
+ try:
67
+ raw=read_member(z,name)
68
+ inventory.append((name,len(raw) if isinstance(raw,list) else None,list(raw[0]) if isinstance(raw,list) and raw and isinstance(raw[0],dict) else None))
69
+ rows=canonical(raw); candidates.append((name,rows))
70
+ except (ValueError,KeyError,TypeError,UnicodeError): continue
71
+ if not candidates:
72
+ print('Archive dataset inventory:',json.dumps(inventory,ensure_ascii=False),flush=True)
73
+ raise RuntimeError('No validated 1006-item parallel dataset found. Send the inventory; no fallback to another version.')
74
+ signatures={hashlib.sha256(json.dumps(rows,ensure_ascii=False,sort_keys=True).encode()).hexdigest() for _,rows in candidates}
75
+ if len(signatures)!=1:
76
+ print('Multiple distinct valid dataset members:',[n for n,_ in candidates],flush=True); raise RuntimeError('Specify --data-member after checking archive.')
77
+ name,rows=candidates[0]; print('Verified dataset:',name,len(rows),flush=True); return name,rows
78
+
79
+ def norm(s):
80
+ s=unicodedata.normalize('NFKC',str(s)).strip()
81
+ # Turkish/Azerbaijani dotted/dotless I case handling. Preserve internal punctuation.
82
+ s=s.replace('İ','i').replace('I','ı').casefold() if any(c in s for c in 'əƏıİğĞşŞçÇöÖüÜ') else s.casefold()
83
+ s=' '.join(s.split()); return s.strip(' \t\n.?!"“”«»')
84
+
85
+ def correct(answer,golds):
86
+ a=norm(answer); return bool(a) and any(a==norm(g) for g in golds)
87
+
88
+ def report(rows,settings,out):
89
+ paired=[r for r in rows if all(a in r for a in ARMS)]
90
+ def group(rr):
91
+ n=len(rr); stats={}
92
+ for a in ARMS:
93
+ k=sum(correct(r[a]['answer'],r['gold_'+a[-2:]]) for r in rr)
94
+ stats[a]={'correct':k,'accuracy':round(100*k/n,3) if n else None,'empty':sum(not r[a]['answer'].strip() for r in rr)}
95
+ stats['n']=n
96
+ if n:
97
+ stats['az_gain_pp']=round(100*(stats['cascade_az']['correct']-stats['base_az']['correct'])/n,3)
98
+ stats['az_retention_percent']=round(100*stats['cascade_az']['correct']/stats['base_en']['correct'],3) if stats['base_en']['correct'] else None
99
+ stats['base_only_az_correct']=sum(correct(r['base_az']['answer'],r['gold_az']) and not correct(r['cascade_az']['answer'],r['gold_az']) for r in rr)
100
+ stats['cascade_only_az_correct']=sum(correct(r['cascade_az']['answer'],r['gold_az']) and not correct(r['base_az']['answer'],r['gold_az']) for r in rr)
101
+ return stats
102
+ s={'settings':settings,'target_n':len(rows),'overall':group(paired),'categories':{c:group([r for r in paired if r['category']==c]) for c in sorted({r['category'] for r in rows})}}
103
+ save(out/'summary.json',s); print(json.dumps(s['overall'],ensure_ascii=False),flush=True)
104
+
105
+ def env_for(exe):
106
+ env=os.environ.copy(); dirs=[str(exe.parent),*sorted({str(p.parent) for p in exe.parent.rglob('*.so*')}),'/usr/local/cuda/lib64',env.get('LD_LIBRARY_PATH','')]; env['LD_LIBRARY_PATH']=os.pathsep.join(dict.fromkeys(dirs)); return env
107
+
108
+ def answer_message(m):
109
+ reason=m.get('reasoning_content') or ''; ans=m.get('content') or ''
110
+ close=r'</(?:ifm\|think\w*|think)>'
111
+ if re.search(close,reason): ans=re.split(close,reason+ans)[-1]
112
+ elif re.search(close,ans): ans=re.split(close,ans)[-1]
113
+ if re.search(r'<(?:ifm\|think\w*|think)>',ans): return ''
114
+ return ans.strip()
115
+
116
+ def ask(prompt,port):
117
+ start=time.monotonic()
118
+ body={'model':'k2-horizon','messages':[{'role':'user','content':prompt}], 'temperature':0.0,'seed':42,'max_tokens':1024,'stream':False,'chat_template_kwargs':{'reasoning_effort':'low'}}
119
+ r=requests.post(f'http://127.0.0.1:{port}/v1/chat/completions',json=body,timeout=2400); r.raise_for_status(); data=r.json(); choice=data['choices'][0]
120
+ return {'prompt':prompt,'answer':answer_message(choice['message']),'finish_reason':choice.get('finish_reason'),'raw_message':choice['message'],'usage':data.get('usage'),'seconds':round(time.monotonic()-start,3)}
121
+
122
+ def main():
123
+ p=argparse.ArgumentParser(); p.add_argument('--k2-dir',type=Path,default=Path('/content/k2')); p.add_argument('--out',type=Path,default=Path('/content/k2_azeval_v2')); p.add_argument('--limit',type=int,default=1006); p.add_argument('--parallel',type=int,default=2,choices=(1,2,4)); p.add_argument('--batch',type=int,default=8); p.add_argument('--port',type=int,default=8087); p.add_argument('--data-member'); args=p.parse_args()
124
+ import torch, transformers
125
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
126
+ from huggingface_hub import HfApi
127
+ if not torch.cuda.is_available(): raise RuntimeError('Enable Colab GPU.')
128
+ if not 1<=args.limit<=1006 or args.batch<1: raise ValueError('invalid limit/batch')
129
+ out=args.out; out.mkdir(parents=True,exist_ok=True); path=out/'results.json'
130
+ member,rows=dataset(out,args.data_member); random.Random(42).shuffle(rows); rows=rows[:args.limit]
131
+ server=next(args.k2_dir.rglob('llama-server'),None); gguf=next(args.k2_dir.rglob('K2-Horizon-4B-Q4_K_M.gguf'),None)
132
+ if not server or not gguf: raise FileNotFoundError('Official K2 server/model missing.')
133
+ env=env_for(server); version=subprocess.check_output([str(server),'--version'],env=env,cwd=server.parent,stderr=subprocess.STDOUT,text=True)
134
+ if '11619' not in version: raise RuntimeError('Expected build b11619: '+version)
135
+ old=json.loads(path.read_text()) if path.exists() else None
136
+ rev=old['settings']['nllb_revision'] if old else HfApi().model_info(NLLB).sha
137
+ with gguf.open('rb') as f: sha=hashlib.file_digest(f,'sha256').hexdigest()
138
+ settings=dict(dataset='AZ-Eval v2.0.1',doi='10.5281/zenodo.22695092',archive_md5=MD5,member=member,limit=args.limit,seed=42,nllb=NLLB,nllb_revision=rev,model_file=gguf.name,model_sha256=sha,runtime=version.strip(),context_per_slot=4096,parallel=args.parallel,temperature=0,reasoning_effort='low',max_tokens=1024,nllb_dtype='float16',beams=4,translation_max_new_tokens=512,translation_batch=args.batch,torch=str(torch.__version__),transformers=transformers.__version__,scoring='local normalized exact match with language-specific reference aliases; not official scorer',english_route='identity; reuse base_en',instructions=INSTRUCTIONS)
139
+ if old:
140
+ if old['settings']!=settings or [r['id'] for r in old['rows']]!=[r['id'] for r in rows]: raise RuntimeError('Settings changed: use same arguments or new --out.')
141
+ rows=old['rows']
142
+ def checkpoint(): save(path,{'settings':settings,'rows':rows})
143
+ checkpoint()
144
+ tok=AutoTokenizer.from_pretrained(NLLB,revision=rev,src_lang='azj_Latn')
145
+ model=AutoModelForSeq2SeqLM.from_pretrained(NLLB,revision=rev,torch_dtype=torch.float16,low_cpu_mem_usage=True,device_map={'':'cuda:0'}).eval()
146
+ @torch.inference_mode()
147
+ def translate(texts,src,tgt):
148
+ result=list(texts); active=[i for i,t in enumerate(texts) if t.strip() and not re.fullmatch(r'[+-]?\d+(?:[.,]\d+)?',t.strip())]
149
+ if active:
150
+ tok.src_lang=src
151
+ x=tok([texts[i] for i in active],padding=True,truncation=False,return_tensors='pt').to('cuda:0')
152
+ if x.input_ids.shape[1]>1024: raise ValueError('Translation input exceeds limit; no silent truncation.')
153
+ y=model.generate(**x,forced_bos_token_id=tok.convert_tokens_to_ids(tgt),num_beams=4,do_sample=False,max_new_tokens=512)
154
+ if y.shape[1]>=513: raise RuntimeError('Translation reached token cap; inspect.')
155
+ for i,t in zip(active,tok.batch_decode(y,skip_special_tokens=True)): result[i]=t.strip()
156
+ return result
157
+ log=(out/'server.log').open('w')
158
+ command=[str(server),'-m',str(gguf),'-ngl','99','-c',str(4096*args.parallel),'--parallel',str(args.parallel),'--jinja','--chat-template-kwargs','{"reasoning_effort":"low"}','--host','127.0.0.1','--port',str(args.port)]
159
+ proc=subprocess.Popen(command,env=env,cwd=server.parent,stdout=log,stderr=subprocess.STDOUT,stdin=subprocess.DEVNULL)
160
+ try:
161
+ for _ in range(240):
162
+ if proc.poll() is not None: raise RuntimeError('K2 server exited; see server.log')
163
+ try:
164
+ if requests.get(f'http://127.0.0.1:{args.port}/health',timeout=2).status_code==200: break
165
+ except requests.RequestException: pass
166
+ time.sleep(1)
167
+ else: raise RuntimeError('K2 server not ready; see server.log')
168
+ print('Server ready. Starting paired evaluation.',flush=True)
169
+ with cf.ThreadPoolExecutor(max_workers=args.parallel) as pool:
170
+ for offset in range(0,len(rows),args.batch):
171
+ block=rows[offset:offset+args.batch]
172
+ pending=[r for r in block if 'translated_question' not in r]
173
+ if pending:
174
+ t=time.monotonic(); tr=translate([r['question_az'] for r in pending],'azj_Latn','eng_Latn'); elapsed=time.monotonic()-t
175
+ for r,s in zip(pending,tr): r['translated_question']=s; r['forward_batch_seconds']=elapsed; r['forward_batch_size']=len(pending)
176
+ checkpoint()
177
+ tasks={}
178
+ for r in block:
179
+ for a,q,lang in [('base_en',r['question_en'],'en'),('base_az',r['question_az'],'az'),('cascade_internal',r['translated_question'],'en')]:
180
+ if a not in r: tasks[pool.submit(ask,q+'\n'+INSTRUCTIONS[lang],args.port)]=(r,a)
181
+ for f in cf.as_completed(tasks):
182
+ r,a=tasks[f]; r[a]=f.result()
183
+ if a=='base_en': r['cascade_en']={**r[a],'reused_base_en':True}
184
+ checkpoint()
185
+ for r in block:
186
+ if 'cascade_en' not in r: r['cascade_en']={**r['base_en'],'reused_base_en':True}
187
+ pending=[r for r in block if 'cascade_az' not in r]
188
+ if pending:
189
+ t=time.monotonic(); tr=translate([r['cascade_internal']['answer'] for r in pending],'eng_Latn','azj_Latn'); elapsed=time.monotonic()-t
190
+ for r,s in zip(pending,tr): r['cascade_az']={'answer':s,'back_batch_seconds':elapsed,'back_batch_size':len(pending)}
191
+ checkpoint(); report(rows,settings,out)
192
+ finally:
193
+ proc.terminate()
194
+ try: proc.wait(timeout=15)
195
+ except subprocess.TimeoutExpired: proc.kill(); proc.wait()
196
+ log.close()
197
+ report(rows,settings,out)
198
+
199
+ if __name__=='__main__': main()
benchmarks/azeval_partial_48.json ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "status": "partial; transcribed from observed Colab stdout, not the raw prediction file",
3
+ "dataset": "AZ-Eval v2.0.1",
4
+ "target_n": 1006,
5
+ "scoring": "local normalized exact match; not official scoring",
6
+ "english_route": "shared prediction, no independent second run",
7
+ "overall": {
8
+ "base_en": {
9
+ "correct": 13,
10
+ "accuracy": 27.083,
11
+ "empty": 0
12
+ },
13
+ "base_az": {
14
+ "correct": 2,
15
+ "accuracy": 4.167,
16
+ "empty": 0
17
+ },
18
+ "cascade_en": {
19
+ "correct": 13,
20
+ "accuracy": 27.083,
21
+ "empty": 0
22
+ },
23
+ "cascade_az": {
24
+ "correct": 11,
25
+ "accuracy": 22.917,
26
+ "empty": 0
27
+ },
28
+ "n": 48,
29
+ "az_gain_pp": 18.75,
30
+ "az_retention_percent": 84.615,
31
+ "base_only_az_correct": 1,
32
+ "cascade_only_az_correct": 10
33
+ },
34
+ "observed_progress": [
35
+ {
36
+ "base_en": {
37
+ "correct": 8,
38
+ "accuracy": 25.0,
39
+ "empty": 0
40
+ },
41
+ "base_az": {
42
+ "correct": 1,
43
+ "accuracy": 3.125,
44
+ "empty": 0
45
+ },
46
+ "cascade_en": {
47
+ "correct": 8,
48
+ "accuracy": 25.0,
49
+ "empty": 0
50
+ },
51
+ "cascade_az": {
52
+ "correct": 7,
53
+ "accuracy": 21.875,
54
+ "empty": 0
55
+ },
56
+ "n": 32,
57
+ "az_gain_pp": 18.75,
58
+ "az_retention_percent": 87.5,
59
+ "base_only_az_correct": 1,
60
+ "cascade_only_az_correct": 7
61
+ },
62
+ {
63
+ "base_en": {
64
+ "correct": 11,
65
+ "accuracy": 27.5,
66
+ "empty": 0
67
+ },
68
+ "base_az": {
69
+ "correct": 1,
70
+ "accuracy": 2.5,
71
+ "empty": 0
72
+ },
73
+ "cascade_en": {
74
+ "correct": 11,
75
+ "accuracy": 27.5,
76
+ "empty": 0
77
+ },
78
+ "cascade_az": {
79
+ "correct": 9,
80
+ "accuracy": 22.5,
81
+ "empty": 0
82
+ },
83
+ "n": 40,
84
+ "az_gain_pp": 20.0,
85
+ "az_retention_percent": 81.818,
86
+ "base_only_az_correct": 1,
87
+ "cascade_only_az_correct": 9
88
+ },
89
+ {
90
+ "base_en": {
91
+ "correct": 13,
92
+ "accuracy": 27.083,
93
+ "empty": 0
94
+ },
95
+ "base_az": {
96
+ "correct": 2,
97
+ "accuracy": 4.167,
98
+ "empty": 0
99
+ },
100
+ "cascade_en": {
101
+ "correct": 13,
102
+ "accuracy": 27.083,
103
+ "empty": 0
104
+ },
105
+ "cascade_az": {
106
+ "correct": 11,
107
+ "accuracy": 22.917,
108
+ "empty": 0
109
+ },
110
+ "n": 48,
111
+ "az_gain_pp": 18.75,
112
+ "az_retention_percent": 84.615,
113
+ "base_only_az_correct": 1,
114
+ "cascade_only_az_correct": 10
115
+ }
116
+ ],
117
+ "note": "run timed out after 48 fully paired questions; no category or item-level results available in this release"
118
+ }
inference.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Experimental text cascade. No weight modifications. Requires CUDA and K2 server build b11619."""
2
+ import argparse, json, re, subprocess, time
3
+ from pathlib import Path
4
+ import requests
5
+ import torch
6
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
7
+ from benchmark import NLLB, INSTRUCTIONS, ask, env_for
8
+
9
+ class MultilingualReasoner:
10
+ def __init__(self, port=8087, revision=None):
11
+ self.port = port
12
+ self.tokenizer = AutoTokenizer.from_pretrained(NLLB, revision=revision, src_lang='azj_Latn')
13
+ self.model = AutoModelForSeq2SeqLM.from_pretrained(NLLB, revision=revision,
14
+ torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map={'':'cuda:0'}).eval()
15
+
16
+ @torch.inference_mode()
17
+ def translate(self, text, src, tgt):
18
+ if src == tgt or not text.strip() or re.fullmatch(r'[+-]?\d+(?:[.,]\d+)?',text.strip()):
19
+ return text
20
+ self.tokenizer.src_lang = src
21
+ x = self.tokenizer([text], padding=True, truncation=False, return_tensors='pt').to('cuda:0')
22
+ if x.input_ids.shape[1] > 1024:
23
+ raise ValueError('Translation input exceeds limit.')
24
+ bos = self.tokenizer.convert_tokens_to_ids(tgt)
25
+ if bos == self.tokenizer.unk_token_id:
26
+ raise ValueError('Unsupported NLLB target language code: '+tgt)
27
+ y = self.model.generate(**x, forced_bos_token_id=bos, num_beams=4, do_sample=False, max_new_tokens=512)
28
+ if y.shape[1] >= 513:
29
+ raise RuntimeError('Translation reached token cap.')
30
+ return self.tokenizer.batch_decode(y,skip_special_tokens=True)[0].strip()
31
+
32
+ def answer(self, question, language='azj_Latn', short_answer=False):
33
+ if language != 'eng_Latn' and self.tokenizer.convert_tokens_to_ids(language) == self.tokenizer.unk_token_id:
34
+ raise ValueError('Unsupported NLLB source language code: '+language)
35
+ en = self.translate(question,language,'eng_Latn')
36
+ prompt = en + ('\n'+INSTRUCTIONS['en'] if short_answer else '')
37
+ response = ask(prompt,self.port)
38
+ result = self.translate(response['answer'],'eng_Latn',language)
39
+ return {'question':question,'language':language,'translated_question':en,'english_answer':response['answer'],'answer':result,'finish_reason':response['finish_reason'],'k2_seconds':response['seconds']}
40
+
41
+ def main():
42
+ p=argparse.ArgumentParser(); p.add_argument('--k2-dir',type=Path,default=Path('/content/k2')); p.add_argument('--language',default='azj_Latn'); p.add_argument('--question'); p.add_argument('--short-answer',action='store_true'); p.add_argument('--port',type=int,default=8087); p.add_argument('--revision'); a=p.parse_args()
43
+ if not torch.cuda.is_available(): raise RuntimeError('CUDA GPU required by this reference implementation.')
44
+ server=next(a.k2_dir.rglob('llama-server'),None); gguf=next(a.k2_dir.rglob('K2-Horizon-4B-Q4_K_M.gguf'),None)
45
+ if not server or not gguf: raise FileNotFoundError('Install K2 using the README first.')
46
+ env=env_for(server)
47
+ version=subprocess.check_output([str(server),'--version'],env=env,cwd=server.parent,stderr=subprocess.STDOUT,text=True)
48
+ if '11619' not in version: raise RuntimeError('Expected build b11619: '+version)
49
+ engine=MultilingualReasoner(a.port,a.revision)
50
+ with open('inference_server.log','w') as log:
51
+ proc=subprocess.Popen([str(server),'-m',str(gguf),'-ngl','99','-c','4096','--parallel','1','--jinja','--chat-template-kwargs','{"reasoning_effort":"low"}','--host','127.0.0.1','--port',str(a.port)],env=env,cwd=server.parent,stdout=log,stderr=subprocess.STDOUT,stdin=subprocess.DEVNULL)
52
+ try:
53
+ for _ in range(240):
54
+ if proc.poll() is not None: raise RuntimeError('K2 server exited; inspect inference_server.log')
55
+ try:
56
+ if requests.get(f'http://127.0.0.1:{a.port}/health',timeout=2).status_code==200: break
57
+ except requests.RequestException: pass
58
+ time.sleep(1)
59
+ else: raise RuntimeError('K2 server not ready.')
60
+ if a.question: print(json.dumps(engine.answer(a.question,a.language,a.short_answer),ensure_ascii=False,indent=2))
61
+ else:
62
+ while True:
63
+ try: q=input('Question (empty to exit): ').strip()
64
+ except EOFError: break
65
+ if not q: break
66
+ print(json.dumps(engine.answer(q,a.language,a.short_answer),ensure_ascii=False,indent=2))
67
+ finally:
68
+ proc.terminate()
69
+ try: proc.wait(timeout=15)
70
+ except subprocess.TimeoutExpired: proc.kill(); proc.wait()
71
+
72
+ if __name__=='__main__': main()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ accelerate
4
+ sentencepiece
5
+ requests
6
+ huggingface_hub