Document final route coverage and include supplemental preprocessing sources
Browse files- LICENSES.md +8 -0
- README.md +17 -2
- convert.py +104 -0
- refs/motif-3-handoff/reproduction/calibration/build_calibration.py +465 -0
- refs/solar-data/scripts/solar_format.py +305 -0
LICENSES.md
CHANGED
|
@@ -13,3 +13,11 @@ Apache-2.0 license for the data.
|
|
| 13 |
|
| 14 |
Text windows and media preprocessing are modifications for Inkling calibration.
|
| 15 |
All source attributions, third-party rights and applicable source terms remain.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
Text windows and media preprocessing are modifications for Inkling calibration.
|
| 15 |
All source attributions, third-party rights and applicable source terms remain.
|
| 16 |
+
|
| 17 |
+
The structured-dialog supplement additionally uses these exact revisions:
|
| 18 |
+
|
| 19 |
+
- NVIDIA Nemotron Cascade SFT Stage 2: `54cfa23ba28c9d94aeae15142e73bde6f8d14d8b`, `tool_calling.jsonl`.
|
| 20 |
+
- NVIDIA Nemotron SFT Instruction Following Chat v2: `1a9454ed054b8544503ab8d8c0a519d141a44c5b`, `data/reasoning_on.jsonl`.
|
| 21 |
+
|
| 22 |
+
Their source terms remain applicable. GPL-3.0 and Apache-2.0 license texts
|
| 23 |
+
are included in `licenses/`; the source links above identify other terms.
|
README.md
CHANGED
|
@@ -49,8 +49,10 @@ The primary balanced pass is:
|
|
| 49 |
| Total | 1,462 | 1,049,129 | 100% |
|
| 50 |
|
| 51 |
A subsequent coverage pass added 201 real structured reasoning/tool conversations
|
| 52 |
-
(529,126 tokens, seed 3408, up to 4,096 tokens per sample). It
|
| 53 |
-
experts, including L41 expert 123 which
|
|
|
|
|
|
|
| 54 |
These are normalized from the pinned NVIDIA Instruction-Following-Chat-v2
|
| 55 |
reasoning_on and Cascade-SFT-Stage-2 tool_calling sources and rendered with actual
|
| 56 |
Inkling thinking/tool syntax. Total actual input: **1,578,255 tokens**.
|
|
@@ -116,3 +118,16 @@ is recorded with the reproduction materials and model handoff.
|
|
| 116 |
|
| 117 |
See [LICENSES.md](LICENSES.md). Source-specific licenses remain applicable;
|
| 118 |
this collection does not relicense its constituent examples.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
| Total | 1,462 | 1,049,129 | 100% |
|
| 50 |
|
| 51 |
A subsequent coverage pass added 201 real structured reasoning/tool conversations
|
| 52 |
+
(529,126 tokens, seed 3408, up to 4,096 tokens per sample). It probes rare
|
| 53 |
+
experts, including L41 expert 123, which remained unobserved after both passes.
|
| 54 |
+
The final model protects L40–41 with Q4_K; expert 123 uses ordinary Q4_K
|
| 55 |
+
without fabricated importance data.
|
| 56 |
These are normalized from the pinned NVIDIA Instruction-Following-Chat-v2
|
| 57 |
reasoning_on and Cascade-SFT-Stage-2 tool_calling sources and rendered with actual
|
| 58 |
Inkling thinking/tool syntax. Total actual input: **1,578,255 tokens**.
|
|
|
|
| 118 |
|
| 119 |
See [LICENSES.md](LICENSES.md). Source-specific licenses remain applicable;
|
| 120 |
this collection does not relicense its constituent examples.
|
| 121 |
+
|
| 122 |
+
## Rebuilding and replay
|
| 123 |
+
|
| 124 |
+
For exact replay, download the published tensor packs and use the index above.
|
| 125 |
+
`build_samples.py` reconstructs the primary pack from source media and the
|
| 126 |
+
checksum-pinned K2 text pools; those historical pool files are retained in the
|
| 127 |
+
owner’s earlier private handoff. `build_supplement.py` reconstructs the added
|
| 128 |
+
structured dialogs; its two source dataset revisions and raw row hashes are
|
| 129 |
+
in `manifest.json`. The normalizer helpers are under `refs/`.
|
| 130 |
+
Set `INKLING_ROOT` to the prepared work tree, with tokenizer/processor files
|
| 131 |
+
in `source/`, source media under `calibration/`, and the helpers in `refs/`.
|
| 132 |
+
The pinned Transformers commit is in `provenance/toolchain.json`. Exact input
|
| 133 |
+
replay does not require access to the private historical text pools.
|
convert.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Lossless source-layout GGUF container plus per-role GGML quantization.
|
| 3 |
+
|
| 4 |
+
Names and interleaved gate/up row ordering remain identical to the source.
|
| 5 |
+
No row permutation, expert removal, or implicit precision fallback is allowed.
|
| 6 |
+
"""
|
| 7 |
+
import argparse, collections, ctypes, hashlib, json, math, re, time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import numpy as np
|
| 10 |
+
import gguf
|
| 11 |
+
|
| 12 |
+
ROOT=Path(__import__('os').environ.get('INKLING_ROOT', '/inkling'))
|
| 13 |
+
LAYOUT={'BF16':(30,1,2),'F32':(0,1,4),'Q8_0':(8,32,34),'IQ2_XXS':(16,256,66),'Q2_K':(10,256,84),'Q4_K':(12,256,144)}
|
| 14 |
+
|
| 15 |
+
def policy(name, dtype, variant):
|
| 16 |
+
if variant=='BF16' or name.startswith('model.mtp.'):
|
| 17 |
+
return dtype
|
| 18 |
+
if '.mlp.experts.' in name:
|
| 19 |
+
if variant=='Q8_0': return 'Q8_0'
|
| 20 |
+
if int(name.split('.')[3])==2: return dtype
|
| 21 |
+
if variant=='MQ89' and int(name.split('.')[3])>=40: return 'Q4_K'
|
| 22 |
+
return 'IQ2_XXS' if 'w13' in name else 'Q2_K'
|
| 23 |
+
if name in ('model.llm.embed.weight','model.llm.unembed.weight') or '.mlp.shared_experts.' in name or re.search(r'layers\.[01]\.mlp\.w',name):
|
| 24 |
+
return 'Q8_0'
|
| 25 |
+
return dtype
|
| 26 |
+
|
| 27 |
+
def inventory(variant, mtp=False):
|
| 28 |
+
meta=json.load(open(ROOT/'refs/safetensors-metadata.json'))
|
| 29 |
+
out=[]
|
| 30 |
+
for file, fm in meta['files_metadata'].items():
|
| 31 |
+
for name,t in fm['tensors'].items():
|
| 32 |
+
if name.startswith('model.mtp.') != mtp: continue
|
| 33 |
+
typ=policy(name,t['dtype'],variant); code,block,size=LAYOUT[typ]
|
| 34 |
+
if typ not in ('BF16','F32'): assert t['shape'][-1]%block==0, name
|
| 35 |
+
out.append(dict(name=name,shape=t['shape'],dtype=t['dtype'],type=typ,file=file,source_offsets=t['data_offsets'],bytes=math.prod(t['shape'])//block*size))
|
| 36 |
+
return sorted(out,key=lambda t:t['name'])
|
| 37 |
+
|
| 38 |
+
def header_size(path):
|
| 39 |
+
with open(path,'rb') as f: return int.from_bytes(f.read(8),'little')+8
|
| 40 |
+
|
| 41 |
+
def source_array(t, source):
|
| 42 |
+
return np.memmap(source/t['file'],mode='r',dtype='<u2' if t['dtype']=='BF16' else '<f4',offset=header_size(source/t['file'])+t['source_offsets'][0],shape=tuple(t['shape']))
|
| 43 |
+
|
| 44 |
+
def main():
|
| 45 |
+
p=argparse.ArgumentParser(); p.add_argument('--variant',choices=['BF16','Q8_0','MQ85','MQ89'],required=True); p.add_argument('--mtp',action='store_true'); p.add_argument('--plan',action='store_true');p.add_argument('--threads',type=int,default=64);p.add_argument('--imatrix',type=Path);args=p.parse_args()
|
| 46 |
+
ts=inventory(args.variant,args.mtp); tag='MTP-BF16' if args.mtp else args.variant
|
| 47 |
+
outdir=ROOT/'artifacts'/tag;outdir.mkdir(exist_ok=True)
|
| 48 |
+
counts=collections.Counter()
|
| 49 |
+
for t in ts: counts[t['type']]+=t['bytes']
|
| 50 |
+
plan={'variant':tag,'tensor_count':len(ts),'payload_bytes':sum(counts.values()),'payload_gib':sum(counts.values())/2**30,'type_bytes':dict(counts),'tensors':ts}
|
| 51 |
+
(outdir/'tensor-plan.json').write_text(json.dumps(plan,indent=2));print(json.dumps({k:v for k,v in plan.items() if k!='tensors'}),flush=True)
|
| 52 |
+
if args.plan:return
|
| 53 |
+
if list(outdir.glob('*.gguf')):raise RuntimeError('Output exists; refusing overwrite')
|
| 54 |
+
if args.variant in ('MQ85','MQ89') and not args.imatrix:raise RuntimeError('Measured imatrix required')
|
| 55 |
+
imp=np.load(args.imatrix) if args.imatrix else None
|
| 56 |
+
writer=gguf.GGUFWriter(outdir/f'Inkling-Small-{tag}.gguf','inkling',split_max_size=16*2**30)
|
| 57 |
+
writer.add_name(f'Inkling-Small {tag}')
|
| 58 |
+
writer.add_string('inkling.tensor_layout','source-interleaved-v1')
|
| 59 |
+
writer.add_string('inkling.config.json',(ROOT/'source/config.json').read_text())
|
| 60 |
+
writer.add_string('inkling.quantization.recipe',tag)
|
| 61 |
+
writer.add_string('general.source.huggingface.repository','thinkingmachines/Inkling-Small')
|
| 62 |
+
writer.add_string('general.source.huggingface.revision',json.load(open(ROOT/'refs/source-manifest.json'))['revision'])
|
| 63 |
+
writer.add_string('inkling.tokenizer.json',(ROOT/'source/tokenizer.json').read_text())
|
| 64 |
+
writer.add_string('inkling.tokenizer_config.json',(ROOT/'source/tokenizer_config.json').read_text())
|
| 65 |
+
writer.add_chat_template((ROOT/'source/chat_template.jinja').read_text())
|
| 66 |
+
writer.add_string('inkling.processor_config.json',(ROOT/'source/processor_config.json').read_text())
|
| 67 |
+
writer.add_bool('inkling.mtp.sidecar',args.mtp)
|
| 68 |
+
if imp:
|
| 69 |
+
writer.add_string('inkling.imatrix.sha256',hashlib.sha256(args.imatrix.read_bytes()).hexdigest())
|
| 70 |
+
for t in ts:
|
| 71 |
+
writer.add_tensor_info(t['name'],t['shape'],np.dtype('float32'),t['bytes'],raw_dtype=gguf.GGMLQuantizationType(LAYOUT[t['type']][0]))
|
| 72 |
+
writer.write_header_to_file();writer.write_kv_data_to_file();writer.write_ti_data_to_file()
|
| 73 |
+
lib=ctypes.CDLL(str(ROOT/'artifacts/libinkling_quant.so'));fn=lib.quant_bf16
|
| 74 |
+
fn.argtypes=[ctypes.c_void_p,ctypes.c_void_p,ctypes.c_int64,ctypes.c_int64,ctypes.c_int64,ctypes.c_int,ctypes.c_void_p,ctypes.c_int];fn.restype=ctypes.c_int
|
| 75 |
+
started=time.time();fallbacks=[]
|
| 76 |
+
for i,t in enumerate(ts):
|
| 77 |
+
src=source_array(t,ROOT/'source')
|
| 78 |
+
if t['type'] in ('BF16','F32'):data=src
|
| 79 |
+
else:
|
| 80 |
+
assert t['dtype']=='BF16'
|
| 81 |
+
shape=t['shape']; experts=math.prod(shape[:-2]);rows,cols=shape[-2:]
|
| 82 |
+
importance=None
|
| 83 |
+
if t['type'] in ('IQ2_XXS','Q2_K','Q4_K'):
|
| 84 |
+
importance=np.ascontiguousarray(imp[t['name']],dtype=np.float32)
|
| 85 |
+
assert importance.shape==(experts,cols), (t['name'],importance.shape)
|
| 86 |
+
assert np.isfinite(importance).all() and (importance>=0).all(),t['name']
|
| 87 |
+
observed=(importance.sum(-1)>0)
|
| 88 |
+
assert ((importance>0).all(-1)|~observed).all(),t['name']
|
| 89 |
+
if not observed.all():assert t['type']=='Q4_K' and int(t['name'].split('.')[3])>=40,t['name']
|
| 90 |
+
data=np.empty(t['bytes'],dtype=np.uint8)
|
| 91 |
+
if importance is not None and not observed.all():
|
| 92 |
+
for e in range(experts):
|
| 93 |
+
iptr=importance[e].ctypes.data if observed[e] else None
|
| 94 |
+
assert fn(src[e].ctypes.data,data.ctypes.data+e*(t['bytes']//experts),1,rows,cols,LAYOUT[t['type']][0],iptr,args.threads)==0
|
| 95 |
+
if not observed[e]:fallbacks.append({'tensor':t['name'],'expert':e,'type':'Q4_K','importance':'none; unobserved, higher-precision quantization'})
|
| 96 |
+
else:
|
| 97 |
+
assert fn(src.ctypes.data,data.ctypes.data,experts,rows,cols,LAYOUT[t['type']][0],importance.ctypes.data if importance is not None else None,args.threads)==0
|
| 98 |
+
writer.write_tensor_data(data)
|
| 99 |
+
print(f'{i+1}/{len(ts)} {t["name"]} {t["type"]} {t["bytes"]} elapsed={time.time()-started:.1f}',flush=True)
|
| 100 |
+
del src,data
|
| 101 |
+
writer.close()
|
| 102 |
+
(outdir/'conversion-complete.json').write_text(json.dumps({'seconds':time.time()-started,'tensor_count':len(ts),'unobserved_q4_fallbacks':fallbacks},indent=2))
|
| 103 |
+
|
| 104 |
+
if __name__=='__main__':main()
|
refs/motif-3-handoff/reproduction/calibration/build_calibration.py
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build Motif 3 imatrix text from the audited Solar mixed-quant composition.
|
| 3 |
+
|
| 4 |
+
The source buckets, files, revisions, shares, and seed are fixed. Records are
|
| 5 |
+
normalized with the checksum-pinned Healing Mix normalizer, then rendered by
|
| 6 |
+
the official Motif 3 chat template and counted with the official tokenizer.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import hashlib
|
| 13 |
+
import importlib.util
|
| 14 |
+
import json
|
| 15 |
+
import random
|
| 16 |
+
import sys
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any
|
| 20 |
+
|
| 21 |
+
import requests
|
| 22 |
+
from huggingface_hub import HfApi, get_token, hf_hub_url
|
| 23 |
+
|
| 24 |
+
SOURCE_MODEL = "Motif-Technologies/Motif-3"
|
| 25 |
+
SOURCE_REVISION = "ccceb1a5fd7b5eb32e47841216b3caf5666c07bc"
|
| 26 |
+
REFERENCE_DATASET = "Baekpica/Solar-Open2-120B-A15B-REAM-148E-Healing-Mix"
|
| 27 |
+
REFERENCE_REVISION = "1931f3a40cc3463217f9c7d25906f80ded029264"
|
| 28 |
+
NORMALIZER_SHA256 = "677274f0d6a93326aa3d76e99e0d251d499317fa455dfb7eefed8fbc93ad1b93"
|
| 29 |
+
MIN_BUCKET_COVERAGE = 0.98
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass(frozen=True)
|
| 33 |
+
class Bucket:
|
| 34 |
+
name: str
|
| 35 |
+
repo: str
|
| 36 |
+
revision: str
|
| 37 |
+
files: tuple[str, ...]
|
| 38 |
+
share: float
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
BUCKETS = (
|
| 42 |
+
Bucket(
|
| 43 |
+
"if_chat",
|
| 44 |
+
"nvidia/Nemotron-SFT-Instruction-Following-Chat-v2",
|
| 45 |
+
"1a9454ed054b8544503ab8d8c0a519d141a44c5b",
|
| 46 |
+
("data/reasoning_on.jsonl", "data/reasoning_off.jsonl"),
|
| 47 |
+
0.22,
|
| 48 |
+
),
|
| 49 |
+
Bucket(
|
| 50 |
+
"cascade1_reasoning",
|
| 51 |
+
"nvidia/Nemotron-Cascade-SFT-Stage-1",
|
| 52 |
+
"e59a356b107737562f064ec252e6adacbc737899",
|
| 53 |
+
("general.jsonl", "science.jsonl", "math/math_1.jsonl", "code/code_1.jsonl"),
|
| 54 |
+
0.16,
|
| 55 |
+
),
|
| 56 |
+
Bucket(
|
| 57 |
+
"cascade2_reasoning",
|
| 58 |
+
"nvidia/Nemotron-Cascade-SFT-Stage-2",
|
| 59 |
+
"54cfa23ba28c9d94aeae15142e73bde6f8d14d8b",
|
| 60 |
+
(
|
| 61 |
+
"instruction-following.jsonl",
|
| 62 |
+
"tool_calling.jsonl",
|
| 63 |
+
"general/general_1.jsonl",
|
| 64 |
+
"math/math_1.jsonl",
|
| 65 |
+
"science.jsonl",
|
| 66 |
+
"swe_repair.jsonl",
|
| 67 |
+
"swe_localization.jsonl",
|
| 68 |
+
),
|
| 69 |
+
0.16,
|
| 70 |
+
),
|
| 71 |
+
Bucket(
|
| 72 |
+
"ko",
|
| 73 |
+
"nvidia/Nemotron-SFT-Multilingual-v2",
|
| 74 |
+
"971a252224b75414b1b67c55dbe0446d8b6606a0",
|
| 75 |
+
(
|
| 76 |
+
"ultra-v3_math_ko_translated_final.jsonl",
|
| 77 |
+
"ultra-v3_code_ko_translated_final.jsonl",
|
| 78 |
+
"ultra-v3_stem_ko_translated_postedit_final.jsonl",
|
| 79 |
+
),
|
| 80 |
+
0.16,
|
| 81 |
+
),
|
| 82 |
+
Bucket(
|
| 83 |
+
"multilingual_other",
|
| 84 |
+
"nvidia/Nemotron-SFT-Multilingual-v2",
|
| 85 |
+
"971a252224b75414b1b67c55dbe0446d8b6606a0",
|
| 86 |
+
tuple(
|
| 87 |
+
f"ultra-v3_{domain}_{language}_{suffix}.jsonl"
|
| 88 |
+
for language in ("ja", "pt", "hi")
|
| 89 |
+
for domain, suffix in (
|
| 90 |
+
("math", "translated_final"),
|
| 91 |
+
("code", "translated_final"),
|
| 92 |
+
("stem", "translated_postedit_final"),
|
| 93 |
+
)
|
| 94 |
+
),
|
| 95 |
+
0.12,
|
| 96 |
+
),
|
| 97 |
+
Bucket(
|
| 98 |
+
"finance",
|
| 99 |
+
"nvidia/Nemotron-SpecializedDomains-Finance-v1",
|
| 100 |
+
"5a21b106168facb96ced11b883c2a9b4788ee939",
|
| 101 |
+
("data/train.jsonl",),
|
| 102 |
+
0.06,
|
| 103 |
+
),
|
| 104 |
+
Bucket(
|
| 105 |
+
"swe_agentic",
|
| 106 |
+
"nvidia/Nemotron-SFT-SWE-v2",
|
| 107 |
+
"bd151f3f2d89c4804dda0083d912bd9f6a0a9fb7",
|
| 108 |
+
("data/agentless.jsonl",),
|
| 109 |
+
0.06,
|
| 110 |
+
),
|
| 111 |
+
Bucket(
|
| 112 |
+
"code_algo",
|
| 113 |
+
"nvidia/Nemotron-SFT-Competitive-Programming-v2",
|
| 114 |
+
"778afc98a9e027e10b3cd78020c120e93e142ef2",
|
| 115 |
+
(
|
| 116 |
+
"data/exercism.jsonl",
|
| 117 |
+
"data/text_to_sql.jsonl",
|
| 118 |
+
"data/competitive_programming_python_00.jsonl",
|
| 119 |
+
),
|
| 120 |
+
0.06,
|
| 121 |
+
),
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def parse_args() -> argparse.Namespace:
|
| 126 |
+
parser = argparse.ArgumentParser()
|
| 127 |
+
parser.add_argument("--out", type=Path, required=True)
|
| 128 |
+
parser.add_argument("--tokenizer", type=Path, required=True)
|
| 129 |
+
parser.add_argument("--normalizer", type=Path, required=True)
|
| 130 |
+
parser.add_argument("--total-tokens", type=int, default=4_000_000)
|
| 131 |
+
parser.add_argument("--seed", type=int, default=1234)
|
| 132 |
+
return parser.parse_args()
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def file_sha256(path: Path) -> str:
|
| 136 |
+
digest = hashlib.sha256()
|
| 137 |
+
with path.open("rb") as handle:
|
| 138 |
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
| 139 |
+
digest.update(chunk)
|
| 140 |
+
return digest.hexdigest()
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def load_normalizer(path: Path) -> Any:
|
| 144 |
+
digest = file_sha256(path)
|
| 145 |
+
if digest != NORMALIZER_SHA256:
|
| 146 |
+
raise RuntimeError(f"reference normalizer hash mismatch: {digest}")
|
| 147 |
+
spec = importlib.util.spec_from_file_location("healing_mix_normalizer", path)
|
| 148 |
+
if spec is None or spec.loader is None:
|
| 149 |
+
raise RuntimeError(f"cannot load normalizer: {path}")
|
| 150 |
+
module = importlib.util.module_from_spec(spec)
|
| 151 |
+
spec.loader.exec_module(module)
|
| 152 |
+
return module
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def canonical_to_messages(canonical: dict[str, Any]) -> tuple[list[dict], list[dict] | None]:
|
| 156 |
+
messages: list[dict] = []
|
| 157 |
+
if canonical.get("system"):
|
| 158 |
+
messages.append({"role": "system", "content": canonical["system"]})
|
| 159 |
+
for turn in canonical["turns"]:
|
| 160 |
+
role = turn["role"]
|
| 161 |
+
if role == "assistant":
|
| 162 |
+
message: dict[str, Any] = {
|
| 163 |
+
"role": "assistant",
|
| 164 |
+
"content": turn.get("content", ""),
|
| 165 |
+
}
|
| 166 |
+
if turn.get("reasoning"):
|
| 167 |
+
message["reasoning_content"] = turn["reasoning"]
|
| 168 |
+
if turn.get("tool_calls"):
|
| 169 |
+
message["tool_calls"] = [
|
| 170 |
+
{
|
| 171 |
+
"id": call["id"],
|
| 172 |
+
"type": "function",
|
| 173 |
+
"function": {
|
| 174 |
+
"name": call["name"],
|
| 175 |
+
"arguments": call["arguments"],
|
| 176 |
+
},
|
| 177 |
+
}
|
| 178 |
+
for call in turn["tool_calls"]
|
| 179 |
+
]
|
| 180 |
+
messages.append(message)
|
| 181 |
+
elif role == "tool":
|
| 182 |
+
messages.append(
|
| 183 |
+
{
|
| 184 |
+
"role": "tool",
|
| 185 |
+
"content": turn.get("content", ""),
|
| 186 |
+
"tool_call_id": turn.get("tool_call_id"),
|
| 187 |
+
}
|
| 188 |
+
)
|
| 189 |
+
else:
|
| 190 |
+
messages.append({"role": role, "content": turn.get("content", "")})
|
| 191 |
+
tools = canonical.get("tools")
|
| 192 |
+
if tools:
|
| 193 |
+
tools = [{"type": "function", "function": tool} for tool in tools]
|
| 194 |
+
return messages, tools
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def render_record(record: dict[str, Any], normalizer: Any, tokenizer: Any) -> str | None:
|
| 198 |
+
if isinstance(record.get("messages"), list):
|
| 199 |
+
try:
|
| 200 |
+
canonical = normalizer.normalize(record)
|
| 201 |
+
messages, tools = canonical_to_messages(canonical)
|
| 202 |
+
rendered = tokenizer.apply_chat_template(
|
| 203 |
+
messages,
|
| 204 |
+
tools=tools,
|
| 205 |
+
tokenize=False,
|
| 206 |
+
add_generation_prompt=False,
|
| 207 |
+
enable_thinking=True,
|
| 208 |
+
)
|
| 209 |
+
if len(rendered) >= 150:
|
| 210 |
+
return rendered
|
| 211 |
+
except normalizer.SkipRecord:
|
| 212 |
+
pass
|
| 213 |
+
except (TypeError, ValueError, KeyError, AttributeError):
|
| 214 |
+
pass
|
| 215 |
+
|
| 216 |
+
for key in ("text", "content", "problem", "question", "prompt"):
|
| 217 |
+
value = record.get(key)
|
| 218 |
+
if isinstance(value, str) and len(value.strip()) >= 100:
|
| 219 |
+
return tokenizer.apply_chat_template(
|
| 220 |
+
[{"role": "user", "content": value.strip()}],
|
| 221 |
+
tokenize=False,
|
| 222 |
+
add_generation_prompt=True,
|
| 223 |
+
enable_thinking=True,
|
| 224 |
+
)
|
| 225 |
+
return None
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class Sampler:
|
| 229 |
+
def __init__(self, seed: int, tokenizer: Any, normalizer: Any) -> None:
|
| 230 |
+
token = get_token()
|
| 231 |
+
self.session = requests.Session()
|
| 232 |
+
if token:
|
| 233 |
+
self.session.headers["Authorization"] = f"Bearer {token}"
|
| 234 |
+
self.session.headers["Accept-Encoding"] = "identity"
|
| 235 |
+
self.api = HfApi(token=token)
|
| 236 |
+
self.seed = seed
|
| 237 |
+
self.tokenizer = tokenizer
|
| 238 |
+
self.normalizer = normalizer
|
| 239 |
+
self.file_sizes: dict[tuple[str, str, str], int] = {}
|
| 240 |
+
|
| 241 |
+
def file_size(self, bucket: Bucket, filename: str) -> int:
|
| 242 |
+
key = (bucket.repo, bucket.revision, filename)
|
| 243 |
+
if key not in self.file_sizes:
|
| 244 |
+
info = self.api.dataset_info(
|
| 245 |
+
bucket.repo, revision=bucket.revision, files_metadata=True
|
| 246 |
+
)
|
| 247 |
+
if info.sha != bucket.revision:
|
| 248 |
+
raise RuntimeError(
|
| 249 |
+
f"dataset revision mismatch for {bucket.repo}: {info.sha}"
|
| 250 |
+
)
|
| 251 |
+
for sibling in info.siblings:
|
| 252 |
+
self.file_sizes[(bucket.repo, bucket.revision, sibling.rfilename)] = (
|
| 253 |
+
sibling.size or 0
|
| 254 |
+
)
|
| 255 |
+
return self.file_sizes.get(key, 0)
|
| 256 |
+
|
| 257 |
+
def sample_jsonl(
|
| 258 |
+
self, bucket: Bucket, filename: str, want_tokens: int, *, salt: int
|
| 259 |
+
) -> list[tuple[str, int]]:
|
| 260 |
+
size = self.file_size(bucket, filename)
|
| 261 |
+
if size <= 0 or want_tokens <= 0:
|
| 262 |
+
return []
|
| 263 |
+
url = hf_hub_url(
|
| 264 |
+
bucket.repo,
|
| 265 |
+
filename,
|
| 266 |
+
repo_type="dataset",
|
| 267 |
+
revision=bucket.revision,
|
| 268 |
+
)
|
| 269 |
+
windows = 8
|
| 270 |
+
window_bytes = max(
|
| 271 |
+
1 << 20,
|
| 272 |
+
min(6 << 20, (want_tokens * 12 + windows - 1) // windows),
|
| 273 |
+
)
|
| 274 |
+
rng = random.Random(self.seed + salt)
|
| 275 |
+
starts = [
|
| 276 |
+
min(size - 1, int(size * (index + rng.random() * 0.7) / windows))
|
| 277 |
+
for index in range(windows)
|
| 278 |
+
]
|
| 279 |
+
documents: list[tuple[str, int]] = []
|
| 280 |
+
tokens = 0
|
| 281 |
+
for start in starts:
|
| 282 |
+
if tokens >= want_tokens:
|
| 283 |
+
break
|
| 284 |
+
end = min(size - 1, start + window_bytes - 1)
|
| 285 |
+
if end <= start:
|
| 286 |
+
continue
|
| 287 |
+
try:
|
| 288 |
+
response = self.session.get(
|
| 289 |
+
url,
|
| 290 |
+
headers={"Range": f"bytes={start}-{end}"},
|
| 291 |
+
timeout=300,
|
| 292 |
+
stream=True,
|
| 293 |
+
)
|
| 294 |
+
if response.status_code != 206:
|
| 295 |
+
response.close()
|
| 296 |
+
print(
|
| 297 |
+
f" rejected unbounded response for {filename}: "
|
| 298 |
+
f"HTTP {response.status_code}",
|
| 299 |
+
file=sys.stderr,
|
| 300 |
+
)
|
| 301 |
+
continue
|
| 302 |
+
payload = response.content
|
| 303 |
+
response.close()
|
| 304 |
+
except requests.RequestException as exc:
|
| 305 |
+
print(
|
| 306 |
+
f" range failure {filename}: {type(exc).__name__}",
|
| 307 |
+
file=sys.stderr,
|
| 308 |
+
)
|
| 309 |
+
continue
|
| 310 |
+
|
| 311 |
+
lines = payload.decode("utf-8", "ignore").splitlines()
|
| 312 |
+
if start > 0 and lines:
|
| 313 |
+
lines = lines[1:]
|
| 314 |
+
if end < size - 1 and lines:
|
| 315 |
+
lines = lines[:-1]
|
| 316 |
+
for line in lines:
|
| 317 |
+
try:
|
| 318 |
+
record = json.loads(line)
|
| 319 |
+
except (json.JSONDecodeError, TypeError):
|
| 320 |
+
continue
|
| 321 |
+
if not isinstance(record, dict):
|
| 322 |
+
continue
|
| 323 |
+
rendered = render_record(record, self.normalizer, self.tokenizer)
|
| 324 |
+
if not rendered:
|
| 325 |
+
continue
|
| 326 |
+
rendered = rendered[:32_000]
|
| 327 |
+
count = len(
|
| 328 |
+
self.tokenizer.encode(rendered, add_special_tokens=False)
|
| 329 |
+
)
|
| 330 |
+
if count == 0:
|
| 331 |
+
continue
|
| 332 |
+
documents.append((rendered, count))
|
| 333 |
+
tokens += count
|
| 334 |
+
if tokens >= want_tokens:
|
| 335 |
+
break
|
| 336 |
+
return documents
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def main() -> None:
|
| 340 |
+
args = parse_args()
|
| 341 |
+
if args.total_tokens <= 0:
|
| 342 |
+
raise SystemExit("--total-tokens must be positive")
|
| 343 |
+
if abs(sum(bucket.share for bucket in BUCKETS) - 1.0) > 1e-9:
|
| 344 |
+
raise RuntimeError("calibration shares must sum to 1.0")
|
| 345 |
+
if not args.tokenizer.is_dir():
|
| 346 |
+
raise SystemExit(f"official tokenizer directory missing: {args.tokenizer}")
|
| 347 |
+
if not args.normalizer.is_file():
|
| 348 |
+
raise SystemExit(f"reference normalizer missing: {args.normalizer}")
|
| 349 |
+
|
| 350 |
+
from transformers import AutoTokenizer
|
| 351 |
+
|
| 352 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 353 |
+
args.tokenizer,
|
| 354 |
+
local_files_only=True,
|
| 355 |
+
trust_remote_code=True,
|
| 356 |
+
)
|
| 357 |
+
if tokenizer.vocab_size != 220_160:
|
| 358 |
+
raise RuntimeError(f"Motif tokenizer vocab mismatch: {tokenizer.vocab_size}")
|
| 359 |
+
normalizer = load_normalizer(args.normalizer)
|
| 360 |
+
sampler = Sampler(args.seed, tokenizer, normalizer)
|
| 361 |
+
|
| 362 |
+
corpus: list[str] = []
|
| 363 |
+
buckets_report: list[dict[str, Any]] = []
|
| 364 |
+
for bucket_index, bucket in enumerate(BUCKETS):
|
| 365 |
+
wanted = int(args.total_tokens * bucket.share)
|
| 366 |
+
per_file = max(1, wanted // len(bucket.files))
|
| 367 |
+
sampled: list[tuple[str, int]] = []
|
| 368 |
+
print(
|
| 369 |
+
f"[{bucket.name}] target {wanted / 1e6:.3f}M Motif tokens "
|
| 370 |
+
f"from {bucket.repo}@{bucket.revision[:8]}",
|
| 371 |
+
flush=True,
|
| 372 |
+
)
|
| 373 |
+
for file_index, filename in enumerate(bucket.files):
|
| 374 |
+
sampled.extend(
|
| 375 |
+
sampler.sample_jsonl(
|
| 376 |
+
bucket,
|
| 377 |
+
filename,
|
| 378 |
+
per_file,
|
| 379 |
+
salt=bucket_index * 101 + file_index,
|
| 380 |
+
)
|
| 381 |
+
)
|
| 382 |
+
documents = [document for document, _ in sampled]
|
| 383 |
+
actual_tokens = sum(count for _, count in sampled)
|
| 384 |
+
actual_chars = sum(len(document) for document in documents)
|
| 385 |
+
corpus.extend(documents)
|
| 386 |
+
report = {
|
| 387 |
+
"bucket": bucket.name,
|
| 388 |
+
"share": bucket.share,
|
| 389 |
+
"repo": bucket.repo,
|
| 390 |
+
"revision": bucket.revision,
|
| 391 |
+
"files": list(bucket.files),
|
| 392 |
+
"target_tokens": wanted,
|
| 393 |
+
"tokens": actual_tokens,
|
| 394 |
+
"chars": actual_chars,
|
| 395 |
+
"documents": len(documents),
|
| 396 |
+
"coverage": actual_tokens / wanted,
|
| 397 |
+
"status": (
|
| 398 |
+
"ok" if actual_tokens >= wanted * MIN_BUCKET_COVERAGE else "shortfall"
|
| 399 |
+
),
|
| 400 |
+
}
|
| 401 |
+
buckets_report.append(report)
|
| 402 |
+
print(
|
| 403 |
+
f" {len(documents)} docs, {actual_tokens / 1e6:.3f}M tokens, "
|
| 404 |
+
f"coverage={report['coverage']:.3f}",
|
| 405 |
+
flush=True,
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
shortfalls = [row["bucket"] for row in buckets_report if row["status"] != "ok"]
|
| 409 |
+
if shortfalls:
|
| 410 |
+
raise SystemExit(
|
| 411 |
+
"calibration buckets below 98% of target: " + ", ".join(shortfalls)
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
random.Random(args.seed).shuffle(corpus)
|
| 415 |
+
args.out.parent.mkdir(parents=True, exist_ok=True)
|
| 416 |
+
args.out.write_text(
|
| 417 |
+
"\n\n".join(document.replace("\r", "") for document in corpus) + "\n",
|
| 418 |
+
encoding="utf-8",
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
template_path = args.tokenizer / "chat_template.jinja"
|
| 422 |
+
tokenizer_path = args.tokenizer / "tokenizer.json"
|
| 423 |
+
composition = {
|
| 424 |
+
"schema_version": 1,
|
| 425 |
+
"output": str(args.out),
|
| 426 |
+
"output_sha256": file_sha256(args.out),
|
| 427 |
+
"bytes": args.out.stat().st_size,
|
| 428 |
+
"documents": len(corpus),
|
| 429 |
+
"seed": args.seed,
|
| 430 |
+
"requested_tokens": args.total_tokens,
|
| 431 |
+
"actual_tokens": sum(row["tokens"] for row in buckets_report),
|
| 432 |
+
"source_model": {"repo": SOURCE_MODEL, "revision": SOURCE_REVISION},
|
| 433 |
+
"reference_mix": {
|
| 434 |
+
"dataset": REFERENCE_DATASET,
|
| 435 |
+
"revision": REFERENCE_REVISION,
|
| 436 |
+
"normalizer_sha256": NORMALIZER_SHA256,
|
| 437 |
+
"reuse": "bucket shares, source files, source revisions, record normalization",
|
| 438 |
+
},
|
| 439 |
+
"tokenizer": {
|
| 440 |
+
"class": type(tokenizer).__name__,
|
| 441 |
+
"vocab_size": tokenizer.vocab_size,
|
| 442 |
+
"tokenizer_json_sha256": file_sha256(tokenizer_path),
|
| 443 |
+
},
|
| 444 |
+
"rendering": {
|
| 445 |
+
"template": "official Motif-3 chat_template.jinja",
|
| 446 |
+
"template_sha256": file_sha256(template_path),
|
| 447 |
+
"enable_thinking": True,
|
| 448 |
+
"tools": "preserved where present",
|
| 449 |
+
},
|
| 450 |
+
"buckets": buckets_report,
|
| 451 |
+
}
|
| 452 |
+
composition_path = args.out.with_suffix(".composition.json")
|
| 453 |
+
composition_path.write_text(
|
| 454 |
+
json.dumps(composition, ensure_ascii=False, indent=2) + "\n",
|
| 455 |
+
encoding="utf-8",
|
| 456 |
+
)
|
| 457 |
+
print(
|
| 458 |
+
f"wrote {args.out}: {len(corpus)} docs, "
|
| 459 |
+
f"{args.out.stat().st_size / 1e6:.2f} MB"
|
| 460 |
+
)
|
| 461 |
+
print(f"composition -> {composition_path}")
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
if __name__ == "__main__":
|
| 465 |
+
main()
|
refs/solar-data/scripts/solar_format.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Nemotron 계열 SFT 레코드를 Solar Open 2 chat template 문자열로 렌더하고
|
| 2 |
+
assistant 토큰만 학습 대상으로 남기는 정규화/렌더러.
|
| 3 |
+
|
| 4 |
+
렌더러는 v1 레포의 chat_template.jinja를 그대로 옮긴 것이며
|
| 5 |
+
(provider_system_prompt=false, think_render_option="interleaved",
|
| 6 |
+
add_generation_prompt=false), verify_renderer.py가 jinja 출력과
|
| 7 |
+
바이트 단위 일치를 검증한다.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import re
|
| 14 |
+
|
| 15 |
+
THINK_RE = re.compile(r"^\s*<think>(.*?)</think>\s*", re.DOTALL)
|
| 16 |
+
TOOL_CALL_RE = re.compile(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", re.DOTALL)
|
| 17 |
+
TOOL_RESP_RE = re.compile(r"^\s*<tool_response>(.*?)</tool_response>\s*$", re.DOTALL)
|
| 18 |
+
QWEN_TOOLS_RE = re.compile(r"<tools>\s*(.*?)\s*</tools>", re.DOTALL)
|
| 19 |
+
QWEN_TOOL_SECTION_RE = re.compile(
|
| 20 |
+
r"\n*#+ *Tools\b.*?(?=\Z)", re.DOTALL | re.IGNORECASE
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class SkipRecord(Exception):
|
| 25 |
+
"""정규화할 수 없는 레코드."""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# --------------------------------------------------------------------------
|
| 29 |
+
# 정규화: 소스별 방언 -> 단일 canonical 레코드
|
| 30 |
+
# --------------------------------------------------------------------------
|
| 31 |
+
def _extract_reasoning(msg: dict) -> tuple[str | None, str]:
|
| 32 |
+
"""assistant 메시지에서 (reasoning, content) 분리."""
|
| 33 |
+
content = msg.get("content") or ""
|
| 34 |
+
reasoning = msg.get("reasoning_content") or msg.get("reasoning") or None
|
| 35 |
+
if reasoning is None:
|
| 36 |
+
m = THINK_RE.match(content)
|
| 37 |
+
if m:
|
| 38 |
+
reasoning = m.group(1).strip()
|
| 39 |
+
content = content[m.end():]
|
| 40 |
+
if reasoning is not None:
|
| 41 |
+
reasoning = reasoning.strip()
|
| 42 |
+
if not reasoning:
|
| 43 |
+
reasoning = None
|
| 44 |
+
return reasoning, content
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _extract_tool_calls(msg: dict, content: str) -> tuple[list[dict], str]:
|
| 48 |
+
"""OpenAI tool_calls 필드 또는 Qwen <tool_call> 인라인 블록을 파싱."""
|
| 49 |
+
calls: list[dict] = []
|
| 50 |
+
native = msg.get("tool_calls")
|
| 51 |
+
if native:
|
| 52 |
+
for i, tc in enumerate(native):
|
| 53 |
+
fn = tc.get("function", tc)
|
| 54 |
+
args = fn.get("arguments")
|
| 55 |
+
if isinstance(args, str):
|
| 56 |
+
try:
|
| 57 |
+
args = json.loads(args)
|
| 58 |
+
except json.JSONDecodeError:
|
| 59 |
+
args = {"_raw": args}
|
| 60 |
+
if not isinstance(args, dict):
|
| 61 |
+
args = {"_raw": str(args)}
|
| 62 |
+
calls.append({
|
| 63 |
+
"id": tc.get("id") or f"call_{i}",
|
| 64 |
+
"name": fn.get("name") or "unknown",
|
| 65 |
+
"arguments": args,
|
| 66 |
+
})
|
| 67 |
+
return calls, content
|
| 68 |
+
|
| 69 |
+
for i, m in enumerate(TOOL_CALL_RE.finditer(content)):
|
| 70 |
+
try:
|
| 71 |
+
obj = json.loads(m.group(1))
|
| 72 |
+
except json.JSONDecodeError:
|
| 73 |
+
continue
|
| 74 |
+
args = obj.get("arguments", {})
|
| 75 |
+
if isinstance(args, str):
|
| 76 |
+
try:
|
| 77 |
+
args = json.loads(args)
|
| 78 |
+
except json.JSONDecodeError:
|
| 79 |
+
args = {"_raw": args}
|
| 80 |
+
if not isinstance(args, dict):
|
| 81 |
+
args = {"_raw": str(args)}
|
| 82 |
+
calls.append({
|
| 83 |
+
"id": f"call_{i}",
|
| 84 |
+
"name": obj.get("name") or "unknown",
|
| 85 |
+
"arguments": args,
|
| 86 |
+
})
|
| 87 |
+
if calls:
|
| 88 |
+
content = TOOL_CALL_RE.sub("", content).strip()
|
| 89 |
+
return calls, content
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _parse_qwen_system_tools(system: str) -> tuple[list[dict] | None, str]:
|
| 93 |
+
"""Qwen 스타일 `<tools>` 선언을 OpenAI tool 스펙 리스트로 뽑고 시스템 텍스트에서 제거."""
|
| 94 |
+
m = QWEN_TOOLS_RE.search(system)
|
| 95 |
+
if not m:
|
| 96 |
+
return None, system
|
| 97 |
+
tools = []
|
| 98 |
+
for line in m.group(1).splitlines():
|
| 99 |
+
line = line.strip()
|
| 100 |
+
if not line:
|
| 101 |
+
continue
|
| 102 |
+
try:
|
| 103 |
+
obj = json.loads(line)
|
| 104 |
+
except json.JSONDecodeError:
|
| 105 |
+
continue
|
| 106 |
+
if "function" in obj:
|
| 107 |
+
tools.append(obj["function"])
|
| 108 |
+
elif "name" in obj:
|
| 109 |
+
tools.append(obj)
|
| 110 |
+
if not tools:
|
| 111 |
+
return None, system
|
| 112 |
+
cleaned = QWEN_TOOL_SECTION_RE.sub("", system).strip()
|
| 113 |
+
return tools, cleaned
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def normalize(record: dict) -> dict:
|
| 117 |
+
"""소스 레코드 -> {system, tools, turns[]}."""
|
| 118 |
+
messages = record.get("messages")
|
| 119 |
+
if not messages:
|
| 120 |
+
raise SkipRecord("no messages")
|
| 121 |
+
|
| 122 |
+
system_parts: list[str] = []
|
| 123 |
+
turns: list[dict] = []
|
| 124 |
+
for msg in messages:
|
| 125 |
+
role = msg.get("role")
|
| 126 |
+
if role == "system":
|
| 127 |
+
text = (msg.get("content") or "").strip()
|
| 128 |
+
if text:
|
| 129 |
+
system_parts.append(text)
|
| 130 |
+
elif role == "user":
|
| 131 |
+
content = (msg.get("content") or "").strip()
|
| 132 |
+
if not content:
|
| 133 |
+
raise SkipRecord("empty user turn")
|
| 134 |
+
turns.append({"role": "user", "content": content})
|
| 135 |
+
elif role == "assistant":
|
| 136 |
+
reasoning, content = _extract_reasoning(msg)
|
| 137 |
+
calls, content = _extract_tool_calls(msg, content)
|
| 138 |
+
content = content.strip()
|
| 139 |
+
if not content and not calls and not reasoning:
|
| 140 |
+
raise SkipRecord("empty assistant turn")
|
| 141 |
+
turns.append({
|
| 142 |
+
"role": "assistant",
|
| 143 |
+
"content": content,
|
| 144 |
+
"reasoning": reasoning,
|
| 145 |
+
"tool_calls": calls,
|
| 146 |
+
})
|
| 147 |
+
elif role in ("tool", "function"):
|
| 148 |
+
content = msg.get("content") or ""
|
| 149 |
+
m = TOOL_RESP_RE.match(content)
|
| 150 |
+
if m:
|
| 151 |
+
content = m.group(1)
|
| 152 |
+
turns.append({
|
| 153 |
+
"role": "tool",
|
| 154 |
+
"content": content.strip(),
|
| 155 |
+
"tool_call_id": msg.get("tool_call_id"),
|
| 156 |
+
})
|
| 157 |
+
else:
|
| 158 |
+
raise SkipRecord(f"unknown role {role}")
|
| 159 |
+
|
| 160 |
+
system = "\n\n".join(system_parts)
|
| 161 |
+
tools = record.get("tools")
|
| 162 |
+
if tools:
|
| 163 |
+
tools = [t.get("function", t) for t in tools]
|
| 164 |
+
else:
|
| 165 |
+
parsed, system = _parse_qwen_system_tools(system)
|
| 166 |
+
tools = parsed
|
| 167 |
+
|
| 168 |
+
# tool 응답에 id가 없으면 직전 assistant tool_call id를 순서대로 붙인다
|
| 169 |
+
for i, turn in enumerate(turns):
|
| 170 |
+
if turn["role"] != "tool" or turn.get("tool_call_id"):
|
| 171 |
+
continue
|
| 172 |
+
j = i - 1
|
| 173 |
+
while j >= 0 and turns[j]["role"] == "tool":
|
| 174 |
+
j -= 1
|
| 175 |
+
if j >= 0 and turns[j]["role"] == "assistant" and turns[j]["tool_calls"]:
|
| 176 |
+
offset = i - j - 1
|
| 177 |
+
calls = turns[j]["tool_calls"]
|
| 178 |
+
turn["tool_call_id"] = calls[min(offset, len(calls) - 1)]["id"]
|
| 179 |
+
else:
|
| 180 |
+
raise SkipRecord("orphan tool response")
|
| 181 |
+
|
| 182 |
+
if not any(t["role"] == "assistant" for t in turns):
|
| 183 |
+
raise SkipRecord("no assistant turn")
|
| 184 |
+
return {"system": system, "tools": tools, "turns": turns}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# --------------------------------------------------------------------------
|
| 188 |
+
# 렌더링: canonical -> (piece, is_target) 리스트
|
| 189 |
+
# --------------------------------------------------------------------------
|
| 190 |
+
def _render_tool_arguments(arguments: dict) -> str:
|
| 191 |
+
out = []
|
| 192 |
+
for key, value in arguments.items():
|
| 193 |
+
rendered = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)
|
| 194 |
+
out.append(f"<|tool_arg:start|>{key}<|tool_arg:value|>{rendered}<|tool_arg:end|>\n")
|
| 195 |
+
return "".join(out)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def render_pieces(rec: dict) -> list[tuple[str, bool]]:
|
| 199 |
+
"""(text, is_loss_target) 조각 리스트. 특수 토큰 경계에서만 분할되므로
|
| 200 |
+
조각별 인코딩 후 이어붙여도 BPE 경계 문제가 없다."""
|
| 201 |
+
system, tools, turns = rec["system"], rec["tools"], rec["turns"]
|
| 202 |
+
pieces: list[tuple[str, bool]] = []
|
| 203 |
+
buf: list[str] = []
|
| 204 |
+
|
| 205 |
+
def emit(text: str):
|
| 206 |
+
buf.append(text)
|
| 207 |
+
|
| 208 |
+
def flush():
|
| 209 |
+
if buf:
|
| 210 |
+
pieces.append(("".join(buf), False))
|
| 211 |
+
buf.clear()
|
| 212 |
+
|
| 213 |
+
# ---- system block ----
|
| 214 |
+
if system or tools:
|
| 215 |
+
emit("<|im:start|>system<|im:content|>")
|
| 216 |
+
first = True
|
| 217 |
+
if system:
|
| 218 |
+
emit("## System Prompt\n\n" + system)
|
| 219 |
+
first = False
|
| 220 |
+
if tools:
|
| 221 |
+
if not first:
|
| 222 |
+
emit("\n\n")
|
| 223 |
+
emit("## Tools\n- You may invoke one or more tools to assist with the user's query.")
|
| 224 |
+
emit("\n\n### Available Tools\n")
|
| 225 |
+
for tool in tools:
|
| 226 |
+
emit("<|tool:start|>" + json.dumps(tool, ensure_ascii=False) + "<|tool:end|>\n")
|
| 227 |
+
emit("\n### Tool Call Instruction\n")
|
| 228 |
+
emit("- If using a tool, any reasoning must strictly precede the call. Do not append any text after the tool call.\n")
|
| 229 |
+
emit("- If no tool is required, answer directly from your knowledge without ever mentioning the availability or absence of tools.\n")
|
| 230 |
+
emit("- Each tool call MUST use this following format: <|tool_call:start|>{example-tool-name}\n<|tool_arg:start|>{example-key-name-1}<|tool_arg:value|>{example-value-1}<|tool_arg:end|>\n<|tool_arg:start|>{example-key-name-2}<|tool_arg:value|>{example-value-2}<|tool_arg:end|>\n<|tool_call:end|>\n")
|
| 231 |
+
emit("<|im:end|>\n")
|
| 232 |
+
|
| 233 |
+
last_user_idx = max(
|
| 234 |
+
(i for i, t in enumerate(turns) if t["role"] == "user"), default=-1
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
i = 0
|
| 238 |
+
while i < len(turns):
|
| 239 |
+
turn = turns[i]
|
| 240 |
+
if turn["role"] == "user":
|
| 241 |
+
emit(f"<|im:start|>user<|im:content|>{turn['content']}<|im:end|>\n")
|
| 242 |
+
i += 1
|
| 243 |
+
elif turn["role"] == "tool":
|
| 244 |
+
# 연속된 tool 응답은 하나의 tool 블록으로 병합 (직전 assistant의 호출 순서 기준)
|
| 245 |
+
block = [turns[i]]
|
| 246 |
+
j = i + 1
|
| 247 |
+
while j < len(turns) and turns[j]["role"] == "tool":
|
| 248 |
+
block.append(turns[j])
|
| 249 |
+
j += 1
|
| 250 |
+
emit("<|im:start|>tool<|im:content|>")
|
| 251 |
+
prev = turns[i - 1] if i > 0 else None
|
| 252 |
+
ordered, rendered_ids = [], set()
|
| 253 |
+
if prev and prev["role"] == "assistant" and prev.get("tool_calls"):
|
| 254 |
+
for call in prev["tool_calls"]:
|
| 255 |
+
for msg in block:
|
| 256 |
+
if msg.get("tool_call_id") == call["id"]:
|
| 257 |
+
ordered.append(msg)
|
| 258 |
+
rendered_ids.add(msg["tool_call_id"])
|
| 259 |
+
for msg in block:
|
| 260 |
+
if msg.get("tool_call_id") not in rendered_ids:
|
| 261 |
+
ordered.append(msg)
|
| 262 |
+
else:
|
| 263 |
+
ordered = block
|
| 264 |
+
emit("\n".join(
|
| 265 |
+
f"<|tool_response:start|>{m['content']}<|tool_response:end|>" for m in ordered
|
| 266 |
+
))
|
| 267 |
+
emit("\n<|im:end|>\n")
|
| 268 |
+
i = j
|
| 269 |
+
else: # assistant
|
| 270 |
+
flush()
|
| 271 |
+
pieces.append(("<|im:start|>assistant<|im:content|>", False))
|
| 272 |
+
out = []
|
| 273 |
+
reasoning = turn.get("reasoning")
|
| 274 |
+
if reasoning and i > last_user_idx:
|
| 275 |
+
out.append(f"<|think:start|>{reasoning}<|think:end|>")
|
| 276 |
+
else:
|
| 277 |
+
out.append("<|think:start|><|think:end|>")
|
| 278 |
+
if turn.get("content"):
|
| 279 |
+
out.append(turn["content"])
|
| 280 |
+
if turn.get("tool_calls"):
|
| 281 |
+
for k, call in enumerate(turn["tool_calls"]):
|
| 282 |
+
if k:
|
| 283 |
+
out.append("\n")
|
| 284 |
+
out.append(f"<|tool_call:start|>{call['name']}\n")
|
| 285 |
+
out.append(_render_tool_arguments(call["arguments"]))
|
| 286 |
+
out.append("<|tool_call:end|>")
|
| 287 |
+
out.append("\n")
|
| 288 |
+
out.append("<|im:end|>\n")
|
| 289 |
+
pieces.append(("".join(out), True))
|
| 290 |
+
i += 1
|
| 291 |
+
|
| 292 |
+
flush()
|
| 293 |
+
return pieces
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def render_text(rec: dict) -> str:
|
| 297 |
+
return "".join(p for p, _ in render_pieces(rec))
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def truncate_turns(rec: dict, keep: int) -> dict:
|
| 301 |
+
"""turn 단위로 앞에서 keep개만 남기고, 마지막이 assistant가 되도록 자른다."""
|
| 302 |
+
turns = rec["turns"][:keep]
|
| 303 |
+
while turns and turns[-1]["role"] != "assistant":
|
| 304 |
+
turns.pop()
|
| 305 |
+
return {"system": rec["system"], "tools": rec["tools"], "turns": turns}
|