"""TP2 阶段状态:受限 JSON 树与 safetensors,不加载 pickle 对象。""" from __future__ import annotations import hashlib import json import math import os import re import sys import uuid from pathlib import Path PROFILE = 'minimax-h3-fl2va-bf16-tp2-v1' MODEL_REPO = 'MiniMaxAI/MiniMax-H3' MODEL_REVISION = '12253298adb81e36757eabebb81d2ba1c0cc70cc' RUNTIME_REVISION = '423ab90580b2847998591669b8326f47b6d14d8b' MAX_JSON_BYTES = 4 * 1024 ** 2 MAX_TENSOR_BYTES = 4 * 1024 ** 3 _NAME = re.compile(r'[a-z][a-z0-9_-]{0,63}\Z') def _directory(directory): path = Path(directory) if not path.is_absolute() or not path.is_dir() or path.is_symlink() or path.resolve() != path: raise ValueError('State directory must be an absolute real directory without symlinks') return path def _paths(directory, name): if not isinstance(name, str) or _NAME.fullmatch(name) is None: raise ValueError('Invalid state name') path = _directory(directory) return path / f'{name}.json', path / f'{name}.safetensors' def _binding(): digest = os.environ.get('LLM_TP2_REQUEST_SHA256') token = os.environ.get('LLM_TP2_GROUP_TOKEN') if (digest is None) != (token is None): raise ValueError('Incomplete state request/group binding') if digest is not None: if re.fullmatch(r'[0-9a-f]{64}', digest) is None: raise ValueError('Invalid state request binding') try: uuid.UUID(token) except (ValueError, AttributeError, TypeError) as exc: raise ValueError('Invalid state group binding') from exc return {'profile': PROFILE, 'model': MODEL_REPO, 'model_revision': MODEL_REVISION, 'runtime_revision': RUNTIME_REVISION, 'request_sha256': digest, 'group_token': token} def _hash(path): digest = hashlib.sha256() with path.open('rb') as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b''): digest.update(chunk) return digest.hexdigest() def _publish(temporary, target): # 同目录硬链接原子发布且拒绝覆盖;竞争写入不能改掉另一 rank 的结果。 os.link(temporary, target) temporary.unlink() def _atomic_json(path, value): content = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(',', ':')).encode('utf-8') if len(content) > MAX_JSON_BYTES: raise ValueError('State manifest is too large') temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp') try: with temporary.open('xb') as stream: stream.write(content) stream.flush() os.fsync(stream.fileno()) _publish(temporary, path) finally: temporary.unlink(missing_ok=True) def _encode(value, tensors, count, depth=0): count[0] += 1 if depth > 32 or count[0] > 100000: raise ValueError('Unsupported state nesting or item count') if value is None or type(value) in (bool, str, int, float): if isinstance(value, str) and len(value) > 1024 ** 2: raise ValueError('Unsupported state string length') if type(value) is int and not -(2 ** 63) <= value < 2 ** 63: raise ValueError('Unsupported state integer') if type(value) is float and not math.isfinite(value): raise ValueError('State floating values must be finite') return {'kind': 'scalar', 'value': value} torch = sys.modules.get('torch') if torch is not None and isinstance(value, torch.Tensor): if value.is_meta or value.layout != torch.strided or value.is_quantized: raise ValueError('Unsupported state tensor layout') tensor = value.detach().to(device='cpu').contiguous().clone() if tensor.numel() * tensor.element_size() > MAX_TENSOR_BYTES: raise ValueError('Unsupported state tensor size') key = f'tensor_{len(tensors)}' tensors[key] = tensor return {'kind': 'tensor', 'key': key} if type(value) in (list, tuple): return {'kind': 'tuple' if type(value) is tuple else 'list', 'items': [_encode(item, tensors, count, depth + 1) for item in value]} if type(value) is dict: if any(type(key) is not str or len(key) > 1024 for key in value): raise ValueError('State dictionary key must be a short string') return {'kind': 'dict', 'items': [[key, _encode(item, tensors, count, depth + 1)] for key, item in value.items()]} raise ValueError(f'Unsupported state value type: {type(value).__name__}') def _decode(node, tensors, seen, count, depth=0): count[0] += 1 if depth > 32 or count[0] > 100000 or type(node) is not dict: raise ValueError('Invalid state schema') kind = node.get('kind') if kind == 'scalar' and set(node) == {'kind', 'value'}: value = node['value'] _encode(value, {}, [0]) if value is not None and type(value) not in (bool, str, int, float): raise ValueError('Invalid state scalar') return value if kind == 'tensor' and set(node) == {'kind', 'key'}: key = node['key'] if type(key) is not str or key not in tensors or key in seen: raise ValueError('Invalid or duplicate state tensor reference') seen.add(key) return tensors[key] if kind in ('list', 'tuple', 'dict') and set(node) == {'kind', 'items'} and type(node['items']) is list: if kind in ('list', 'tuple'): values = [_decode(item, tensors, seen, count, depth + 1) for item in node['items']] return tuple(values) if kind == 'tuple' else values result = {} for item in node['items']: if (type(item) is not list or len(item) != 2 or type(item[0]) is not str or len(item[0]) > 1024 or item[0] in result): raise ValueError('Invalid state dictionary key') result[item[0]] = _decode(item[1], tensors, seen, count, depth + 1) return result raise ValueError('Invalid state schema') def save_state(directory, name, value): manifest_path, tensor_path = _paths(directory, name) if any(path.exists() or path.is_symlink() for path in (manifest_path, tensor_path)): raise ValueError('State output already exists; refusing overwrite') tensors = {} tree = _encode(value, tensors, [0]) binding = _binding() if sum(t.numel() * t.element_size() for t in tensors.values()) > MAX_TENSOR_BYTES: raise ValueError('Unsupported total state tensor size') description = {key: {'shape': list(t.shape), 'dtype': str(t.dtype)} for key, t in tensors.items()} temporary = tensor_path.with_name(tensor_path.name + '.' + uuid.uuid4().hex + '.tmp') published = False try: if tensors: from safetensors.torch import save_file save_file(tensors, str(temporary)) os.chmod(temporary, 0o600) _publish(temporary, tensor_path) published = True _atomic_json(manifest_path, {'schema_version': 1, 'binding': binding, 'tree': tree, 'tensor_file': tensor_path.name if tensors else None, 'tensor_bytes': tensor_path.stat().st_size if tensors else 0, 'tensor_sha256': _hash(tensor_path) if tensors else None, 'tensors': description}) except BaseException: if published: tensor_path.unlink(missing_ok=True) raise finally: temporary.unlink(missing_ok=True) def _unique_object(pairs): result = {} for key, value in pairs: if key in result: raise ValueError('Duplicate state manifest key') result[key] = value return result def load_state(directory, name, device='cpu'): manifest_path, tensor_path = _paths(directory, name) if manifest_path.is_symlink() or not manifest_path.is_file() or manifest_path.stat().st_size > MAX_JSON_BYTES: raise ValueError('Invalid state manifest file') try: content = json.loads(manifest_path.read_text(encoding='utf-8'), object_pairs_hook=_unique_object, parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Nonfinite state value'))) except (OSError, UnicodeError, json.JSONDecodeError) as exc: raise ValueError('Invalid state manifest JSON') from exc if type(content) is not dict or set(content) != { 'schema_version', 'binding', 'tree', 'tensor_file', 'tensor_bytes', 'tensor_sha256', 'tensors'}: raise ValueError('Invalid state manifest schema') if type(content['schema_version']) is not int or content['schema_version'] != 1: raise ValueError('Unsupported state manifest version') if content['binding'] != _binding(): raise ValueError('State request/group/model/runtime binding mismatch') descriptors = content['tensors'] if type(descriptors) is not dict: raise ValueError('Invalid state tensor descriptors') tensors = {} if descriptors: if (content['tensor_file'] != tensor_path.name or tensor_path.is_symlink() or not tensor_path.is_file() or type(content['tensor_bytes']) is not int or not 0 < content['tensor_bytes'] <= MAX_TENSOR_BYTES + MAX_JSON_BYTES or tensor_path.stat().st_size != content['tensor_bytes'] or type(content['tensor_sha256']) is not str or _hash(tensor_path) != content['tensor_sha256']): raise ValueError('State tensor integrity/hash check failed') from safetensors.torch import load_file tensors = load_file(str(tensor_path), device='cpu') if set(tensors) != set(descriptors): raise ValueError('State tensor inventory mismatch') for key, tensor in tensors.items(): if descriptors[key] != {'shape': list(tensor.shape), 'dtype': str(tensor.dtype)}: raise ValueError('State tensor descriptor mismatch') tensors = {key: tensor.to(device=device) for key, tensor in tensors.items()} elif content['tensor_file'] is not None or content['tensor_bytes'] != 0 or content['tensor_sha256'] is not None: raise ValueError('Invalid empty state tensor manifest') seen = set() value = _decode(content['tree'], tensors, seen, [0]) if seen != set(tensors): raise ValueError('Unused state tensors') return value