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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen source model acquisition: streaming download -> decompose -> purge.
|
| 2 |
+
|
| 3 |
+
Proposition P-SRC (one-at-a-time streaming with purge). For source s:
|
| 4 |
+
1. hf_hub_download fetches only model.onnx + model.onnx.data + tokenizer
|
| 5 |
+
(token from env HF_TOKEN exclusively -- NEVER persisted to disk).
|
| 6 |
+
2. Decomposition extracts the mandated geometry (int4_proto, int4_xi,
|
| 7 |
+
keys, 4 adapters) into compact .npz artifacts.
|
| 8 |
+
3. The raw blobs are deleted (MemoryManager.sweep_caches) since the
|
| 9 |
+
decomposed twins exist; disk returns to ~artifact size.
|
| 10 |
+
Peak disk = max over s of |raw_s| + |artifacts|, not the sum -- the
|
| 11 |
+
one-at-a-time rule turns a 4.2 GiB requirement into ~1.9 GiB.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import logging
|
| 17 |
+
import os
|
| 18 |
+
import shutil
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, List
|
| 21 |
+
|
| 22 |
+
log = logging.getLogger("hako.sources")
|
| 23 |
+
|
| 24 |
+
QWEN = "amd/Qwen2.5-0.5B-Instruct-quantized_int4-float16-cpu-onnx"
|
| 25 |
+
GRANITE = "amd/granite-4.0-1b-awq-grp32-oga-cpu"
|
| 26 |
+
|
| 27 |
+
MODEL_FILES = ["model.onnx", "model.onnx.data", "tokenizer.json",
|
| 28 |
+
"tokenizer_config.json", "vocab.json", "merges.txt"]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _token() -> str | None:
|
| 32 |
+
"""Read the HF token from the environment ONLY. Never log it."""
|
| 33 |
+
return os.environ.get("HF_TOKEN") or None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def fetch_source(repo: str, cache_dir: Path, memmgr) -> Path:
|
| 37 |
+
"""Download one source's onnx + tokenizer files, then MATERIALIZE real
|
| 38 |
+
(dereferenced) copies under <work>/sources/<name>/ -- onnx's external-
|
| 39 |
+
data loader rejects HF-cache symlinks ('not regular file'). Returns the
|
| 40 |
+
materialized snapshot dir (which the purge step deletes)."""
|
| 41 |
+
import shutil as _shutil
|
| 42 |
+
from huggingface_hub import hf_hub_download
|
| 43 |
+
cache_dir = Path(cache_dir)
|
| 44 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 45 |
+
mat = Path(memmgr.cfg.work_dir) / "sources" / repo.split("/")[-1]
|
| 46 |
+
marker = mat / "model.onnx.data"
|
| 47 |
+
if marker.exists():
|
| 48 |
+
return mat # materialized copy survives purge
|
| 49 |
+
need = 4.5 * 1024 ** 3 if "granite" in repo.lower() else 2.2 * 1024 ** 3
|
| 50 |
+
memmgr.ensure_disk(need)
|
| 51 |
+
local: str | None = None
|
| 52 |
+
for fname in MODEL_FILES:
|
| 53 |
+
try:
|
| 54 |
+
p = hf_hub_download(repo_id=repo, filename=fname,
|
| 55 |
+
cache_dir=str(cache_dir), token=_token())
|
| 56 |
+
local = local or str(Path(p).parent) # snapshot dir
|
| 57 |
+
log.info("fetched %s/%s", repo, fname)
|
| 58 |
+
except Exception as exc:
|
| 59 |
+
log.info("skip %s (%s)", fname, type(exc).__name__)
|
| 60 |
+
if local is None:
|
| 61 |
+
raise RuntimeError(f"could not fetch any file from {repo}")
|
| 62 |
+
mat.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
for fname in MODEL_FILES:
|
| 64 |
+
src = Path(local) / fname
|
| 65 |
+
dst = mat / fname
|
| 66 |
+
if src.exists() and not dst.exists():
|
| 67 |
+
_shutil.copy(src, dst) # dereferences symlinks
|
| 68 |
+
return mat
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def purge_source(repo: str, cache_dir: Path, memmgr) -> int:
|
| 72 |
+
"""Delete raw blobs + materialized copy AFTER decomposed artifacts exist."""
|
| 73 |
+
import shutil as _shutil
|
| 74 |
+
marker = Path("/home/z/my-project/download/hako/artifacts") / (
|
| 75 |
+
repo.split("/")[-1] + ".decomposed.json")
|
| 76 |
+
if not marker.exists():
|
| 77 |
+
log.info("keep %s: no decomposed artifact yet", repo)
|
| 78 |
+
return 0
|
| 79 |
+
freed = 0
|
| 80 |
+
mat = Path(memmgr.cfg.work_dir) / "sources" / repo.split("/")[-1]
|
| 81 |
+
if mat.exists():
|
| 82 |
+
freed += sum(f.stat().st_size for f in mat.rglob("*") if f.is_file())
|
| 83 |
+
_shutil.rmtree(mat, ignore_errors=True)
|
| 84 |
+
freed += memmgr.sweep_caches()
|
| 85 |
+
return freed
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def fetch_datasets_streaming(cfg, memmgr, max_docs: Dict[str, int]
|
| 89 |
+
) -> Dict[str, List[str]]:
|
| 90 |
+
"""Stream EN + PT-BR + zh text. Returns {lang: [docs]}.
|
| 91 |
+
|
| 92 |
+
Streaming (datasets) reads parquet row-groups over HTTP ranges, so the
|
| 93 |
+
1.1 GiB shard of corpus-ptbr-v1 and the 467 MiB ultra-alpaca parquet are
|
| 94 |
+
never fully materialized on disk (P-SRC applied to data).
|
| 95 |
+
"""
|
| 96 |
+
out: Dict[str, List] = {"pt": [], "en": [], "zh": [], "pt_instr": []}
|
| 97 |
+
from datasets import load_dataset
|
| 98 |
+
|
| 99 |
+
# --- PT-BR 1: BrunoN-Dev/ultra-alpaca-ptbr (instruction pairs) --------
|
| 100 |
+
try:
|
| 101 |
+
ds = load_dataset("BrunoN-Dev/ultra-alpaca-ptbr", split="train",
|
| 102 |
+
streaming=True)
|
| 103 |
+
n = 0
|
| 104 |
+
for row in ds:
|
| 105 |
+
# instruction format: prompt=[{role,content}], completion=str
|
| 106 |
+
try:
|
| 107 |
+
prompt = row["prompt"][0]["content"]
|
| 108 |
+
resp = row["completion"]
|
| 109 |
+
out["pt"].append((str(prompt) + "\n" + str(resp))[:2000])
|
| 110 |
+
out["pt_instr"].append((str(prompt)[:512], str(resp)[:512]))
|
| 111 |
+
except (KeyError, IndexError, TypeError):
|
| 112 |
+
txt = " \n ".join(str(v) for v in row.values()
|
| 113 |
+
if v and len(str(v)) > 1)
|
| 114 |
+
out["pt"].append(txt[:2000])
|
| 115 |
+
n += 1
|
| 116 |
+
if n >= max_docs.get("pt_alpaca", 12000):
|
| 117 |
+
break
|
| 118 |
+
log.info("ultra-alpaca-ptbr streamed: %d docs (%d instruction pairs)",
|
| 119 |
+
n, len(out["pt_instr"]))
|
| 120 |
+
except Exception as exc:
|
| 121 |
+
log.warning("ultra-alpaca-ptbr failed: %s", exc)
|
| 122 |
+
|
| 123 |
+
# --- PT-BR 2: BrunoN-Dev/corpus-ptbr-v1 (cached sample) ---------------
|
| 124 |
+
# The shard has ONE 500k-row row group (~1.2 GiB decompressed) that
|
| 125 |
+
# cannot be streamed incrementally; it is materialized by the isolated
|
| 126 |
+
# corpus_cache subprocess (run before training, clean RAM) and read here
|
| 127 |
+
# from the small JSONL cache.
|
| 128 |
+
cache_file = Path(cfg.work_dir) / "cache" / "corpus_ptbr.jsonl"
|
| 129 |
+
if cache_file.exists():
|
| 130 |
+
with open(cache_file, "r", encoding="utf-8") as fh:
|
| 131 |
+
for line in fh:
|
| 132 |
+
try:
|
| 133 |
+
out["pt"].append(json.loads(line)["text"][:2000])
|
| 134 |
+
except Exception:
|
| 135 |
+
continue
|
| 136 |
+
log.info("corpus-ptbr-v1 from cache: %d docs", len(out["pt"]))
|
| 137 |
+
|
| 138 |
+
# --- EN: wikitext-2-raw ----------------------------------------------
|
| 139 |
+
try:
|
| 140 |
+
ds = load_dataset("Salesforce/wikitext", "wikitext-2-raw-v1",
|
| 141 |
+
split="train", streaming=True)
|
| 142 |
+
n = 0
|
| 143 |
+
for row in ds:
|
| 144 |
+
t = row.get("text", "").strip()
|
| 145 |
+
if len(t) > 200:
|
| 146 |
+
out["en"].append(t[:2000])
|
| 147 |
+
n += 1
|
| 148 |
+
if n >= max_docs.get("en", 8000):
|
| 149 |
+
break
|
| 150 |
+
log.info("wikitext-2 streamed: %d docs", n)
|
| 151 |
+
except Exception as exc:
|
| 152 |
+
log.warning("wikitext failed: %s", exc)
|
| 153 |
+
|
| 154 |
+
# --- zh: wikipedia streaming slice ------------------------------------
|
| 155 |
+
try:
|
| 156 |
+
ds = load_dataset("wikimedia/wikipedia", "20231101.zh",
|
| 157 |
+
split="train", streaming=True)
|
| 158 |
+
n = 0
|
| 159 |
+
for row in ds:
|
| 160 |
+
t = row.get("text", "").strip()
|
| 161 |
+
if len(t) > 200:
|
| 162 |
+
out["zh"].append(t[:1500])
|
| 163 |
+
n += 1
|
| 164 |
+
if n >= max_docs.get("zh", 2500):
|
| 165 |
+
break
|
| 166 |
+
log.info("wikipedia-zh streamed: %d docs", n)
|
| 167 |
+
except Exception as exc:
|
| 168 |
+
log.warning("wikipedia-zh failed: %s", exc)
|
| 169 |
+
|
| 170 |
+
for lang in out:
|
| 171 |
+
memmgr.cap_file_size # no-op ref to keep linters calm
|
| 172 |
+
return out
|