Download common.py from openmodelai/Terra-2.5: direct link, hf CLI and curl.
- Browser
- Download file 2.56 kB
-
https://huggingface.co/openmodelai/Terra-2.5/resolve/main/common.py
- Command line
-
hf download hf://openmodelai/Terra-2.5/common.py
-
curl -L -o common.py https://huggingface.co/openmodelai/Terra-2.5/resolve/main/common.py
2.56 kB
| import hashlib | |
| import json | |
| import re | |
| from pathlib import Path | |
| import torch | |
| def read_pairs(path): | |
| pairs = [] | |
| for i, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), 1): | |
| if not line.strip(): | |
| continue | |
| item = json.loads(line) | |
| if any(not isinstance(item.get(k), str) or not item[k].strip() | |
| for k in ("question", "answer")): | |
| raise ValueError(f"{path}:{i}: нужны непустые question и answer") | |
| pairs.append(item) | |
| if not pairs: | |
| raise ValueError(f"Пустой датасет: {path}") | |
| return pairs | |
| def detect_language(question): | |
| # Lightweight UI routing, not a trained language detector; explicit override wins. | |
| if re.search(r"[А-Яа-яЁё]", question): | |
| return "ru" | |
| if re.search(r"[\u3400-\u9fff]", question): | |
| return "zh" | |
| return "en" | |
| def prompt(question, language=None): | |
| language = language or detect_language(question) | |
| templates = {"ru": "Вопрос: {}\nОтвет:", "en": "Question: {}\nAnswer:", "zh": "问题:{}\n回答:"} | |
| if language not in templates: | |
| raise ValueError(f"Unsupported language: {language}") | |
| return templates[language].format(question.strip()) | |
| def digest(path): | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| for chunk in iter(lambda: f.read(1024 * 1024), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def encode_pairs(pairs, tokenizer, max_length): | |
| result = [] | |
| for pair in pairs: | |
| prefix = tokenizer.encode(prompt(pair["question"], pair.get("language")), add_special_tokens=False) | |
| answer = tokenizer.encode(" " + pair["answer"], add_special_tokens=False) | |
| ids = prefix + answer + [tokenizer.eos_token_id] | |
| # Не обрезаем ответы незаметно: исправьте данные или увеличьте контекст. | |
| if len(ids) > max_length: | |
| raise ValueError(f"Пример длиннее {max_length} токенов: {pair['question']}") | |
| result.append((ids, [-100] * len(prefix) + answer + [tokenizer.eos_token_id])) | |
| return result | |
| def batch(rows, pad_id): | |
| width = max(len(ids) for ids, _ in rows) | |
| return { | |
| "input_ids": torch.tensor([ids + [pad_id] * (width - len(ids)) for ids, _ in rows]), | |
| "attention_mask": torch.tensor([[1] * len(ids) + [0] * (width - len(ids)) for ids, _ in rows]), | |
| "labels": torch.tensor([labels + [-100] * (width - len(labels)) for _, labels in rows]), | |
| } | |