Spaces:
Sleeping
Sleeping
Download src/decision_model/features.py from xstard/decision-model: direct link, hf CLI and curl.
- Browser
- Download file 3.56 kB
-
https://huggingface.co/spaces/xstard/decision-model/resolve/main/src/decision_model/features.py
- Command line
-
hf download hf://spaces/xstard/decision-model/src/decision_model/features.py
-
curl -L -o features.py https://huggingface.co/spaces/xstard/decision-model/resolve/main/src/decision_model/features.py
3.56 kB
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| from .artifacts import sha256 | |
| from .data import DecisionExample, read_jsonl | |
| from .encoding import render_question, candidates | |
| from .settings import ROOT, TEMPLATE_VERSION | |
| def cache_features(input_path, output_path, encoder): | |
| rows = read_jsonl(input_path, DecisionExample) | |
| if not rows: | |
| raise ValueError("Порожня вибірка ознак.") | |
| directory = ROOT / ".cache" / "features" | |
| directory.mkdir(parents=True, exist_ok=True) | |
| arrays, meta = [], [] | |
| for i, row in enumerate(rows): | |
| text, spans, _ = render_question(row.state, row.question) | |
| identity = [encoder.model_id, encoder.revision, TEMPLATE_VERSION, text, spans] | |
| if getattr(encoder,'adaptation_sha256',None): | |
| identity.append({'encoder_delta_sha256':encoder.adaptation_sha256}) | |
| key = hashlib.sha256(json.dumps(identity, ensure_ascii=False).encode()).hexdigest() | |
| file = directory / f"{key}.npz" | |
| if file.exists(): | |
| with np.load(file, allow_pickle=False) as cached: | |
| feature = cached["features"] | |
| tokens = int(cached["tokens"]) | |
| else: | |
| encoded = encoder.encode(row.state, row.question) | |
| feature, tokens = encoded.features, encoded.input_tokens | |
| np.savez_compressed(file, features=feature, tokens=tokens) | |
| if feature.shape != (len(candidates(row.question)[0]), encoder.hidden_size) or not np.isfinite(feature).all(): | |
| raise ValueError("Несумісний кеш ознак.") | |
| arrays.append(feature) | |
| meta.append({"id": row.id, "ticket_id": row.ticket_id, "group_id": row.group_id, "language": row.language, "type": row.question.type, | |
| "gold": row.gold, "reviewed": row.reviewed, "reviewer": row.reviewer, "demo": row.demo, | |
| "candidates": len(feature), "input_tokens": tokens}) | |
| if i % 100 == 0: | |
| print(f"features {Path(input_path).stem}: {i}/{len(rows)}", flush=True) | |
| max_k = max(len(a) for a in arrays) | |
| features = np.zeros((len(arrays), max_k, encoder.hidden_size), dtype=np.float32) | |
| mask = np.zeros((len(arrays), max_k), dtype=bool) | |
| for i, array in enumerate(arrays): | |
| features[i, :len(array)] = array | |
| mask[i, :len(array)] = True | |
| output = Path(output_path) | |
| output.parent.mkdir(parents=True, exist_ok=True) | |
| np.savez_compressed(output, features=features, mask=mask, gold=np.array([m["gold"] for m in meta], dtype=np.int64)) | |
| metadata = {"encoder_id": encoder.model_id, "encoder_revision": encoder.revision, | |
| "template_version": TEMPLATE_VERSION, "hidden_size": encoder.hidden_size, | |
| "data_hash": sha256(input_path), "features_hash": sha256(output), "rows": meta} | |
| if getattr(encoder,'adaptation_sha256',None): | |
| metadata['encoder_delta_sha256'] = encoder.adaptation_sha256 | |
| output.with_suffix(".json").write_text(json.dumps(metadata, ensure_ascii=False), encoding="utf-8") | |
| return metadata | |
| def load_features(path): | |
| path = Path(path) | |
| metadata = json.loads(path.with_suffix(".json").read_text(encoding="utf-8")) | |
| if sha256(path) != metadata["features_hash"] or metadata["template_version"] != TEMPLATE_VERSION: | |
| raise ValueError("Кеш ознак пошкоджений або застарілий.") | |
| with np.load(path, allow_pickle=False) as file: | |
| arrays = {key: file[key] for key in ("features", "mask", "gold")} | |
| return arrays, metadata | |