Instructions to use ioxdue/moediet-runs with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use ioxdue/moediet-runs with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf ioxdue/moediet-runs:Q4_K_M # Run inference directly in the terminal: llama cli -hf ioxdue/moediet-runs:Q4_K_M
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf ioxdue/moediet-runs:Q4_K_M # Run inference directly in the terminal: llama cli -hf ioxdue/moediet-runs:Q4_K_M
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf ioxdue/moediet-runs:Q4_K_M # Run inference directly in the terminal: ./build/bin/llama cli -hf ioxdue/moediet-runs:Q4_K_M
Use Docker
docker model run hf.co/ioxdue/moediet-runs:Q4_K_M
- Llama new
- LM Studio
- Jan
- Ollama
How to use ioxdue/moediet-runs with Ollama:
ollama run hf.co/ioxdue/moediet-runs:Q4_K_M
- Unsloth Desktop
- Docker Model Runner
How to use ioxdue/moediet-runs with Docker Model Runner:
docker model run hf.co/ioxdue/moediet-runs:Q4_K_M
- Lemonade
How to use ioxdue/moediet-runs with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull ioxdue/moediet-runs:Q4_K_M
Run and chat with the model
lemonade run user.moediet-runs-Q4_K_M
List all available models
lemonade list
- Atomic Chat
MoEDiet: codice e parametri del Job
Browse files- requests/fd7c309dd6d8431ba83fda6aa954b87b/adapters.py +170 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/architecture.py +169 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/architectures/olmoe.json +19 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/architectures/qwen2_moe.json +19 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/architectures/qwen3_moe.json +19 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/architectures/qwen3_next.json +21 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/architectures/qwen4_exp.json +7 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/corpus.json +128 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/fidelity.py +90 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/gguf_export.py +167 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/hf_jobs.py +103 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/llama_tools.py +96 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/moediet.py +363 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/preflight.py +63 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/probes.py +90 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/request.json +1 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/requirements-q4.txt +6 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/requirements-qwen3next.txt +7 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/requirements.txt +4 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/routing.py +77 -0
- requests/fd7c309dd6d8431ba83fda6aa954b87b/run.py +254 -0
requests/fd7c309dd6d8431ba83fda6aa954b87b/adapters.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Runtime implementation of the declarative softmax/top-k/ModuleList contract."""
|
| 2 |
+
|
| 3 |
+
from contextlib import ExitStack, contextmanager
|
| 4 |
+
import copy
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
import transformers
|
| 9 |
+
|
| 10 |
+
from architecture import read_path, resolve_profile, topology, write_path
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def tolerances(dtype):
|
| 14 |
+
# Numerical equivalence limits, independent of the quality/KL threshold.
|
| 15 |
+
if dtype == torch.bfloat16:
|
| 16 |
+
return {'atol': 0.125, 'rtol': 0.001}
|
| 17 |
+
if dtype == torch.float16:
|
| 18 |
+
return {'atol': 0.02, 'rtol': 0.001}
|
| 19 |
+
return {'atol': 0.0001, 'rtol': 0.00001}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ModuleListAdapter:
|
| 23 |
+
def __init__(self, spec):
|
| 24 |
+
self.spec = spec
|
| 25 |
+
self.layout = spec['layout']
|
| 26 |
+
|
| 27 |
+
def check_runtime(self):
|
| 28 |
+
expected = self.spec['transformers_version']
|
| 29 |
+
if transformers.__version__ != expected:
|
| 30 |
+
raise ValueError(f"Il profilo {self.spec['id']} richiede transformers=={expected}; installato {transformers.__version__}.")
|
| 31 |
+
|
| 32 |
+
def topology(self, config):
|
| 33 |
+
return topology(config, self.spec)
|
| 34 |
+
|
| 35 |
+
def blocks(self, model):
|
| 36 |
+
self.check_runtime()
|
| 37 |
+
routing = self.topology(model.config)
|
| 38 |
+
layers = read_path(model, self.layout['layers'])
|
| 39 |
+
if len(layers) != read_path(model.config, self.spec['config']['layers']):
|
| 40 |
+
raise ValueError('Numero di layer incompatibile con il profilo.')
|
| 41 |
+
selected = [read_path(layers[i], self.layout['block']) for i in routing['layer_indices']]
|
| 42 |
+
for block in selected:
|
| 43 |
+
gate, experts = self.router(block), self.experts(block)
|
| 44 |
+
if not (isinstance(gate, nn.Linear) and gate.bias is None and isinstance(experts, nn.ModuleList)
|
| 45 |
+
and read_path(block, self.layout['count']) == gate.out_features == len(experts) == routing['experts_per_layer']
|
| 46 |
+
and read_path(block, self.layout['top_k']) == routing['experts_per_token']
|
| 47 |
+
and type(read_path(block, self.layout['normalize'])) is bool
|
| 48 |
+
and read_path(block, self.layout['normalize']) == routing['norm_topk_prob']):
|
| 49 |
+
raise ValueError('Layout del router/esperti incompatibile con il profilo ModuleList.')
|
| 50 |
+
for shared in self.spec['shared_experts']:
|
| 51 |
+
if not (isinstance(read_path(block, shared['module']), nn.Module)
|
| 52 |
+
and isinstance(read_path(block, shared['gate']), nn.Linear)):
|
| 53 |
+
raise ValueError('Shared expert incompatibile con il profilo.')
|
| 54 |
+
return selected
|
| 55 |
+
|
| 56 |
+
def router(self, block):
|
| 57 |
+
return read_path(block, self.layout['router'])
|
| 58 |
+
|
| 59 |
+
def experts(self, block):
|
| 60 |
+
return read_path(block, self.layout['experts'])
|
| 61 |
+
|
| 62 |
+
def weights(self, block, logits):
|
| 63 |
+
probs = logits.float().softmax(-1)
|
| 64 |
+
weights, chosen = probs.topk(read_path(block, self.layout['top_k']), dim=-1)
|
| 65 |
+
if read_path(block, self.layout['normalize']):
|
| 66 |
+
weights = weights / weights.sum(dim=-1, keepdim=True)
|
| 67 |
+
return weights, chosen
|
| 68 |
+
|
| 69 |
+
def forward_backbone(self, model, ids):
|
| 70 |
+
return read_path(model, self.layout['backbone'])(input_ids=ids, use_cache=False,
|
| 71 |
+
output_router_logits=False, return_dict=True)
|
| 72 |
+
|
| 73 |
+
def router_logits(self, model, ids):
|
| 74 |
+
layers = self.blocks(model)
|
| 75 |
+
captured = [[] for _ in layers]
|
| 76 |
+
with ExitStack() as stack:
|
| 77 |
+
for i, block in enumerate(layers):
|
| 78 |
+
def capture(module, args, output, i=i):
|
| 79 |
+
captured[i].append(output.detach())
|
| 80 |
+
stack.callback(self.router(block).register_forward_hook(capture).remove)
|
| 81 |
+
self.forward_backbone(model, ids)
|
| 82 |
+
if any(len(values) != 1 for values in captured):
|
| 83 |
+
raise ValueError('Ogni router deve essere eseguito esattamente una volta per sonda.')
|
| 84 |
+
return [values[0] for values in captured]
|
| 85 |
+
|
| 86 |
+
def validate_rows(self, model, rows):
|
| 87 |
+
layers = self.blocks(model)
|
| 88 |
+
routing = self.topology(model.config)
|
| 89 |
+
top_k, total = routing['experts_per_token'], routing['experts_per_layer']
|
| 90 |
+
if not isinstance(rows, list) or len(rows) != len(layers):
|
| 91 |
+
raise ValueError('La maschera deve contenere una lista per ogni layer MoE, in ordine.')
|
| 92 |
+
for row in rows:
|
| 93 |
+
if (not isinstance(row, list) or not top_k <= len(row) <= total
|
| 94 |
+
or any(type(i) is not int or not 0 <= i < total for i in row)
|
| 95 |
+
or row != sorted(set(row)) or len(row) != len(rows[0])):
|
| 96 |
+
raise ValueError('Maschera non valida: ID unici ordinati, budget uniforme >= top-k.')
|
| 97 |
+
return layers
|
| 98 |
+
|
| 99 |
+
@contextmanager
|
| 100 |
+
def masked(self, model, rows):
|
| 101 |
+
layers = self.validate_rows(model, rows)
|
| 102 |
+
with ExitStack() as stack:
|
| 103 |
+
for block, ids in zip(layers, rows):
|
| 104 |
+
gate = self.router(block)
|
| 105 |
+
if len(ids) == gate.out_features:
|
| 106 |
+
continue
|
| 107 |
+
excluded = torch.ones(gate.out_features, device=gate.weight.device, dtype=torch.bool)
|
| 108 |
+
excluded[ids] = False
|
| 109 |
+
|
| 110 |
+
def mask_logits(module, args, logits, excluded=excluded):
|
| 111 |
+
return logits.masked_fill(excluded, -torch.inf)
|
| 112 |
+
|
| 113 |
+
stack.callback(gate.register_forward_hook(mask_logits).remove)
|
| 114 |
+
yield
|
| 115 |
+
|
| 116 |
+
def compact(self, model, rows):
|
| 117 |
+
layers = self.validate_rows(model, rows)
|
| 118 |
+
keep = len(rows[0])
|
| 119 |
+
for block, ids in zip(layers, rows):
|
| 120 |
+
old = self.router(block)
|
| 121 |
+
index = torch.tensor(ids, device=old.weight.device)
|
| 122 |
+
gate = nn.Linear(old.in_features, keep, bias=False, device=old.weight.device, dtype=old.weight.dtype)
|
| 123 |
+
gate.weight = nn.Parameter(old.weight.index_select(0, index), requires_grad=old.weight.requires_grad)
|
| 124 |
+
write_path(block, self.layout['router'], gate)
|
| 125 |
+
write_path(block, self.layout['experts'], nn.ModuleList([self.experts(block)[i] for i in ids]))
|
| 126 |
+
write_path(block, self.layout['count'], keep)
|
| 127 |
+
write_path(model.config, self.spec['config']['experts'], keep)
|
| 128 |
+
if hasattr(model, 'num_experts'):
|
| 129 |
+
model.num_experts = keep
|
| 130 |
+
model.config.moediet_architecture = copy.deepcopy(self.spec)
|
| 131 |
+
model.eval()
|
| 132 |
+
|
| 133 |
+
@torch.inference_mode()
|
| 134 |
+
def verify_contract(self, model, ids):
|
| 135 |
+
"""Check actual native MoE outputs against the declared routing mathematics."""
|
| 136 |
+
layers = self.blocks(model)
|
| 137 |
+
seen = [0] * len(layers)
|
| 138 |
+
peak = [0.0]
|
| 139 |
+
with ExitStack() as stack:
|
| 140 |
+
for i, block in enumerate(layers):
|
| 141 |
+
def check(module, args, output, i=i):
|
| 142 |
+
hidden = args[0]
|
| 143 |
+
flat = hidden.reshape(-1, hidden.shape[-1])
|
| 144 |
+
weights, chosen = self.weights(module, self.router(module)(flat))
|
| 145 |
+
weights = weights.to(flat.dtype)
|
| 146 |
+
result = torch.zeros_like(flat)
|
| 147 |
+
for expert_id in chosen.unique().tolist():
|
| 148 |
+
tokens, slots = torch.where(chosen == expert_id)
|
| 149 |
+
values = self.experts(module)[expert_id](flat[tokens]) * weights[tokens, slots, None]
|
| 150 |
+
result.index_add_(0, tokens, values.to(flat.dtype))
|
| 151 |
+
for shared in self.spec['shared_experts']:
|
| 152 |
+
result += read_path(module, shared['gate'])(flat).sigmoid() * read_path(module, shared['module'])(flat)
|
| 153 |
+
native = output[0] if isinstance(output, tuple) else output
|
| 154 |
+
result = result.reshape(hidden.shape)
|
| 155 |
+
if (native.shape != result.shape or not torch.isfinite(native).all()
|
| 156 |
+
or not torch.allclose(native, result, **tolerances(flat.dtype))):
|
| 157 |
+
raise ValueError(f'Il blocco MoE {i} non rispetta la matematica del profilo.')
|
| 158 |
+
peak[0] = max(peak[0], (native - result).abs().max().item())
|
| 159 |
+
seen[i] += 1
|
| 160 |
+
stack.callback(block.register_forward_hook(check).remove)
|
| 161 |
+
self.forward_backbone(model, ids)
|
| 162 |
+
if seen != [1] * len(layers):
|
| 163 |
+
raise ValueError('Verifica incompleta dei blocchi MoE.')
|
| 164 |
+
return {'passed': True, 'tokens': ids.numel(), 'max_abs_delta': peak[0],
|
| 165 |
+
'tolerance': tolerances(model.get_input_embeddings().weight.dtype)}
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def adapter_for(model_or_config, requested=None):
|
| 169 |
+
config = getattr(model_or_config, 'config', model_or_config)
|
| 170 |
+
return ModuleListAdapter(resolve_profile(config, requested))
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/architecture.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned, declarative architecture profiles. No torch import in the launcher."""
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
PROFILES = Path(__file__).resolve().parent / 'architectures'
|
| 11 |
+
IMPLEMENTATION = 'softmax_topk_modulelist_v1'
|
| 12 |
+
BUILTINS = ('olmoe', 'qwen2_moe', 'qwen3_moe', 'qwen3_next', 'qwen4_exp')
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def read_path(obj, path):
|
| 16 |
+
for name in path.split('.') if path else ():
|
| 17 |
+
try:
|
| 18 |
+
obj = obj[name] if isinstance(obj, dict) else getattr(obj, name)
|
| 19 |
+
except (KeyError, AttributeError) as error:
|
| 20 |
+
raise ValueError(f'Campo o modulo mancante: {path}') from error
|
| 21 |
+
return obj
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def write_path(obj, path, value):
|
| 25 |
+
parent, _, name = path.rpartition('.')
|
| 26 |
+
obj = read_path(obj, parent)
|
| 27 |
+
if isinstance(obj, dict):
|
| 28 |
+
obj[name] = value
|
| 29 |
+
else:
|
| 30 |
+
setattr(obj, name, value)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _keys(obj, required, optional=()):
|
| 34 |
+
if not isinstance(obj, dict) or set(obj) - set(required) - set(optional) or set(required) - set(obj):
|
| 35 |
+
raise ValueError(f'Profilo architettura: chiavi richieste {sorted(required)}, opzionali {sorted(optional)}.')
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _path(value):
|
| 39 |
+
if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)*', value):
|
| 40 |
+
raise ValueError(f'Percorso dichiarativo non valido: {value!r}')
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def load_profile(value=None, model_type=None):
|
| 44 |
+
if value is None or value == 'auto':
|
| 45 |
+
if model_type not in BUILTINS:
|
| 46 |
+
raise ValueError(f'Architettura {model_type!r} non supportata. Specificare un profilo compatibile.')
|
| 47 |
+
value = model_type
|
| 48 |
+
if isinstance(value, str) and value.lstrip().startswith('{'):
|
| 49 |
+
value = json.loads(value)
|
| 50 |
+
if isinstance(value, dict):
|
| 51 |
+
spec = copy.deepcopy(value)
|
| 52 |
+
else:
|
| 53 |
+
path = PROFILES / f'{value}.json' if value in BUILTINS else Path(value)
|
| 54 |
+
spec = json.loads(path.read_text(encoding='utf-8-sig'))
|
| 55 |
+
_keys(spec, {'schema_version', 'id', 'model_type', 'implementation'},
|
| 56 |
+
{'reason', 'transformers_version', 'layout', 'config', 'layer_selection', 'shared_experts'})
|
| 57 |
+
if type(spec['schema_version']) is not int or spec['schema_version'] != 1:
|
| 58 |
+
raise ValueError('Versione del profilo architettura non supportata.')
|
| 59 |
+
for field in ('id', 'model_type', 'implementation'):
|
| 60 |
+
if not isinstance(spec[field], str) or not spec[field].strip():
|
| 61 |
+
raise ValueError(f'{field} deve essere una stringa non vuota.')
|
| 62 |
+
if model_type and spec['model_type'] != model_type:
|
| 63 |
+
raise ValueError(f"Profilo {spec['id']} per {spec['model_type']}, checkpoint {model_type}.")
|
| 64 |
+
if spec['implementation'] == 'unsupported':
|
| 65 |
+
raise ValueError(f"{spec['model_type']}: {spec.get('reason', 'adattatore non implementato')}")
|
| 66 |
+
if spec['implementation'] != IMPLEMENTATION:
|
| 67 |
+
raise ValueError(f"Implementazione non disponibile: {spec['implementation']}")
|
| 68 |
+
_keys(spec.get('layout'), {'backbone', 'layers', 'block', 'router', 'experts', 'count', 'top_k', 'normalize'})
|
| 69 |
+
_keys(spec.get('config'), {'layers', 'experts', 'top_k', 'normalize', 'context'})
|
| 70 |
+
for mapping in (spec['layout'], spec['config']):
|
| 71 |
+
for path in mapping.values():
|
| 72 |
+
_path(path)
|
| 73 |
+
if spec.get('layer_selection') not in ('all', 'qwen_sparse_step'):
|
| 74 |
+
raise ValueError('layer_selection non supportata.')
|
| 75 |
+
if not isinstance(spec.get('transformers_version'), str) or not re.fullmatch(r'\d+\.\d+\.\d+', spec['transformers_version']):
|
| 76 |
+
raise ValueError('Il profilo richiede una versione Transformers esatta.')
|
| 77 |
+
if not isinstance(spec.get('shared_experts'), list):
|
| 78 |
+
raise ValueError('shared_experts deve essere una lista (anche vuota).')
|
| 79 |
+
for shared in spec['shared_experts']:
|
| 80 |
+
_keys(shared, {'module', 'gate', 'activation'})
|
| 81 |
+
_path(shared['module'])
|
| 82 |
+
_path(shared['gate'])
|
| 83 |
+
if shared['activation'] != 'sigmoid':
|
| 84 |
+
raise ValueError('Solo shared expert con gate sigmoid supportati.')
|
| 85 |
+
return spec
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def profile_hash(spec):
|
| 89 |
+
return hashlib.sha256(json.dumps(spec, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def resolve_profile(cfg, requested=None):
|
| 93 |
+
embedded = cfg.get('moediet_architecture') if isinstance(cfg, dict) else getattr(cfg, 'moediet_architecture', None)
|
| 94 |
+
selected = requested if requested is not None else embedded
|
| 95 |
+
spec = load_profile(selected, read_path(cfg, 'model_type'))
|
| 96 |
+
if embedded and requested is not None and spec != load_profile(embedded, read_path(cfg, 'model_type')):
|
| 97 |
+
raise ValueError('Il profilo richiesto differisce da quello incorporato nel checkpoint.')
|
| 98 |
+
return spec
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def layer_indices(cfg, spec):
|
| 102 |
+
count = read_path(cfg, spec['config']['layers'])
|
| 103 |
+
if type(count) is not int or count < 1:
|
| 104 |
+
raise ValueError('Numero di layer non valido.')
|
| 105 |
+
if spec['layer_selection'] == 'all':
|
| 106 |
+
return list(range(count))
|
| 107 |
+
excluded, step = read_path(cfg, 'mlp_only_layers'), read_path(cfg, 'decoder_sparse_step')
|
| 108 |
+
if (type(step) is not int or step < 1 or not isinstance(excluded, list)
|
| 109 |
+
or any(type(i) is not int or not 0 <= i < count for i in excluded)):
|
| 110 |
+
raise ValueError('Selezione dei layer MoE non valida.')
|
| 111 |
+
return [i for i in range(count) if i not in excluded and (i + 1) % step == 0]
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def topology(cfg, spec):
|
| 115 |
+
fields = spec['config']
|
| 116 |
+
total, top_k = read_path(cfg, fields['experts']), read_path(cfg, fields['top_k'])
|
| 117 |
+
norm = read_path(cfg, fields['normalize'])
|
| 118 |
+
indices = layer_indices(cfg, spec)
|
| 119 |
+
if (not indices or type(total) is not int or type(top_k) is not int or not 1 <= top_k <= total
|
| 120 |
+
or type(norm) is not bool):
|
| 121 |
+
raise ValueError('Checkpoint senza layer MoE o con routing non valido.')
|
| 122 |
+
context = read_path(cfg, fields['context'])
|
| 123 |
+
if type(context) is not int or context < 1:
|
| 124 |
+
raise ValueError('Lunghezza del contesto non valida.')
|
| 125 |
+
return {'num_layers': len(indices), 'experts_per_layer': total, 'experts_per_token': top_k,
|
| 126 |
+
'norm_topk_prob': norm, 'layer_indices': indices}
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def budgets_for(total, top_k, requested=None, fractions=None):
|
| 130 |
+
if type(total) is not int or type(top_k) is not int or not 1 <= top_k <= total:
|
| 131 |
+
raise ValueError('Numero di esperti o top-k del modello non valido.')
|
| 132 |
+
if requested is not None and fractions is not None:
|
| 133 |
+
raise ValueError('Usare budgets oppure keep_fractions, non entrambi.')
|
| 134 |
+
if fractions is not None:
|
| 135 |
+
if (not isinstance(fractions, list) or not fractions or any(type(x) not in (int, float)
|
| 136 |
+
or not math.isfinite(x) or not 0 < x <= 1 for x in fractions)):
|
| 137 |
+
raise ValueError('keep_fractions deve contenere frazioni finite in (0, 1].')
|
| 138 |
+
requested = [math.ceil(total * x) for x in fractions]
|
| 139 |
+
if requested is None:
|
| 140 |
+
requested, value = [], top_k
|
| 141 |
+
while value < total:
|
| 142 |
+
requested.append(value)
|
| 143 |
+
value *= 2
|
| 144 |
+
elif not isinstance(requested, list) or not requested:
|
| 145 |
+
raise ValueError('budgets deve essere una lista non vuota.')
|
| 146 |
+
if any(type(x) is not int or not top_k <= x <= total for x in requested):
|
| 147 |
+
raise ValueError(f'Ogni budget deve essere fra {top_k} (routing nativo) e {total}.')
|
| 148 |
+
return sorted(set(requested) | {total})
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# Profiles whose native GGUF export path is verified end-to-end (fixture tests):
|
| 152 |
+
# 'olmoe' (AllenAI OLMoE 0125) and 'qwen3_next' (Qwen3-Next, llama.cpp Qwen3NextModel).
|
| 153 |
+
EXPORT_PROFILES = ('olmoe', 'qwen3_next')
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def check_export(spec, quantization):
|
| 157 |
+
if quantization:
|
| 158 |
+
# Only the exact built-in layouts have a verified native GGUF exporter.
|
| 159 |
+
if all(spec != load_profile(name) for name in EXPORT_PROFILES):
|
| 160 |
+
raise ValueError('Export GGUF non supportato per questo profilo. Usare export.format=hf o quantization=null.')
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def validate_checkpoint_config(cfg, requested=None, quantization=None):
|
| 164 |
+
spec = resolve_profile(cfg, requested)
|
| 165 |
+
if (cfg.get('quantization_config') if isinstance(cfg, dict) else getattr(cfg, 'quantization_config', None)):
|
| 166 |
+
raise ValueError('Il pruning richiede pesi HF non quantizzati.')
|
| 167 |
+
routing = topology(cfg, spec)
|
| 168 |
+
check_export(spec, quantization)
|
| 169 |
+
return spec, routing
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/architectures/olmoe.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": 1,
|
| 3 |
+
"id": "olmoe-transformers-4.55.4",
|
| 4 |
+
"model_type": "olmoe",
|
| 5 |
+
"implementation": "softmax_topk_modulelist_v1",
|
| 6 |
+
"transformers_version": "4.55.4",
|
| 7 |
+
"layout": {
|
| 8 |
+
"backbone": "model", "layers": "model.layers", "block": "mlp",
|
| 9 |
+
"router": "gate", "experts": "experts", "count": "num_experts",
|
| 10 |
+
"top_k": "top_k", "normalize": "norm_topk_prob"
|
| 11 |
+
},
|
| 12 |
+
"config": {
|
| 13 |
+
"layers": "num_hidden_layers", "experts": "num_experts",
|
| 14 |
+
"top_k": "num_experts_per_tok", "normalize": "norm_topk_prob",
|
| 15 |
+
"context": "max_position_embeddings"
|
| 16 |
+
},
|
| 17 |
+
"layer_selection": "all",
|
| 18 |
+
"shared_experts": []
|
| 19 |
+
}
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/architectures/qwen2_moe.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": 1,
|
| 3 |
+
"id": "qwen2-moe-transformers-4.55.4",
|
| 4 |
+
"model_type": "qwen2_moe",
|
| 5 |
+
"implementation": "softmax_topk_modulelist_v1",
|
| 6 |
+
"transformers_version": "4.55.4",
|
| 7 |
+
"layout": {
|
| 8 |
+
"backbone": "model", "layers": "model.layers", "block": "mlp",
|
| 9 |
+
"router": "gate", "experts": "experts", "count": "num_experts",
|
| 10 |
+
"top_k": "top_k", "normalize": "norm_topk_prob"
|
| 11 |
+
},
|
| 12 |
+
"config": {
|
| 13 |
+
"layers": "num_hidden_layers", "experts": "num_experts",
|
| 14 |
+
"top_k": "num_experts_per_tok", "normalize": "norm_topk_prob",
|
| 15 |
+
"context": "max_position_embeddings"
|
| 16 |
+
},
|
| 17 |
+
"layer_selection": "qwen_sparse_step",
|
| 18 |
+
"shared_experts": [{"module": "shared_expert", "gate": "shared_expert_gate", "activation": "sigmoid"}]
|
| 19 |
+
}
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/architectures/qwen3_moe.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": 1,
|
| 3 |
+
"id": "qwen3-moe-transformers-4.55.4",
|
| 4 |
+
"model_type": "qwen3_moe",
|
| 5 |
+
"implementation": "softmax_topk_modulelist_v1",
|
| 6 |
+
"transformers_version": "4.55.4",
|
| 7 |
+
"layout": {
|
| 8 |
+
"backbone": "model", "layers": "model.layers", "block": "mlp",
|
| 9 |
+
"router": "gate", "experts": "experts", "count": "num_experts",
|
| 10 |
+
"top_k": "top_k", "normalize": "norm_topk_prob"
|
| 11 |
+
},
|
| 12 |
+
"config": {
|
| 13 |
+
"layers": "num_hidden_layers", "experts": "num_experts",
|
| 14 |
+
"top_k": "num_experts_per_tok", "normalize": "norm_topk_prob",
|
| 15 |
+
"context": "max_position_embeddings"
|
| 16 |
+
},
|
| 17 |
+
"layer_selection": "qwen_sparse_step",
|
| 18 |
+
"shared_experts": []
|
| 19 |
+
}
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/architectures/qwen3_next.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": 1,
|
| 3 |
+
"id": "qwen3-next-transformers-4.57.6",
|
| 4 |
+
"model_type": "qwen3_next",
|
| 5 |
+
"implementation": "softmax_topk_modulelist_v1",
|
| 6 |
+
"transformers_version": "4.57.6",
|
| 7 |
+
"layout": {
|
| 8 |
+
"backbone": "model", "layers": "model.layers", "block": "mlp",
|
| 9 |
+
"router": "gate", "experts": "experts", "count": "num_experts",
|
| 10 |
+
"top_k": "top_k", "normalize": "norm_topk_prob"
|
| 11 |
+
},
|
| 12 |
+
"config": {
|
| 13 |
+
"layers": "num_hidden_layers", "experts": "num_experts",
|
| 14 |
+
"top_k": "num_experts_per_tok", "normalize": "norm_topk_prob",
|
| 15 |
+
"context": "max_position_embeddings"
|
| 16 |
+
},
|
| 17 |
+
"layer_selection": "qwen_sparse_step",
|
| 18 |
+
"shared_experts": [
|
| 19 |
+
{"module": "shared_expert", "gate": "shared_expert_gate", "activation": "sigmoid"}
|
| 20 |
+
]
|
| 21 |
+
}
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/architectures/qwen4_exp.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": 1,
|
| 3 |
+
"id": "qwen4-exp-not-supported",
|
| 4 |
+
"model_type": "qwen4_exp",
|
| 5 |
+
"implementation": "unsupported",
|
| 6 |
+
"reason": "Qwen3.8-Flash-Next richiede un adattatore per qwen4_exp, esperti fusi e runtime compatibile. Non verificato con Transformers 4.55.4: il Job viene bloccato prima del download dei pesi e della spesa di calcolo. I profili qwen2_moe e qwen3_moe non sono sostituti compatibili."
|
| 7 |
+
}
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/corpus.json
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"profile": {
|
| 3 |
+
"agents": [
|
| 4 |
+
"An agent retries a failed tool call with byte-identical arguments five times and then gives up. Explain how to attribute the failure between planner, tool contract, and retry policy, and design bounded retries with escalation.",
|
| 5 |
+
"Two agent workers read a shared task queue and both start the same item. Explain the claim race and design idempotent claiming with a lease and expiry.",
|
| 6 |
+
"An agent's context fills with old tool outputs and it loses track of the original goal. Explain context degradation and design a compaction step that writes an explicit state note before discarding history.",
|
| 7 |
+
"A twelve-step plan derails at step three, but the agent keeps executing the remaining steps. Explain why step-local success hides global failure, and design replanning triggers with checkpoints.",
|
| 8 |
+
"An agent delegates a subtask to a helper agent that returns a confident but wrong answer. Explain verification of delegated results and design a review step proportional to the risk of the subtask.",
|
| 9 |
+
"An agent declares success on a goal with ambiguous success criteria. Explain goal operationalization and design explicit acceptance checks that must pass before termination.",
|
| 10 |
+
"Across sessions, an agent's memory accumulates outdated facts that keep resurfacing. Explain memory write policies and design supersession so corrected facts replace stale ones.",
|
| 11 |
+
"An agent oscillates between two states, alternating the same two actions without progress. Explain cycle detection in the trajectory and design a termination rule that forces a different strategy."
|
| 12 |
+
],
|
| 13 |
+
"tools": [
|
| 14 |
+
"A tool schema declares its date argument as a string, and the model passes 'tomorrow'. Explain schema validation versus semantic validation, and design a normalization layer with clear errors.",
|
| 15 |
+
"Two tools with overlapping responsibilities return conflicting results for the same query. Explain tool granularity and design a single source of truth with documented precedence.",
|
| 16 |
+
"A retry after a timeout causes a destructive delete tool to run twice. Explain idempotency keys and design the tool contract so repeated calls are safe.",
|
| 17 |
+
"A tool returns fifty thousand tokens and the instruction is buried. Explain output shaping and design summarized tool responses with pointers to full data.",
|
| 18 |
+
"Mid-session, a tool starts returning 401 and the agent loops on the same call. Explain credential lifecycle and design refresh handling with a limited re-auth budget.",
|
| 19 |
+
"The agent issues parallel tool calls that have a hidden dependency, and they execute in the wrong order. Explain dependency declaration and design the scheduler to respect explicit prerequisites.",
|
| 20 |
+
"A sandboxed code-execution tool can still read the host's environment variables. Explain sandbox boundaries and design the minimal filesystem, network, and environment policy.",
|
| 21 |
+
"A prompt demands strict JSON, but the model wraps it in a markdown fence and downstream parsing crashes. Explain constrained decoding and output repair, and design a tolerant extraction step."
|
| 22 |
+
],
|
| 23 |
+
"evals": [
|
| 24 |
+
"An agent scores 95% on unit-style tool tests but fails long-horizon tasks. Explain the gap between capability probes and trajectory quality, and design a two-level eval suite.",
|
| 25 |
+
"A trace shows the agent took forty steps for a task that needs five, with no failure logged. Explain efficiency metrics and design step and cost budgets per task class.",
|
| 26 |
+
"After a prompt change, last week's 90% eval score drops to 60%. Explain eval versioning and design a regression gate that blocks the change.",
|
| 27 |
+
"An agent learns to satisfy the automated grader by matching expected keywords without solving the task. Explain reward hacking and design held-out and dual grading.",
|
| 28 |
+
"Offline evals look strong, but production users report degraded behavior. Explain distribution shift and design production sampling with canary tasks.",
|
| 29 |
+
"Eval runs are flaky: identical inputs produce different trajectories because tool latency varies. Explain nondeterminism sources and design stable pass criteria.",
|
| 30 |
+
"The full eval harness takes six hours per run, so engineers skip it. Explain stratified sampling and design a fast gate that preserves coverage.",
|
| 31 |
+
"Human reviewers disagree with the automated grader on borderline trajectories. Explain adjudication and design a calibration set that ties grader scores to human judgment."
|
| 32 |
+
],
|
| 33 |
+
"__control__": [
|
| 34 |
+
"A houseplant develops yellow lower leaves while the soil stays wet for days. Explain competing causes and propose observations to discriminate between them before changing the care routine.",
|
| 35 |
+
"Seedlings on a windowsill lean strongly to one side. Explain the underlying stimulus and compare rotating the tray with improving light distribution.",
|
| 36 |
+
"A compass bearing disagrees with the map's true-north lines. Explain declination and work through converting one bearing into the other.",
|
| 37 |
+
"Two landmarks on a hiking map appear misaligned with the terrain. Explain how to resect a position using two bearings and estimate the error.",
|
| 38 |
+
"Two guitar strings sound beats when played together. Explain interference and describe how to bring them to the same pitch.",
|
| 39 |
+
"A melody in one key must be transposed for a singer. Explain the interval relationships and transpose a short phrase step by step.",
|
| 40 |
+
"A calendar application must span a leap day. Explain how date arithmetic changes and give a concrete check for a range crossing February 29.",
|
| 41 |
+
"Two wall clocks disagree after one changes battery. Explain drift and design a reproducible check to decide which clock to trust."
|
| 42 |
+
]
|
| 43 |
+
},
|
| 44 |
+
"select": {
|
| 45 |
+
"agents": [
|
| 46 |
+
"An agent's loop has no maximum iteration count and it runs overnight on a trivial task. Explain termination conditions and give a concrete design combining step limits, progress checks, and budget caps.",
|
| 47 |
+
"A planner emits a full plan before seeing any tool results. Explain replan-on-evidence and rewrite the loop so each tool result can revise the remaining plan.",
|
| 48 |
+
"Two cooperating agents deadlock, each waiting for the other's partial result. Explain dependency inversion and give a concrete protocol with explicit handoff points.",
|
| 49 |
+
"An agent picks the first plausible action instead of comparing alternatives. Explain option comparison and give a small scoring scheme the agent can apply per decision.",
|
| 50 |
+
"A sub-agent is spawned with the entire parent context and duplicates its work. Explain context inheritance and give a minimal brief format for delegation.",
|
| 51 |
+
"The agent cannot tell whether a tool failure is permanent or transient. Explain error classification and give a decision table for retry, alternative tool, and abort.",
|
| 52 |
+
"An agent's self-summary after a long task contradicts its own earlier notes. Explain provenance in state notes and give a merge rule for conflicting summaries.",
|
| 53 |
+
"A user interrupts an agent mid-task with a new priority. Explain interruption handling and give a design that parks state safely and resumes or rolls back cleanly."
|
| 54 |
+
],
|
| 55 |
+
"tools": [
|
| 56 |
+
"A search tool accepts a free-text query and returns irrelevant results half the time. Explain query construction and give a concrete reformulation strategy with filters.",
|
| 57 |
+
"A code-editing tool applies patches that sometimes corrupt nearby lines. Explain patch scoping and give a design using anchors plus a verification read-back.",
|
| 58 |
+
"Tool arguments come from user text and may contain injection attempts. Explain prompt-injection boundaries and give a validation scheme separating instructions from data.",
|
| 59 |
+
"A file-writing tool silently truncates paths beyond a length limit. Explain contract documentation and give a preflight validation the agent can run before the call.",
|
| 60 |
+
"Two versions of the same tool exist after a migration, with different semantics. Explain version pinning and give a discovery step that resolves which tool to call.",
|
| 61 |
+
"A tool's latency varies from milliseconds to minutes. Explain timeout policy and give a design with per-tool budgets and asynchronous completion checks.",
|
| 62 |
+
"An API tool paginates results and the agent stops after the first page. Explain completeness checks and give a loop design that continues until an explicit end marker.",
|
| 63 |
+
"A tool returns an error enum the model has never seen. Explain graceful degradation and give a fallback chain from retry to alternative tool to asking the user."
|
| 64 |
+
],
|
| 65 |
+
"evals": [
|
| 66 |
+
"You inherit an agent eval suite where every task passes trivially. Explain task difficulty calibration and give a method to introduce discriminating cases.",
|
| 67 |
+
"An eval asserts on intermediate steps, but agents reach the goal by different valid routes. Explain outcome-based grading and give a rubric that tolerates path variation.",
|
| 68 |
+
"Eval scores vary between runs by more than the claimed improvement. Explain statistical significance and give a design with repeated runs and confidence intervals.",
|
| 69 |
+
"A new capability is added but no eval covers it, so a regression ships. Explain coverage mapping and give a rule linking every tool and behavior to at least one eval.",
|
| 70 |
+
"Grader code is edited in the same commit as the agent it grades. Explain separation of concerns and give a review workflow that keeps graders independent.",
|
| 71 |
+
"An eval environment leaks state between consecutive tasks. Explain isolation and give a checklist for resetting filesystem, memory, and credentials per case.",
|
| 72 |
+
"Trajectories are stored but never mined after a failure. Explain failure analysis and give a tagging scheme that clusters root causes across runs.",
|
| 73 |
+
"The eval reports an average score that hides a catastrophic tail. Explain distributional reporting and give a dashboard with percentiles and worst cases."
|
| 74 |
+
],
|
| 75 |
+
"__control__": [
|
| 76 |
+
"A potted tomato plant flowers but sets no fruit. Explain pollination and growing conditions, and propose two observations to identify the limiting factor.",
|
| 77 |
+
"Stored seeds from last year fail to germinate. Explain viability testing and give a simple protocol with a control batch.",
|
| 78 |
+
"A hiker must estimate walking time from a contour map. Explain gradient and distance trade-offs and give a worked estimate for a short section.",
|
| 79 |
+
"Wind pushes a boat off its intended bearing. Explain leeway and give a correction procedure using a compass course.",
|
| 80 |
+
"A chord in a song sounds unstable before resolving. Explain tension and resolution and identify the likely chord function.",
|
| 81 |
+
"A recording sounds out of tune against an instrument. Explain beat frequencies and give a step-by-step tuning check.",
|
| 82 |
+
"Three friends split a bill unevenly after sharing items. Explain a fair reconciliation and give a concrete calculation.",
|
| 83 |
+
"Five recorded distances have one obvious outlier. Explain robust averaging and give a rule for deciding whether to exclude it."
|
| 84 |
+
]
|
| 85 |
+
},
|
| 86 |
+
"audit": {
|
| 87 |
+
"agents": [
|
| 88 |
+
"A pruned agent model answers tool-calling prompts as fluently as the original, but audit traces show it invents tool names under pressure. Explain which capability the probe scores actually measure and design an audit that catches hallucinated tools.",
|
| 89 |
+
"After pruning, the agent still solves familiar tasks but ignores the stated success criteria in novel ones. Explain generalization versus memorization in trajectories and design an audit with unseen goals.",
|
| 90 |
+
"The original agent escalates to a human when uncertain; the pruned one always guesses. Explain abstention as a behavior and design an audit that rewards correct refusals.",
|
| 91 |
+
"A masked agent passes identity checks but produces longer, wandering plans. Explain plan efficiency as a first-class metric and design an audit comparing step counts on fixed tasks.",
|
| 92 |
+
"Two pruned variants differ in size by a factor of two but score the same on aggregate. Explain per-task decomposition and design an audit that finds where each variant wins and loses.",
|
| 93 |
+
"The agent's tone and formatting drift after pruning while answers stay correct. Explain surface behavior as a quality dimension and design an audit with style constraints.",
|
| 94 |
+
"Under multi-turn conversation, the pruned agent forgets earlier constraints faster. Explain context retention and design an audit with constraint checks at increasing depth.",
|
| 95 |
+
"An agent that must ask clarifying questions instead answers immediately with assumptions. Explain clarification behavior and design an audit with intentionally ambiguous tasks."
|
| 96 |
+
],
|
| 97 |
+
"tools": [
|
| 98 |
+
"A pruned model emits valid JSON for tool calls less often on long contexts. Explain how context length interacts with structured output and design an audit sweeping input sizes.",
|
| 99 |
+
"The model chooses a reasonable but suboptimal tool when a better one exists. Explain tool selection granularity and design an audit with near-miss alternatives.",
|
| 100 |
+
"After pruning, argument values are syntactically valid but semantically wrong more often. Explain value grounding and design an audit that checks arguments against the user's actual data.",
|
| 101 |
+
"The model stops verifying tool results before acting on them. Explain verification behavior and design an audit where tools return subtly wrong data.",
|
| 102 |
+
"Parallel tool calls collapse into sequential ones after pruning, doubling latency. Explain call planning and design an audit measuring independence detection.",
|
| 103 |
+
"The model mishandles a new tool added after training. Explain tool generalization and design an audit with held-out tools described only by schema.",
|
| 104 |
+
"Error recovery degrades: the model repeats a failing call instead of switching strategy. Explain recovery diversity and design an audit injecting transient and permanent failures.",
|
| 105 |
+
"The pruned model leaks its reasoning about tool credentials into visible output. Explain information boundary behavior and design an audit probing for secret material."
|
| 106 |
+
],
|
| 107 |
+
"evals": [
|
| 108 |
+
"The pruned model's eval scores match the original on the benchmark suite, but a manual review of twenty trajectories finds systematic reasoning shortcuts. Explain the limits of aggregate scoring and design a trajectory audit.",
|
| 109 |
+
"An audit compares masked and compacted models on the same eval but with different random seeds. Explain seed sensitivity and design a comparison with matched seeds and repetitions.",
|
| 110 |
+
"The control group improves when the target group does not, suggesting the eval moved. Explain control-group interpretation and design an audit that isolates model effects from suite effects.",
|
| 111 |
+
"KL divergence between original and pruned log-probabilities is tiny, yet users report worse task success. Explain the gap between token-level and trajectory-level fidelity and design an outcome audit.",
|
| 112 |
+
"An audit pass at budget 384 fails the KL threshold while budget 496 passes, but quality judges prefer 384's outputs. Explain threshold governance and design a dual-gate audit with both metrics.",
|
| 113 |
+
"The audit corpus over-represents short tasks, so pruning harm on long tasks is invisible. Explain coverage bias and design a stratified audit by task horizon.",
|
| 114 |
+
"A pruned agent passes all evals but its cost per solved task doubles. Explain efficiency-adjusted quality and design an audit that reports quality per unit cost.",
|
| 115 |
+
"The audit finds failures concentrated in one tool cluster. Explain slice analysis and design an audit report that breaks scores down by capability slice."
|
| 116 |
+
],
|
| 117 |
+
"__control__": [
|
| 118 |
+
"A shrub shows frost damage on new shoots while woody parts look intact. Explain how to assess damage over time and why removing every affected branch immediately may be premature.",
|
| 119 |
+
"A clay pot dries unevenly, with one side always wet. Explain soil structure and porosity and propose a check before repotting.",
|
| 120 |
+
"A map scale reads 1:25000 and a trail section measures six centimetres. Explain the conversion and give the real distance with a sanity check.",
|
| 121 |
+
"Two position fixes from different landmarks disagree slightly. Explain error sources and give a rule for choosing the more reliable fix.",
|
| 122 |
+
"A melody transposed up a major third exceeds the instrument's range. Explain octave displacement and give a rearrangement strategy.",
|
| 123 |
+
"A rhythm in six-eight time is hard to count. Explain compound meter and give a counting method that groups the beats.",
|
| 124 |
+
"A recipe scaled for three people must serve five. Explain proportional scaling and give the adjusted quantities for two ingredients.",
|
| 125 |
+
"A temperature conversion between Celsius and Fahrenheit looks wrong. Explain the linear transform and give a reversible check with one known value."
|
| 126 |
+
]
|
| 127 |
+
}
|
| 128 |
+
}
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/fidelity.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compare next-token distributions on held-out, original-model greedy continuations."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from routing import continuation, encode
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class Trace:
|
| 12 |
+
group: str
|
| 13 |
+
prefix: torch.Tensor # Input through the penultimate token, on CPU.
|
| 14 |
+
original: torch.Tensor # Log probabilities for the generated positions, on CPU.
|
| 15 |
+
prompt_len: int = 0 # Encoded prompt tokens; continuation starts at prefix[prompt_len - 1].
|
| 16 |
+
generated: torch.Tensor = None # Continuation token ids incl. the last position, on CPU.
|
| 17 |
+
prompt_text: str = '' # Decoded encoded prompt; replay text for llama-cli.
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@torch.inference_mode()
|
| 21 |
+
def log_probs(model, prefix, steps):
|
| 22 |
+
out = model(input_ids=prefix.to(model.get_input_embeddings().weight.device), use_cache=False,
|
| 23 |
+
output_router_logits=False, logits_to_keep=steps, return_dict=True)
|
| 24 |
+
logp = out.logits[0].float().log_softmax(-1).cpu()
|
| 25 |
+
if logp.shape[0] != steps or not torch.isfinite(logp).all():
|
| 26 |
+
raise ValueError('Log-probabilità mancanti o non finite.')
|
| 27 |
+
return logp
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@torch.inference_mode()
|
| 31 |
+
def make_traces(model, tokenizer, groups, steps):
|
| 32 |
+
traces = []
|
| 33 |
+
for group, prompts in groups.items():
|
| 34 |
+
for prompt in prompts:
|
| 35 |
+
ids = encode(model, tokenizer, prompt, reserve=steps)
|
| 36 |
+
sequence = continuation(model, tokenizer, ids, steps)
|
| 37 |
+
used = sequence.shape[1] - ids.shape[1] # EOS may shorten the reference.
|
| 38 |
+
if used < 1:
|
| 39 |
+
raise ValueError('Il modello di riferimento ha generato una continuazione vuota.')
|
| 40 |
+
prefix = sequence[:, :-1].cpu()
|
| 41 |
+
generated = sequence[0, ids.shape[1]:].cpu()
|
| 42 |
+
prompt_text = tokenizer.decode(ids[0], skip_special_tokens=False)
|
| 43 |
+
traces.append(Trace(group, prefix, log_probs(model, prefix, used),
|
| 44 |
+
ids.shape[1], generated, prompt_text))
|
| 45 |
+
return traces
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def replay(model, traces):
|
| 49 |
+
return [log_probs(model, trace.prefix, len(trace.original)) for trace in traces]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def compare(traces, candidate, reference=None):
|
| 53 |
+
if reference is None:
|
| 54 |
+
reference = [t.original for t in traces]
|
| 55 |
+
totals = {}
|
| 56 |
+
for trace, base, new in zip(traces, reference, candidate, strict=True):
|
| 57 |
+
# Sum over vocab then positions; per-group means use the number of generated positions.
|
| 58 |
+
base, new = base.double().log_softmax(-1), new.double().log_softmax(-1)
|
| 59 |
+
difference = base - new
|
| 60 |
+
delta = (base.exp() * difference).sum().item()
|
| 61 |
+
hits = (base.argmax(-1) == new.argmax(-1)).sum().item()
|
| 62 |
+
row = totals.setdefault(trace.group, {'prompts': 0, 'tokens': 0, 'kl_sum': 0.0, 'hits': 0, 'peak': 0.0})
|
| 63 |
+
row['prompts'] += 1
|
| 64 |
+
row['tokens'] += len(base)
|
| 65 |
+
row['kl_sum'] += delta
|
| 66 |
+
row['hits'] += hits
|
| 67 |
+
row['peak'] = max(row['peak'], difference.abs().max().item())
|
| 68 |
+
return {name: {'prompts': row['prompts'], 'tokens': row['tokens'],
|
| 69 |
+
'kl_nats_per_token': max(0.0, row['kl_sum'] / row['tokens']),
|
| 70 |
+
'top1_agreement': row['hits'] / row['tokens'],
|
| 71 |
+
'max_abs_logp_delta': row['peak']} for name, row in totals.items()}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def passes(metrics, limit):
|
| 75 |
+
return bool(metrics) and all(m['kl_nats_per_token'] <= limit for m in metrics.values())
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def equivalent(reference, candidate, atol, rtol):
|
| 79 |
+
"""Independent numerical gate: matching KL to the teacher is not sufficient."""
|
| 80 |
+
passed = bool(reference) and len(reference) == len(candidate)
|
| 81 |
+
peak = 0.0
|
| 82 |
+
if passed:
|
| 83 |
+
for base, new in zip(reference, candidate, strict=True):
|
| 84 |
+
if base.shape != new.shape or not torch.isfinite(base).all() or not torch.isfinite(new).all():
|
| 85 |
+
passed = False
|
| 86 |
+
peak = None
|
| 87 |
+
break
|
| 88 |
+
peak = max(peak, (base - new).abs().max().item())
|
| 89 |
+
passed = bool(torch.allclose(base, new, atol=atol, rtol=rtol)) and passed
|
| 90 |
+
return {'passed': passed, 'max_abs_logp_delta': peak, 'atol': atol, 'rtol': rtol}
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/gguf_export.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Export an accepted MoEDiet run to a quantized GGUF using native llama.cpp."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
from collections import Counter
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import re
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
import tempfile
|
| 12 |
+
|
| 13 |
+
from llama_tools import get_tools, sha256
|
| 14 |
+
from architecture import check_export, layer_indices, resolve_profile, topology
|
| 15 |
+
|
| 16 |
+
QTYPES = ('Q4_K_M', 'Q4_0')
|
| 17 |
+
|
| 18 |
+
# GGUF architecture names for the export-verified profiles (see test_qwen3next_export).
|
| 19 |
+
GGUF_ARCH = {'olmoe': 'olmoe', 'qwen3_next': 'qwen3next'}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def model_config(run, report):
|
| 23 |
+
cfg = json.loads((run / 'checkpoint' / 'config.json').read_text(encoding='utf-8'))
|
| 24 |
+
spec = resolve_profile(cfg)
|
| 25 |
+
check_export(spec, True)
|
| 26 |
+
if spec['model_type'] not in GGUF_ARCH:
|
| 27 |
+
raise ValueError(f"Profilo {spec['model_type']} senza exporter GGUF verificato.")
|
| 28 |
+
native = report['routing']
|
| 29 |
+
if (not report.get('checkpoint') or not report.get('checkpoint_audit', {}).get('passed')
|
| 30 |
+
or cfg.get('model_type') != spec['model_type']
|
| 31 |
+
or cfg[spec['layout']['count']] != report['retained_per_layer']
|
| 32 |
+
or cfg[spec['config']['top_k']] != native['experts_per_token']
|
| 33 |
+
or layer_indices(cfg, spec) != native['layer_indices']
|
| 34 |
+
or not native['experts_per_token'] <= report['retained_per_layer'] < native['experts_per_layer']):
|
| 35 |
+
raise ValueError('Il checkpoint non corrisponde al taglio accettato nel report.')
|
| 36 |
+
# The pinned native OLMoE graph has these semantics. Refuse variants it would silently change.
|
| 37 |
+
if spec['model_type'] == 'olmoe' and (
|
| 38 |
+
cfg.get('norm_topk_prob', False) or cfg.get('clip_qkv') is not None or cfg.get('attention_bias', False)
|
| 39 |
+
or cfg.get('rope_scaling') or cfg.get('hidden_act', 'silu') != 'silu'
|
| 40 |
+
or cfg.get('rms_norm_eps', 1e-5) != 1e-5
|
| 41 |
+
or cfg.get('num_key_value_heads', cfg['num_attention_heads']) != cfg['num_attention_heads']):
|
| 42 |
+
raise ValueError('Configurazione OLMoE fuori dal profilo GGUF verificato (AllenAI 0125).')
|
| 43 |
+
return cfg, spec
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def check_gguf(file, source, cfg, spec, qtype):
|
| 47 |
+
sys.path.insert(0, str(source / 'gguf-py'))
|
| 48 |
+
try:
|
| 49 |
+
from gguf import GGUFReader, LlamaFileType
|
| 50 |
+
finally:
|
| 51 |
+
sys.path.pop(0)
|
| 52 |
+
arch = GGUF_ARCH[spec['model_type']]
|
| 53 |
+
reader = GGUFReader(str(file))
|
| 54 |
+
expected = {'general.architecture': arch, 'general.file_type': int(getattr(LlamaFileType, 'MOSTLY_' + qtype)),
|
| 55 |
+
f'{arch}.block_count': cfg[spec['config']['layers']],
|
| 56 |
+
f'{arch}.expert_count': cfg[spec['layout']['count']],
|
| 57 |
+
f'{arch}.expert_used_count': cfg[spec['config']['top_k']]}
|
| 58 |
+
for key, value in expected.items():
|
| 59 |
+
if key not in reader.fields or reader.fields[key].contents() != value:
|
| 60 |
+
raise ValueError(f'Metadato GGUF errato o mancante: {key}')
|
| 61 |
+
names = {f'blk.{i}.ffn_{axis}_exps.weight' for i in topology(cfg, spec)['layer_indices']
|
| 62 |
+
for axis in ('gate', 'up', 'down')}
|
| 63 |
+
experts = {tensor.name: tensor for tensor in reader.tensors if '_exps.weight' in tensor.name}
|
| 64 |
+
if set(experts) != names or any(len(t.shape) != 3 or t.shape[2] != cfg[spec['layout']['count']]
|
| 65 |
+
for t in experts.values()):
|
| 66 |
+
raise ValueError('Tensori degli esperti mancanti o dimensione errata nel GGUF.')
|
| 67 |
+
counts = Counter(t.tensor_type.name for t in experts.values())
|
| 68 |
+
del reader # Release the file handle before any raise (Windows locks the GGUF).
|
| 69 |
+
if counts['Q4_K' if qtype == 'Q4_K_M' else 'Q4_0'] == 0:
|
| 70 |
+
raise ValueError(f'Nessuna matrice degli esperti quantizzata realmente in {qtype}.')
|
| 71 |
+
return dict(counts)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def export_run(run, qtype='Q4_K_M', llama_dir=None, bin_dir=None):
|
| 75 |
+
run = Path(os.path.expandvars(str(run))).expanduser().resolve()
|
| 76 |
+
if llama_dir:
|
| 77 |
+
llama_dir = Path(os.path.expandvars(str(llama_dir))).expanduser()
|
| 78 |
+
if bin_dir:
|
| 79 |
+
bin_dir = Path(os.path.expandvars(str(bin_dir))).expanduser()
|
| 80 |
+
if qtype not in QTYPES:
|
| 81 |
+
raise ValueError(f'Quantizzazione sconosciuta: {qtype}')
|
| 82 |
+
report = json.loads((run / 'report.json').read_text(encoding='utf-8'))
|
| 83 |
+
if report['status'] != 'pruned':
|
| 84 |
+
if report['status'] not in ('mask_only', 'mask_only_checkpoint_audit_failed',
|
| 85 |
+
'unchanged_audit_failed', 'unchanged_no_candidate'):
|
| 86 |
+
raise ValueError(f"Stato della build sconosciuto: {report['status']}")
|
| 87 |
+
print(f"GGUF saltato: {report['status']}. Nessun checkpoint fisico accettato.", flush=True)
|
| 88 |
+
return None
|
| 89 |
+
cfg, spec = model_config(run, report)
|
| 90 |
+
dest = run / 'gguf' / qtype
|
| 91 |
+
if dest.exists():
|
| 92 |
+
raise ValueError(f'Esiste già un export {qtype}: {dest}')
|
| 93 |
+
tools = get_tools(llama_dir, bin_dir)
|
| 94 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 95 |
+
with tempfile.TemporaryDirectory(prefix='.convert-', dir=dest.parent) as tmp:
|
| 96 |
+
work = Path(tmp)
|
| 97 |
+
stage = work / 'publish'
|
| 98 |
+
stage.mkdir()
|
| 99 |
+
fp16, result = work / 'intermediate-f16.gguf', stage / f'model-{qtype}.gguf'
|
| 100 |
+
env = os.environ.copy()
|
| 101 |
+
env.pop('NO_LOCAL_GGUF', None)
|
| 102 |
+
print(f'Conversione del checkpoint in F16, poi {qtype}...', flush=True)
|
| 103 |
+
convert_cmd = [sys.executable, str(tools.source / 'convert_hf_to_gguf.py'), str(run / 'checkpoint'),
|
| 104 |
+
'--outtype', 'f16', '--outfile', str(fp16)]
|
| 105 |
+
if spec['model_type'] == 'qwen3_next':
|
| 106 |
+
convert_cmd.append('--no-mtp') # D4: MTP draft stays out of v1 artifacts.
|
| 107 |
+
subprocess.run(convert_cmd, env=env, check=True)
|
| 108 |
+
subprocess.run([str(tools.quantize), str(fp16), str(result), qtype], check=True)
|
| 109 |
+
counts = check_gguf(result, tools.source, cfg, spec, qtype)
|
| 110 |
+
smoke_cmd = [str(tools.cli), '-m', str(result), '-ngl', '0',
|
| 111 |
+
'--no-warmup', '--no-display-prompt', '--check-tensors', '--ignore-eos', '-c', '64',
|
| 112 |
+
'-t', '2', '-n', '2', '--temp', '0', '-p', 'print(1)']
|
| 113 |
+
smoke = subprocess.run(smoke_cmd, stdin=subprocess.DEVNULL, capture_output=True, timeout=600)
|
| 114 |
+
logs = smoke.stderr.decode('utf-8', errors='replace')
|
| 115 |
+
out = smoke.stdout.decode('utf-8', errors='replace')
|
| 116 |
+
prefill = re.search(r'prompt eval time\s*=[^\n/]+/\s*([1-9]\d*)\s+tokens?', logs)
|
| 117 |
+
decode = re.search(r':\s*eval time\s*=[^\n/]+/\s*([1-9]\d*)\s+(?:runs?|tokens?)', logs)
|
| 118 |
+
if not prefill or not decode:
|
| 119 |
+
m = re.search(r'Prompt:\s*([0-9.]+)\s*t/s\s*\|\s*Generation:\s*([0-9.]+)\s*t/s', out)
|
| 120 |
+
if m:
|
| 121 |
+
prefill = (None, '2')
|
| 122 |
+
decode = (None, '2')
|
| 123 |
+
if smoke.returncode or not prefill or not decode:
|
| 124 |
+
raise ValueError('Smoke test llama-cli fallito.\n' + (logs + '\n' + out)[-2200:])
|
| 125 |
+
quality = None
|
| 126 |
+
reference = report.get('post_quant_reference')
|
| 127 |
+
if reference:
|
| 128 |
+
from post_quant import evaluate, passes as quality_passes, thresholds_from_report
|
| 129 |
+
from transformers import AutoTokenizer
|
| 130 |
+
print('Valutazione qualità post-quantizzazione...', flush=True)
|
| 131 |
+
tok = AutoTokenizer.from_pretrained(run / 'checkpoint')
|
| 132 |
+
thresholds = thresholds_from_report(report)
|
| 133 |
+
metrics = evaluate(result, tools.server, reference, tok, env=env)
|
| 134 |
+
quality = {'method': 'greedy_continuation_match', **metrics,
|
| 135 |
+
'thresholds': {'first_token_agreement': thresholds.first_token_agreement,
|
| 136 |
+
'full_continuation_match': thresholds.full_continuation_match},
|
| 137 |
+
'passed': quality_passes(metrics, thresholds)}
|
| 138 |
+
if not quality['passed']:
|
| 139 |
+
raise ValueError('Valutazione post-quantizzazione non superata: '
|
| 140 |
+
+ json.dumps(metrics['overall'], ensure_ascii=False))
|
| 141 |
+
record = {'file': result.name, 'quantization': qtype, 'bytes': result.stat().st_size,
|
| 142 |
+
'sha256': sha256(result), 'llama_cpp_revision': tools.revision,
|
| 143 |
+
'architecture': spec['model_type'],
|
| 144 |
+
'layers': len(topology(cfg, spec)['layer_indices']),
|
| 145 |
+
'experts_per_layer': cfg[spec['layout']['count']],
|
| 146 |
+
'experts_per_token': cfg[spec['config']['top_k']], 'expert_tensor_types': counts,
|
| 147 |
+
'smoke': {'backend': 'llama.cpp/CPU', 'requested_tokens': 2, 'passed': True,
|
| 148 |
+
'prompt_tokens_evaluated': int(prefill[1]), 'decode_steps': int(decode[1])},
|
| 149 |
+
'post_quantization_task_quality_measured': quality is not None,
|
| 150 |
+
'post_quantization_task_quality': quality}
|
| 151 |
+
(stage / 'conversion.json').write_text(json.dumps(record, indent=2) + '\n', encoding='utf-8')
|
| 152 |
+
stage.rename(dest)
|
| 153 |
+
print(f'GGUF verificato: {dest / result.name}', flush=True)
|
| 154 |
+
return dest
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
if __name__ == '__main__':
|
| 158 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 159 |
+
parser.add_argument('--run', required=True, type=Path)
|
| 160 |
+
parser.add_argument('--qtype', choices=QTYPES, default=QTYPES[0])
|
| 161 |
+
parser.add_argument('--llama-dir', type=Path)
|
| 162 |
+
parser.add_argument('--bin-dir', type=Path)
|
| 163 |
+
args = parser.parse_args()
|
| 164 |
+
try:
|
| 165 |
+
export_run(args.run, args.qtype, args.llama_dir, args.bin_dir)
|
| 166 |
+
except (ValueError, OSError, ImportError, subprocess.SubprocessError) as error:
|
| 167 |
+
sys.exit(f'Errore: {error}')
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/hf_jobs.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Private, revision-pinned code submission and durable outputs for HF Jobs."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import shutil
|
| 7 |
+
import tempfile
|
| 8 |
+
from uuid import uuid4
|
| 9 |
+
|
| 10 |
+
from huggingface_hub import HfApi, get_token, hf_hub_download
|
| 11 |
+
|
| 12 |
+
from architecture import BUILTINS
|
| 13 |
+
from preflight import check_metadata
|
| 14 |
+
|
| 15 |
+
HERE = Path(__file__).resolve().parent
|
| 16 |
+
IMAGE = 'pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel@sha256:a7103283ea7113e10ae5d014bd2342acebda0bc53164b2f7b1dd6eb7a766bdb6'
|
| 17 |
+
SOURCES = ('moediet.py', 'probes.py', 'routing.py', 'fidelity.py', 'gguf_export.py', 'llama_tools.py',
|
| 18 |
+
'run.py', 'hf_jobs.py', 'requirements.txt', 'requirements-q4.txt', 'requirements-qwen3next.txt',
|
| 19 |
+
'architecture.py', 'adapters.py',
|
| 20 |
+
'preflight.py', *(f'architectures/{name}.json' for name in BUILTINS))
|
| 21 |
+
# No model, token, local commands, or user-supplied values are interpolated into this program.
|
| 22 |
+
BOOTSTRAP = '''
|
| 23 |
+
import os, sys, subprocess, tempfile
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
subprocess.run([sys.executable, '-m', 'pip', 'install', 'huggingface_hub==0.36.2'], check=True)
|
| 26 |
+
from huggingface_hub import snapshot_download
|
| 27 |
+
repo, prefix = os.environ['MOEDIET_REPO'], os.environ['MOEDIET_CODE']
|
| 28 |
+
with tempfile.TemporaryDirectory() as job:
|
| 29 |
+
snapshot_download(repo, revision=os.environ['MOEDIET_COMMIT'], allow_patterns=[prefix + '/*'],
|
| 30 |
+
local_dir=job, token=os.environ['HF_TOKEN'])
|
| 31 |
+
code = Path(job) / prefix
|
| 32 |
+
import json
|
| 33 |
+
cfg = json.loads((code / 'request.json').read_text())
|
| 34 |
+
req_name = cfg.get('requirements') or ('requirements-q4.txt' if cfg['quantization'] else 'requirements.txt')
|
| 35 |
+
if req_name not in ('requirements.txt', 'requirements-q4.txt', 'requirements-qwen3next.txt'):
|
| 36 |
+
raise ValueError('Requirements non consentiti: ' + req_name)
|
| 37 |
+
deps = ['-r', str(code / req_name), 'cmake>=3.28,<4'] if cfg['quantization'] else ['-r', str(code / req_name)]
|
| 38 |
+
subprocess.run([sys.executable, '-m', 'pip', 'install', *deps], check=True)
|
| 39 |
+
subprocess.run([sys.executable, str(code / 'hf_jobs.py')], cwd=job, check=True)
|
| 40 |
+
'''
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def submit(cfg):
|
| 44 |
+
token = get_token()
|
| 45 |
+
if not token:
|
| 46 |
+
raise ValueError('Autenticarsi con hf auth login oppure impostare HF_TOKEN.')
|
| 47 |
+
api = HfApi(token=token)
|
| 48 |
+
repo = cfg['output_repo']
|
| 49 |
+
# Check access and resolve the input before submitting billable compute.
|
| 50 |
+
source = api.model_info(cfg['model'], revision=cfg['build'].get('revision'))
|
| 51 |
+
if not source.sha:
|
| 52 |
+
raise ValueError('Commit del modello sorgente non disponibile.')
|
| 53 |
+
metadata = hf_hub_download(cfg['model'], 'config.json', revision=source.sha, token=token)
|
| 54 |
+
plan = check_metadata(cfg, json.loads(Path(metadata).read_text(encoding='utf-8-sig')))
|
| 55 |
+
api.create_repo(repo_id=repo, private=True, exist_ok=True)
|
| 56 |
+
if api.model_info(repo).private is not True and not cfg.get('allow_public_output'):
|
| 57 |
+
raise ValueError('La destinazione esiste ed è pubblica. Scegliere un repository privato '
|
| 58 |
+
'oppure dichiarare allow_public_output: true nel profilo (scelta esplicita).')
|
| 59 |
+
prefix = 'requests/' + uuid4().hex
|
| 60 |
+
with tempfile.TemporaryDirectory(prefix='moediet-job-') as tmp:
|
| 61 |
+
stage = Path(tmp)
|
| 62 |
+
for name in SOURCES:
|
| 63 |
+
(stage / name).parent.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
shutil.copyfile(HERE / name, stage / name)
|
| 65 |
+
payload = {'model': cfg['model'], 'tags': cfg['tags'], 'quantization': cfg['quantization'],
|
| 66 |
+
'architecture': plan['architecture'],
|
| 67 |
+
'requirements': cfg.get('requirements', 'requirements.txt'),
|
| 68 |
+
'build': {**cfg['build'], 'revision': source.sha}}
|
| 69 |
+
if cfg.get('corpus'):
|
| 70 |
+
shutil.copyfile(cfg['corpus'], stage / 'corpus.json')
|
| 71 |
+
payload['corpus'] = 'corpus.json'
|
| 72 |
+
(stage / 'request.json').write_text(json.dumps(payload, ensure_ascii=False), encoding='utf-8')
|
| 73 |
+
commit = api.upload_folder(repo_id=repo, folder_path=stage, path_in_repo=prefix,
|
| 74 |
+
commit_message='MoEDiet: codice e parametri del Job')
|
| 75 |
+
job = api.run_job(image=IMAGE, command=['python', '-c', BOOTSTRAP], flavor=cfg['flavor'],
|
| 76 |
+
timeout=cfg['timeout'], secrets={'HF_TOKEN': token},
|
| 77 |
+
env={'MOEDIET_REPO': repo, 'MOEDIET_CODE': prefix, 'MOEDIET_COMMIT': commit.oid,
|
| 78 |
+
'PYTORCH_CUDA_ALLOC_CONF': 'expandable_segments:True'})
|
| 79 |
+
print(f'Job: {job.url}\nOutput dopo il salvataggio: https://huggingface.co/{repo}/tree/main/runs/{job.id}')
|
| 80 |
+
return job
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def worker():
|
| 84 |
+
from run import execute
|
| 85 |
+
cfg = json.loads((HERE / 'request.json').read_text(encoding='utf-8'))
|
| 86 |
+
if 'corpus' in cfg:
|
| 87 |
+
cfg['corpus'] = str(HERE / 'corpus.json')
|
| 88 |
+
repo = os.environ['MOEDIET_REPO']
|
| 89 |
+
api = HfApi(token=os.environ['HF_TOKEN'])
|
| 90 |
+
prefix = 'runs/' + os.environ['JOB_ID']
|
| 91 |
+
|
| 92 |
+
def persist(folder, suffix):
|
| 93 |
+
remote_path = prefix + ('/' + suffix if suffix else '')
|
| 94 |
+
commit = api.upload_folder(repo_id=repo, folder_path=folder, path_in_repo=remote_path,
|
| 95 |
+
commit_message=f'MoEDiet: {remote_path}')
|
| 96 |
+
print(f'Salvato: https://huggingface.co/{repo}/tree/{commit.oid}/{remote_path}', flush=True)
|
| 97 |
+
|
| 98 |
+
with tempfile.TemporaryDirectory(prefix='moediet-result-') as tmp:
|
| 99 |
+
execute(cfg, Path(tmp) / 'result', publish=persist)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == '__main__':
|
| 103 |
+
worker()
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/llama_tools.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pinned CPU tools for GGUF conversion and validation, also on Windows ARM64."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import os
|
| 5 |
+
import platform
|
| 6 |
+
import shutil
|
| 7 |
+
import subprocess
|
| 8 |
+
import tarfile
|
| 9 |
+
import tempfile
|
| 10 |
+
import urllib.request
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
COMMIT = 'd81aef19941e145d04f88fb180ea89a67d052ab5' # llama.cpp b11185 (Qwen3-Next converter support)
|
| 15 |
+
ARCHIVE_SHA256 = '837bc921584df017fc512f45980a52692d6fa56f0541d0e5ee898148cb4dd076'
|
| 16 |
+
TARGETS = ('llama-quantize', 'llama-cli', 'llama-server')
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def sha256(path):
|
| 20 |
+
digest = hashlib.sha256()
|
| 21 |
+
with path.open('rb') as stream:
|
| 22 |
+
while block := stream.read(4 << 20):
|
| 23 |
+
digest.update(block)
|
| 24 |
+
return digest.hexdigest()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass(frozen=True)
|
| 28 |
+
class Tools:
|
| 29 |
+
source: Path
|
| 30 |
+
quantize: Path
|
| 31 |
+
cli: Path
|
| 32 |
+
server: Path
|
| 33 |
+
revision: str
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def installed(source, binary_dir=None, revision='user-supplied'):
|
| 37 |
+
source = Path(os.path.expandvars(str(source))).expanduser().resolve()
|
| 38 |
+
if not (source / 'convert_hf_to_gguf.py').is_file() or not (source / 'gguf-py' / 'gguf').is_dir():
|
| 39 |
+
raise ValueError(f'Checkout llama.cpp incompleto: {source}')
|
| 40 |
+
dirs = [Path(os.path.expandvars(str(binary_dir))).expanduser().resolve()] if binary_dir else [
|
| 41 |
+
source / 'build/bin/Release', source / 'build/bin', source / 'bin']
|
| 42 |
+
suffix = '.exe' if os.name == 'nt' else ''
|
| 43 |
+
for directory in dirs:
|
| 44 |
+
bins = [directory / (name + suffix) for name in TARGETS]
|
| 45 |
+
if all(file.is_file() for file in bins):
|
| 46 |
+
return Tools(source, *bins, revision)
|
| 47 |
+
raise ValueError('Servono llama-quantize e llama-cli della stessa build. Verificare bin_dir.')
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_tools(source=None, binary_dir=None):
|
| 51 |
+
if source:
|
| 52 |
+
return installed(source, binary_dir)
|
| 53 |
+
if binary_dir:
|
| 54 |
+
raise ValueError('bin_dir richiede llama_dir.')
|
| 55 |
+
tools_cache = os.environ.get('MOEDIET_TOOLS_CACHE')
|
| 56 |
+
if tools_cache:
|
| 57 |
+
root = Path(os.path.expandvars(str(tools_cache))).expanduser().resolve()
|
| 58 |
+
else:
|
| 59 |
+
root = (Path.home() / '.cache' / 'moediet').resolve()
|
| 60 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 61 |
+
target = root / f'llama-{COMMIT[:12]}-{platform.system()}-{platform.machine()}'
|
| 62 |
+
if target.exists():
|
| 63 |
+
return installed(target, revision=COMMIT)
|
| 64 |
+
if not shutil.which('cmake'):
|
| 65 |
+
raise ValueError('Installare CMake e un compilatore C++, oppure configurare llama_dir e bin_dir.')
|
| 66 |
+
print('Preparazione una tantum degli strumenti llama.cpp b6500...', flush=True)
|
| 67 |
+
with tempfile.TemporaryDirectory(prefix='.tools-', dir=root) as tmp:
|
| 68 |
+
work = Path(tmp)
|
| 69 |
+
archive = work / 'llama.tar.gz'
|
| 70 |
+
url = f'https://codeload.github.com/ggml-org/llama.cpp/tar.gz/{COMMIT}'
|
| 71 |
+
with urllib.request.urlopen(url, timeout=120) as response, archive.open('wb') as output:
|
| 72 |
+
shutil.copyfileobj(response, output)
|
| 73 |
+
if sha256(archive) != ARCHIVE_SHA256:
|
| 74 |
+
raise ValueError('SHA-256 inatteso per i sorgenti llama.cpp.')
|
| 75 |
+
with tarfile.open(archive) as tar:
|
| 76 |
+
tar.extractall(work, filter='data')
|
| 77 |
+
src, build = work / ('llama.cpp-' + COMMIT), work / 'build'
|
| 78 |
+
flags = ['-DCMAKE_BUILD_TYPE=Release', '-DGGML_NATIVE=OFF', '-DGGML_CUDA=OFF', '-DLLAMA_CURL=OFF',
|
| 79 |
+
'-DLLAMA_BUILD_TESTS=OFF', '-DLLAMA_BUILD_EXAMPLES=OFF', '-DLLAMA_BUILD_SERVER=ON',
|
| 80 |
+
'-DBUILD_SHARED_LIBS=OFF']
|
| 81 |
+
if os.name == 'nt' and platform.machine().upper() in ('ARM64', 'AARCH64'):
|
| 82 |
+
flags += ['-G', 'Visual Studio 17 2022', '-A', 'ARM64']
|
| 83 |
+
subprocess.run(['cmake', '-S', str(src), '-B', str(build), *flags], check=True)
|
| 84 |
+
subprocess.run(['cmake', '--build', str(build), '--config', 'Release', '--parallel', '4',
|
| 85 |
+
'--target', *TARGETS], check=True)
|
| 86 |
+
compiled = build / 'bin'
|
| 87 |
+
if (compiled / 'Release').is_dir():
|
| 88 |
+
compiled = compiled / 'Release'
|
| 89 |
+
shutil.copytree(compiled, src / 'bin', dirs_exist_ok=True)
|
| 90 |
+
installed(src)
|
| 91 |
+
try:
|
| 92 |
+
src.rename(target)
|
| 93 |
+
except OSError:
|
| 94 |
+
if not target.is_dir(): # Two first runs may finish installing simultaneously.
|
| 95 |
+
raise
|
| 96 |
+
return installed(target, revision=COMMIT)
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/moediet.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MoEDiet: profile-driven MoE pruning with held-out audits and checkpoint verification."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import gc
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
import os
|
| 9 |
+
import shutil
|
| 10 |
+
import subprocess
|
| 11 |
+
import sys
|
| 12 |
+
import tempfile
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import transformers
|
| 17 |
+
from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM
|
| 18 |
+
|
| 19 |
+
from adapters import adapter_for, tolerances
|
| 20 |
+
from architecture import budgets_for, profile_hash, resolve_profile, validate_checkpoint_config
|
| 21 |
+
from fidelity import compare, equivalent, make_traces, passes, replay
|
| 22 |
+
from probes import clean_tags, make_probes
|
| 23 |
+
from routing import blocks, compact_in_place, continuation, encode, masked, profile, select_experts, validate_rows
|
| 24 |
+
|
| 25 |
+
DEFAULT_MODEL = 'allenai/OLMoE-1B-7B-0125-Instruct'
|
| 26 |
+
FORMAT = 'moediet.mask.v2'
|
| 27 |
+
LEGACY_FORMAT = 'moediet.olmoe.mask.v1'
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def write_json(path, data):
|
| 31 |
+
path.write_text(json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False) + '\n', encoding='utf-8')
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def local_signature(path):
|
| 35 |
+
# Check local model identity even when a training run overwrites the same directory.
|
| 36 |
+
names = ('config.json', 'generation_config.json', 'model.safetensors.index.json', 'tokenizer.json',
|
| 37 |
+
'tokenizer_config.json', 'special_tokens_map.json', 'added_tokens.json', 'vocab.json',
|
| 38 |
+
'vocab.txt', 'merges.txt', 'chat_template.jinja')
|
| 39 |
+
files = sorted({*path.glob('*.safetensors'), *path.glob('*.model'),
|
| 40 |
+
*(path / name for name in names if (path / name).is_file())})
|
| 41 |
+
hashes = hashlib.sha256()
|
| 42 |
+
for file in files:
|
| 43 |
+
digest = hashlib.sha256()
|
| 44 |
+
with file.open('rb') as stream:
|
| 45 |
+
while chunk := stream.read(4 << 20):
|
| 46 |
+
digest.update(chunk)
|
| 47 |
+
hashes.update(file.name.encode('utf-8') + b'\x00' + digest.digest())
|
| 48 |
+
return hashes.hexdigest()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def resolve_source(name, revision, fingerprint, architecture_profile=None, quantization=None):
|
| 52 |
+
name = os.path.expandvars(str(name))
|
| 53 |
+
path = Path(name).expanduser()
|
| 54 |
+
local = path.is_dir()
|
| 55 |
+
if local and revision:
|
| 56 |
+
raise ValueError('--revision si applica solo a un modello sullo Hub.')
|
| 57 |
+
name = str(path.resolve()) if local else name
|
| 58 |
+
from preflight import read_model_config
|
| 59 |
+
raw, commit = read_model_config(name, revision)
|
| 60 |
+
spec, _ = validate_checkpoint_config(raw, architecture_profile, quantization)
|
| 61 |
+
cfg = AutoConfig.from_pretrained(name, revision=commit, trust_remote_code=False)
|
| 62 |
+
cfg.moediet_architecture = spec
|
| 63 |
+
adapter_for(cfg).check_runtime()
|
| 64 |
+
source = {'kind': 'local' if local else 'hub', 'id': name}
|
| 65 |
+
if local and fingerprint:
|
| 66 |
+
source['sha256'] = local_signature(path)
|
| 67 |
+
if not local:
|
| 68 |
+
source['revision'] = commit
|
| 69 |
+
if not source['revision']:
|
| 70 |
+
raise ValueError('Impossibile determinare il commit del checkpoint sullo Hub.')
|
| 71 |
+
return cfg, source
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def load_model(source, device, dtype, architecture_profile=None):
|
| 75 |
+
tp = 'auto' if dtype == 'auto' else getattr(torch, dtype)
|
| 76 |
+
multi_gpu = device == 'cuda' and torch.cuda.device_count() > 1
|
| 77 |
+
kwargs = {}
|
| 78 |
+
if multi_gpu:
|
| 79 |
+
# Modelli piu grandi di una singola GPU (es. Next-80B bf16) vengono
|
| 80 |
+
# distribuiti su tutte le GPU visibili; non serve model.to(device).
|
| 81 |
+
kwargs['device_map'] = 'auto'
|
| 82 |
+
model, info = AutoModelForCausalLM.from_pretrained(
|
| 83 |
+
source['id'], revision=source.get('revision'), torch_dtype=tp, use_safetensors=True,
|
| 84 |
+
attn_implementation='eager', output_loading_info=True, trust_remote_code=False, **kwargs,
|
| 85 |
+
)
|
| 86 |
+
if any(info.get(key) for key in ('missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs')):
|
| 87 |
+
raise ValueError(f'Pesi incompatibili con il modello: {info}')
|
| 88 |
+
model.config.moediet_architecture = resolve_profile(model.config, architecture_profile)
|
| 89 |
+
if not multi_gpu:
|
| 90 |
+
model.to(device)
|
| 91 |
+
model.eval()
|
| 92 |
+
blocks(model)
|
| 93 |
+
return model
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def load_tokenizer(source):
|
| 97 |
+
return AutoTokenizer.from_pretrained(source['id'], revision=source.get('revision'), trust_remote_code=False)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def topology(cfg):
|
| 101 |
+
return adapter_for(cfg).topology(cfg)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def size_of(model):
|
| 105 |
+
return {'parameters': sum(p.numel() for p in model.parameters()),
|
| 106 |
+
'parameter_bytes': sum(p.numel() * p.element_size() for p in model.parameters())}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def verify_manifest(meta, model, source):
|
| 110 |
+
native = topology(model.config)
|
| 111 |
+
if meta.get('format') == LEGACY_FORMAT and model.config.model_type == 'olmoe':
|
| 112 |
+
native = {key: value for key, value in native.items() if key != 'layer_indices'}
|
| 113 |
+
elif meta.get('format') == FORMAT:
|
| 114 |
+
spec = adapter_for(model).spec
|
| 115 |
+
if meta.get('architecture') != spec or meta.get('architecture_sha256') != profile_hash(spec):
|
| 116 |
+
raise ValueError('La maschera usa un profilo architettura differente o alterato.')
|
| 117 |
+
else:
|
| 118 |
+
raise ValueError('Formato maschera non riconosciuto.')
|
| 119 |
+
if meta.get('source') != source or meta.get('routing') != native:
|
| 120 |
+
raise ValueError('La maschera non corrisponde alla sorgente, alla revisione o al routing del modello.')
|
| 121 |
+
rows = meta.get('expert_mask')
|
| 122 |
+
validate_rows(model, rows)
|
| 123 |
+
if meta.get('retained_per_layer') != len(rows[0]):
|
| 124 |
+
raise ValueError('Il budget dichiarato non corrisponde agli ID nella maschera.')
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@torch.inference_mode()
|
| 128 |
+
def post_quant_reference(traces, tokenizer):
|
| 129 |
+
"""Compact replay reference for the post-quantization gate (gguf_export/post_quant)."""
|
| 130 |
+
eos = tokenizer.eos_token_id
|
| 131 |
+
reference = []
|
| 132 |
+
for trace in traces:
|
| 133 |
+
cont = [int(t) for t in trace.generated if int(t) != eos]
|
| 134 |
+
prompt_ids = [int(t) for t in trace.prefix[0, :trace.prompt_len]]
|
| 135 |
+
reference.append({'group': trace.group, 'prompt': trace.prompt_text,
|
| 136 |
+
'prompt_ids': prompt_ids, 'continuation': cont})
|
| 137 |
+
return reference
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def build(args, work, device):
|
| 141 |
+
if not (math.isfinite(args.penalty) and args.penalty >= 0 and math.isfinite(args.max_kl) and args.max_kl >= 0):
|
| 142 |
+
raise ValueError('Lambda e soglia KL devono essere finite e non negative.')
|
| 143 |
+
for name in ('post_quant_min_first_token', 'post_quant_min_full_match'):
|
| 144 |
+
value = getattr(args, name)
|
| 145 |
+
if not (math.isfinite(value) and 0.0 <= value <= 1.0):
|
| 146 |
+
raise ValueError(f'{name} deve essere in [0, 1].')
|
| 147 |
+
if args.eval_tokens < 1:
|
| 148 |
+
raise ValueError('--eval-tokens deve essere positivo.')
|
| 149 |
+
tags = clean_tags(args.tags)
|
| 150 |
+
corpus = make_probes(tags, args.corpus)
|
| 151 |
+
cfg, source = resolve_source(args.model, args.revision, fingerprint=True,
|
| 152 |
+
architecture_profile=args.architecture_profile, quantization=args.gguf)
|
| 153 |
+
adapter = adapter_for(cfg)
|
| 154 |
+
native = adapter.topology(cfg)
|
| 155 |
+
total = native['experts_per_layer']
|
| 156 |
+
budgets = budgets_for(total, native['experts_per_token'], args.budgets, args.keep_fractions)
|
| 157 |
+
tok = load_tokenizer(source)
|
| 158 |
+
model = load_model(source, device, args.dtype or 'auto', adapter.spec)
|
| 159 |
+
dtype = str(model.get_input_embeddings().weight.dtype).split('.')[-1]
|
| 160 |
+
probe = encode(model, tok, corpus['profile'][tags[0]][0])[:, :8]
|
| 161 |
+
contract = adapter.verify_contract(model, probe)
|
| 162 |
+
full_rows = [list(range(total)) for _ in range(native['num_layers'])]
|
| 163 |
+
original_logits = model(input_ids=probe, use_cache=False).logits
|
| 164 |
+
with masked(model, full_rows):
|
| 165 |
+
identity_logits = model(input_ids=probe, use_cache=False).logits
|
| 166 |
+
if not torch.equal(original_logits, identity_logits):
|
| 167 |
+
raise ValueError('La maschera identita modifica il modello originale.')
|
| 168 |
+
print('Profilazione dei router...', flush=True)
|
| 169 |
+
score, tokens = profile(model, tok, corpus['profile'], tags, args.penalty)
|
| 170 |
+
full_size = size_of(model)
|
| 171 |
+
report = {'source': source, 'routing': native, 'dtype': dtype, 'device': str(device),
|
| 172 |
+
'architecture': adapter.spec, 'architecture_sha256': profile_hash(adapter.spec),
|
| 173 |
+
'adapter_contract': contract, 'identity_mask_passed': True,
|
| 174 |
+
'requested_keep_fractions': args.keep_fractions,
|
| 175 |
+
'torch': str(torch.__version__), 'transformers': transformers.__version__, 'probes': corpus,
|
| 176 |
+
'profile_tokens_per_layer_by_group': tokens, 'score_by_layer': score.tolist(),
|
| 177 |
+
'lambda': args.penalty, 'budgets': budgets, 'max_kl_nats_per_token': args.max_kl,
|
| 178 |
+
'max_continuation_tokens': args.eval_tokens, 'selection': [], 'audit': None,
|
| 179 |
+
'full_model': full_size, 'checkpoint': None}
|
| 180 |
+
keep = total
|
| 181 |
+
status = 'unchanged_no_candidate'
|
| 182 |
+
if budgets[0] < total:
|
| 183 |
+
selection = make_traces(model, tok, corpus['select'], args.eval_tokens)
|
| 184 |
+
for budget in budgets:
|
| 185 |
+
if budget == total:
|
| 186 |
+
break # The identity fallback has KL = 0 by construction.
|
| 187 |
+
with masked(model, select_experts(score, budget)):
|
| 188 |
+
metrics = compare(selection, replay(model, selection))
|
| 189 |
+
passed = passes(metrics, args.max_kl)
|
| 190 |
+
report['selection'].append({'keep': budget, 'passed': passed, 'groups': metrics})
|
| 191 |
+
print(f'Budget {budget}/{total}: {"accettato" if passed else "respinto"}', flush=True)
|
| 192 |
+
if passed:
|
| 193 |
+
keep = budget
|
| 194 |
+
break
|
| 195 |
+
del selection
|
| 196 |
+
report['selected_before_audit'] = keep
|
| 197 |
+
rows = select_experts(score, keep)
|
| 198 |
+
if keep < total:
|
| 199 |
+
audit = make_traces(model, tok, corpus['audit'], args.eval_tokens)
|
| 200 |
+
with masked(model, rows):
|
| 201 |
+
masked_logp = replay(model, audit)
|
| 202 |
+
metrics = compare(audit, masked_logp)
|
| 203 |
+
passed = passes(metrics, args.max_kl)
|
| 204 |
+
report['audit'] = {'keep': keep, 'passed': passed, 'groups': metrics}
|
| 205 |
+
if passed:
|
| 206 |
+
status = 'mask_only' if args.mask_only else 'pruned'
|
| 207 |
+
else:
|
| 208 |
+
status, keep = 'unchanged_audit_failed', total
|
| 209 |
+
rows = select_experts(score, total)
|
| 210 |
+
manifest = {'format': FORMAT, 'source': source, 'routing': native, 'profile_dtype': dtype,
|
| 211 |
+
'architecture': adapter.spec, 'architecture_sha256': profile_hash(adapter.spec),
|
| 212 |
+
'target_tags': tags, 'retained_per_layer': keep, 'expert_mask': rows}
|
| 213 |
+
verify_manifest(manifest, model, source)
|
| 214 |
+
if status == 'pruned':
|
| 215 |
+
print('Esportazione e ricaricamento del checkpoint...', flush=True)
|
| 216 |
+
path = work / 'checkpoint'
|
| 217 |
+
compact_in_place(model, rows)
|
| 218 |
+
model.save_pretrained(path, safe_serialization=True, max_shard_size='2GB')
|
| 219 |
+
tok.save_pretrained(path)
|
| 220 |
+
del model
|
| 221 |
+
gc.collect()
|
| 222 |
+
compact = load_model({'id': str(path)}, device, dtype)
|
| 223 |
+
compact_logp = replay(compact, audit)
|
| 224 |
+
actual = compare(audit, compact_logp)
|
| 225 |
+
equivalence = equivalent(masked_logp, compact_logp, **tolerances(getattr(torch, dtype)))
|
| 226 |
+
passed = passes(actual, args.max_kl) and equivalence['passed']
|
| 227 |
+
report['checkpoint_audit'] = {'passed': passed, 'vs_original': actual,
|
| 228 |
+
'mask_equivalence': equivalence,
|
| 229 |
+
'vs_mask': compare(audit, compact_logp, masked_logp)}
|
| 230 |
+
if passed:
|
| 231 |
+
report['checkpoint'] = {**size_of(compact), 'safetensors_bytes': sum(
|
| 232 |
+
file.stat().st_size for file in path.glob('*.safetensors'))}
|
| 233 |
+
# Greedy-continuations from the PRUNED checkpoint isolate quantization
|
| 234 |
+
# damage in the post-quantization gate (gguf_export/post_quant.py).
|
| 235 |
+
ref_traces = make_traces(compact, tok, corpus['audit'], args.eval_tokens)
|
| 236 |
+
report['post_quant_reference'] = post_quant_reference(ref_traces, tok)
|
| 237 |
+
report['post_quant_thresholds'] = {
|
| 238 |
+
'first_token_agreement': args.post_quant_min_first_token,
|
| 239 |
+
'full_continuation_match': args.post_quant_min_full_match}
|
| 240 |
+
else:
|
| 241 |
+
status = 'mask_only_checkpoint_audit_failed'
|
| 242 |
+
del compact
|
| 243 |
+
gc.collect()
|
| 244 |
+
if not passed:
|
| 245 |
+
if path.resolve().parent != work.resolve() or path.name != 'checkpoint':
|
| 246 |
+
raise ValueError('Percorso del checkpoint temporaneo fuori dalla directory della build.')
|
| 247 |
+
shutil.rmtree(path) # Only this run's unpublished temporary export.
|
| 248 |
+
report.update(status=status, retained_per_layer=keep, expert_fraction_removed=1 - keep / total)
|
| 249 |
+
write_json(work / 'mask.json', manifest)
|
| 250 |
+
write_json(work / 'report.json', report)
|
| 251 |
+
return report
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
@torch.inference_mode()
|
| 255 |
+
def generate(args, device):
|
| 256 |
+
if args.max_new_tokens < 1 or not args.prompt.strip():
|
| 257 |
+
raise ValueError('Servono un prompt non vuoto e un numero di token positivo.')
|
| 258 |
+
meta = None
|
| 259 |
+
if args.mask:
|
| 260 |
+
if args.revision:
|
| 261 |
+
raise ValueError('La revisione è già fissata nella maschera.')
|
| 262 |
+
meta = json.loads(Path(args.mask).read_text(encoding='utf-8'))
|
| 263 |
+
if meta.get('format') not in (FORMAT, LEGACY_FORMAT):
|
| 264 |
+
raise ValueError('Formato maschera non riconosciuto.')
|
| 265 |
+
original = meta['source']
|
| 266 |
+
if original['kind'] == 'local' and not Path(original['id']).is_dir():
|
| 267 |
+
raise ValueError('La directory locale originale registrata nella maschera non è disponibile.')
|
| 268 |
+
requested = meta.get('architecture') if meta.get('format') == FORMAT else 'olmoe'
|
| 269 |
+
if args.architecture_profile is not None:
|
| 270 |
+
declared_type = requested['model_type'] if isinstance(requested, dict) else 'olmoe'
|
| 271 |
+
minimal_cfg = {'model_type': declared_type}
|
| 272 |
+
if resolve_profile(minimal_cfg, args.architecture_profile) != resolve_profile(minimal_cfg, requested):
|
| 273 |
+
raise ValueError('Il profilo richiesto differisce da quello della maschera.')
|
| 274 |
+
cfg, source = resolve_source(original['id'], original.get('revision'), fingerprint=True, architecture_profile=requested)
|
| 275 |
+
if source != original:
|
| 276 |
+
raise ValueError('Il checkpoint originale è cambiato dalla profilazione.')
|
| 277 |
+
else:
|
| 278 |
+
cfg, source = resolve_source(args.model, args.revision, fingerprint=False, architecture_profile=args.architecture_profile)
|
| 279 |
+
dtype = args.dtype or (meta['profile_dtype'] if meta else 'auto')
|
| 280 |
+
model, tok = load_model(source, device, dtype, cfg.moediet_architecture), load_tokenizer(source)
|
| 281 |
+
ids = encode(model, tok, args.prompt, reserve=args.max_new_tokens)
|
| 282 |
+
if meta:
|
| 283 |
+
verify_manifest(meta, model, source)
|
| 284 |
+
with masked(model, meta['expert_mask']):
|
| 285 |
+
seq = continuation(model, tok, ids, args.max_new_tokens)
|
| 286 |
+
else:
|
| 287 |
+
seq = continuation(model, tok, ids, args.max_new_tokens)
|
| 288 |
+
return tok.decode(seq[0, ids.shape[1]:].tolist(), skip_special_tokens=True)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def main(argv=None):
|
| 292 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 293 |
+
subs = parser.add_subparsers(dest='command', required=True)
|
| 294 |
+
builder = subs.add_parser('build', help='Profilazione, selezione, audit ed export')
|
| 295 |
+
builder.add_argument('--model', default=DEFAULT_MODEL, help='ID Hub o directory HF locale')
|
| 296 |
+
builder.add_argument('--tags', nargs='+', required=True)
|
| 297 |
+
builder.add_argument('--out', type=Path, required=True, help='Nuova directory dei risultati')
|
| 298 |
+
builder.add_argument('--budgets', nargs='+', type=int, help='Esperti conservati per strato, fallback intero automatico')
|
| 299 |
+
builder.add_argument('--keep-fractions', nargs='+', type=float, help='Frazioni conservate per layer MoE, arrotondate per eccesso')
|
| 300 |
+
builder.add_argument('--lambda', dest='penalty', type=float, default=0.5)
|
| 301 |
+
builder.add_argument('--max-kl', type=float, default=0.10, help='Soglia per ogni gruppo, in nat/token')
|
| 302 |
+
builder.add_argument('--eval-tokens', type=int, default=8)
|
| 303 |
+
builder.add_argument('--post-quant-min-first-token', type=float, default=0.95,
|
| 304 |
+
help="Accettazione GGUF: accordo minimo sul primo token (globale)")
|
| 305 |
+
builder.add_argument('--post-quant-min-full-match', type=float, default=0.40,
|
| 306 |
+
help="Accettazione GGUF: match completo minimo della continuazione (globale)")
|
| 307 |
+
builder.add_argument('--corpus', type=Path, help='JSON di sonde personalizzate')
|
| 308 |
+
builder.add_argument('--mask-only', action='store_true')
|
| 309 |
+
builder.add_argument('--gguf', choices=['Q4_K_M', 'Q4_0'], help='Esporta anche il checkpoint in GGUF Q4')
|
| 310 |
+
builder.add_argument('--llama-dir', type=Path, help='Checkout llama.cpp per --gguf')
|
| 311 |
+
builder.add_argument('--bin-dir', type=Path, help='Directory degli eseguibili della stessa build')
|
| 312 |
+
gen = subs.add_parser('generate', help='Inferenza greedy con maschera o checkpoint HF')
|
| 313 |
+
sources = gen.add_mutually_exclusive_group(required=True)
|
| 314 |
+
sources.add_argument('--model', help='Checkpoint HF completo o compatto')
|
| 315 |
+
sources.add_argument('--mask', type=Path, help='Maschera JSON con riferimento al checkpoint originale')
|
| 316 |
+
gen.add_argument('--prompt', required=True)
|
| 317 |
+
gen.add_argument('--max-new-tokens', type=int, default=48)
|
| 318 |
+
for sub in (builder, gen):
|
| 319 |
+
sub.add_argument('--architecture-profile', help='Profilo JSON oppure nome incorporato; default rilevamento automatico')
|
| 320 |
+
sub.add_argument('--device', choices=['auto', 'cpu', 'cuda'], default='auto')
|
| 321 |
+
sub.add_argument('--dtype', choices=['auto', 'float32', 'float16', 'bfloat16'])
|
| 322 |
+
sub.add_argument('--revision', help='Commit o ref del modello sullo Hub')
|
| 323 |
+
args = parser.parse_args(argv)
|
| 324 |
+
device = ('cuda' if torch.cuda.is_available() else 'cpu') if args.device == 'auto' else args.device
|
| 325 |
+
if args.command == 'generate':
|
| 326 |
+
if args.mask:
|
| 327 |
+
args.mask = Path(os.path.expandvars(str(args.mask))).expanduser()
|
| 328 |
+
if args.model:
|
| 329 |
+
args.model = os.path.expandvars(str(args.model))
|
| 330 |
+
print(generate(args, device))
|
| 331 |
+
return
|
| 332 |
+
if args.corpus:
|
| 333 |
+
args.corpus = Path(os.path.expandvars(str(args.corpus))).expanduser()
|
| 334 |
+
if args.llama_dir:
|
| 335 |
+
args.llama_dir = Path(os.path.expandvars(str(args.llama_dir))).expanduser()
|
| 336 |
+
if args.bin_dir:
|
| 337 |
+
args.bin_dir = Path(os.path.expandvars(str(args.bin_dir))).expanduser()
|
| 338 |
+
if args.mask_only and args.gguf:
|
| 339 |
+
raise ValueError('--gguf richiede il checkpoint fisico: non si combina con --mask-only.')
|
| 340 |
+
if (args.llama_dir or args.bin_dir) and not args.gguf:
|
| 341 |
+
raise ValueError('--llama-dir e --bin-dir richiedono --gguf.')
|
| 342 |
+
if args.bin_dir and not args.llama_dir:
|
| 343 |
+
raise ValueError('--bin-dir richiede --llama-dir.')
|
| 344 |
+
out = Path(os.path.expandvars(str(args.out))).expanduser().resolve()
|
| 345 |
+
if out.exists():
|
| 346 |
+
raise ValueError(f'La destinazione esiste già: {out}. Scegliere una nuova directory.')
|
| 347 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 348 |
+
with tempfile.TemporaryDirectory(prefix='.moediet-', dir=out.parent) as temp:
|
| 349 |
+
stage = Path(temp) / 'result'
|
| 350 |
+
stage.mkdir()
|
| 351 |
+
report = build(args, stage, device)
|
| 352 |
+
stage.rename(out)
|
| 353 |
+
print(f"{report['status']} | {report['retained_per_layer']}/{report['routing']['experts_per_layer']} esperti/strato | {out}")
|
| 354 |
+
if args.gguf:
|
| 355 |
+
from gguf_export import export_run
|
| 356 |
+
export_run(out, args.gguf, args.llama_dir, args.bin_dir)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
if __name__ == '__main__':
|
| 360 |
+
try:
|
| 361 |
+
main()
|
| 362 |
+
except (ValueError, OSError, ImportError, subprocess.SubprocessError) as error:
|
| 363 |
+
sys.exit(f'Errore: {error}')
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/preflight.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read small metadata files and reject unsupported work before starting HF compute."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from architecture import budgets_for, validate_checkpoint_config
|
| 7 |
+
|
| 8 |
+
HERE = Path(__file__).resolve().parent
|
| 9 |
+
JOB_REQUIREMENTS = ('requirements.txt', 'requirements-qwen3next.txt')
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def pinned_transformers(name):
|
| 13 |
+
"""Exact transformers pin a Job would install; fail closed if it cannot be proven."""
|
| 14 |
+
if name not in JOB_REQUIREMENTS:
|
| 15 |
+
raise ValueError(f'Requirements del Job non consentiti: {name}.')
|
| 16 |
+
pinned = None
|
| 17 |
+
for line in (HERE / name).read_text(encoding='utf-8').splitlines():
|
| 18 |
+
line = line.strip()
|
| 19 |
+
if line.startswith('transformers') and '==' in line:
|
| 20 |
+
pinned = line.split('==', 1)[1].strip()
|
| 21 |
+
break
|
| 22 |
+
if pinned is None:
|
| 23 |
+
raise ValueError(f'Pin transformers== mancante in {name}: impossibile verificare il runtime del Job.')
|
| 24 |
+
return pinned
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def read_model_config(name, revision=None, api=None):
|
| 28 |
+
path = Path(name)
|
| 29 |
+
if path.is_dir():
|
| 30 |
+
if revision:
|
| 31 |
+
raise ValueError('revision si applica solo a un modello sullo Hub.')
|
| 32 |
+
return json.loads((path / 'config.json').read_text(encoding='utf-8-sig')), None
|
| 33 |
+
if path.is_absolute() or str(name).startswith(('.', '~')) or '\\' in str(name):
|
| 34 |
+
raise ValueError(f'Directory del modello locale non trovata: {name}')
|
| 35 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 36 |
+
api = api or HfApi()
|
| 37 |
+
source = api.model_info(name, revision=revision)
|
| 38 |
+
if not source.sha:
|
| 39 |
+
raise ValueError('Commit del modello sorgente non disponibile.')
|
| 40 |
+
path = hf_hub_download(name, 'config.json', revision=source.sha, token=api.token)
|
| 41 |
+
return json.loads(Path(path).read_text(encoding='utf-8-sig')), source.sha
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def check_metadata(cfg, raw):
|
| 45 |
+
spec, routing = validate_checkpoint_config(raw, cfg.get('architecture'), cfg.get('quantization'))
|
| 46 |
+
if cfg.get('mode') == 'hf':
|
| 47 |
+
pinned = pinned_transformers(cfg.get('requirements', 'requirements.txt'))
|
| 48 |
+
if spec['transformers_version'] != pinned:
|
| 49 |
+
raise ValueError(
|
| 50 |
+
f"Il Job installerebbe transformers=={pinned}, ma il profilo {spec['id']} richiede "
|
| 51 |
+
f"{spec['transformers_version']}. Allineare il file requirements al profilo.")
|
| 52 |
+
budgets = budgets_for(routing['experts_per_layer'], routing['experts_per_token'],
|
| 53 |
+
cfg['build'].get('budgets'), cfg['build'].get('keep_fractions'))
|
| 54 |
+
return {'architecture': spec, 'routing': routing, 'budgets': budgets,
|
| 55 |
+
'checks': 'metadata_only', 'weights_loaded': False,
|
| 56 |
+
'note': 'Controllo di compatibilita dei metadati: non misura VRAM, non scarica pesi e non prova la qualita.'}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def inspect(cfg):
|
| 60 |
+
raw, revision = read_model_config(cfg['model'], cfg['build'].get('revision'))
|
| 61 |
+
result = check_metadata(cfg, raw)
|
| 62 |
+
result['source_revision'] = revision
|
| 63 |
+
return result
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/probes.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small, inspectable probe bank. No generator model or network calls."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
CONTROL = "__control__"
|
| 7 |
+
SPLITS = ("profile", "select", "audit")
|
| 8 |
+
# Two distinct situations per split. The same stems are used for target and control.
|
| 9 |
+
STEMS = (
|
| 10 |
+
"Explain the mechanism involved.", "Give a concrete solution and justify it.",
|
| 11 |
+
"What would you check first, and why?", "Work through a small example.",
|
| 12 |
+
"Explain what happens next and why.", "Show how you would verify your answer.",
|
| 13 |
+
)
|
| 14 |
+
CASES = {
|
| 15 |
+
"python": ("A mutable default list accumulates items between calls.", "Read a large CSV lazily using a generator.",
|
| 16 |
+
"A closure in a loop returns the last index every time.", "Group log entries using collections.defaultdict.",
|
| 17 |
+
"Two names refer to the same nested list after a shallow copy.", "Test an asynchronous context manager."),
|
| 18 |
+
"c++": ("A std::vector reallocation invalidates an iterator.", "Transfer sole ownership using std::unique_ptr.",
|
| 19 |
+
"A lambda captures a local variable by reference and escapes.", "Implement a move constructor for a buffer.",
|
| 20 |
+
"A std::string_view outlives its backing string.", "Test destruction through a polymorphic base pointer."),
|
| 21 |
+
"devops": ("A rolling deployment serves traffic before readiness checks pass.", "Roll back a failed deployment without losing logs.",
|
| 22 |
+
"A deployment succeeds in staging but fails its production health check.", "Choose a threshold for a canary rollback.",
|
| 23 |
+
"A Kubernetes pod is repeatedly OOMKilled.", "Restore a backup in isolation and verify the restored data."),
|
| 24 |
+
"docker": ("A source change invalidates every Docker build layer.", "Produce a small runtime image with a multi-stage Dockerfile.",
|
| 25 |
+
"A file copied into an image disappears under a bind mount.", "Configure a container health check.",
|
| 26 |
+
"A PID 1 shell does not forward SIGTERM to its child.", "Verify that a named volume survives container replacement."),
|
| 27 |
+
"postgresql": ("An index is ignored on a low-selectivity column.", "Inspect a slow query with EXPLAIN ANALYZE.",
|
| 28 |
+
"Two transactions acquire row locks in opposite order.", "Build a partial index for unprocessed jobs.",
|
| 29 |
+
"An old transaction prevents VACUUM from reclaiming tuples.", "Verify a retry after a serialization failure."),
|
| 30 |
+
"sql": ("A LEFT JOIN loses unmatched rows after a WHERE filter.", "Rank sales totals within each region.",
|
| 31 |
+
"A join duplicates each invoice total.", "Find customers with no orders using NOT EXISTS.",
|
| 32 |
+
"COUNT(column) skips NULL values in a grouped query.", "Test a running total when two rows share a date."),
|
| 33 |
+
"gardening": ("Leaves yellow after overwatering.", "Prepare soil for planting carrots.", "Seedlings bend toward a window.",
|
| 34 |
+
"Choose a watering schedule for a clay pot.", "A late frost damages new shoots.", "Check whether stored seeds will germinate."),
|
| 35 |
+
"navigation": ("A compass bearing differs from true north.", "Estimate walking time using a contour map.", "Two map landmarks seem misaligned.",
|
| 36 |
+
"Convert a map scale into walking distance.", "Wind pushes a boat away from its intended bearing.", "Check a position using two bearings."),
|
| 37 |
+
"music": ("Two strings produce beats when played together.", "Transpose a melody to a new key.", "A chord sounds unstable before resolving.",
|
| 38 |
+
"Count the pulses in six-eight time.", "Shortening a vibrating string raises its pitch.", "Check whether a recording is in tune."),
|
| 39 |
+
}
|
| 40 |
+
ALIASES = {"cpp": "c++", "postgres": "postgresql"}
|
| 41 |
+
GENERAL = ("gardening", "navigation", "music")
|
| 42 |
+
NEUTRAL = ("A calendar spans a leap day.", "Divide a grocery bill between three friends.",
|
| 43 |
+
"Two clocks disagree after a battery change.", "Find the median of five distances.",
|
| 44 |
+
"A queue is served in arrival order.", "Check a temperature conversion by reversing it.")
|
| 45 |
+
GENERIC = ("Introduce a basic concept with a worked example.", "Correct a common beginner mistake.",
|
| 46 |
+
"Diagnose an unexpected outcome on a typical task.", "Compare two methods for a familiar problem.",
|
| 47 |
+
"Predict an edge case in a realistic scenario.", "Design a reproducible check for a subtle error.")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def clean_tags(tags):
|
| 51 |
+
names = [t.strip().casefold() for t in tags]
|
| 52 |
+
names = list(dict.fromkeys(ALIASES.get(t, t) for t in names))
|
| 53 |
+
if not names or any(t in ('', CONTROL) for t in names):
|
| 54 |
+
raise ValueError(f"Serve almeno un tag non vuoto. {CONTROL} è riservato.")
|
| 55 |
+
return names
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def prompts_for(topic, split_index):
|
| 59 |
+
cases = CASES.get(topic, GENERIC)
|
| 60 |
+
return [f"Topic: {topic}. {cases[i]} {STEMS[i]}" for i in range(2 * split_index, 2 * split_index + 2)]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def make_probes(tags, custom=None):
|
| 64 |
+
if custom:
|
| 65 |
+
corpus = json.loads(Path(custom).read_text(encoding="utf-8"))
|
| 66 |
+
else:
|
| 67 |
+
controls = [topic for topic in GENERAL if topic not in tags]
|
| 68 |
+
corpus = {}
|
| 69 |
+
for i, split in enumerate(SPLITS):
|
| 70 |
+
groups = {tag: prompts_for(tag, i) for tag in tags}
|
| 71 |
+
groups[CONTROL] = [prompt for topic in controls for prompt in prompts_for(topic, i)] or [
|
| 72 |
+
f"{NEUTRAL[j]} {STEMS[j]}" for j in range(2 * i, 2 * i + 2)]
|
| 73 |
+
corpus[split] = groups
|
| 74 |
+
if not isinstance(corpus, dict) or set(corpus) != set(SPLITS):
|
| 75 |
+
raise ValueError(f"Il corpus richiede esattamente questi split: {SPLITS}")
|
| 76 |
+
seen = set()
|
| 77 |
+
for split, groups in corpus.items():
|
| 78 |
+
if not isinstance(groups, dict) or set(groups) != {*tags, CONTROL}:
|
| 79 |
+
raise ValueError(f"Gruppi errati in {split}. Servono tutti i tag e {CONTROL}.")
|
| 80 |
+
for group, prompts in groups.items():
|
| 81 |
+
if not isinstance(prompts, list) or not prompts:
|
| 82 |
+
raise ValueError(f"Nessuna sonda in {split}/{group}. Fornire un corpus con esempi distinti.")
|
| 83 |
+
for prompt in prompts:
|
| 84 |
+
if not isinstance(prompt, str) or not prompt.strip():
|
| 85 |
+
raise ValueError(f"Sonda vuota o non testuale in {split}/{group}.")
|
| 86 |
+
key = ' '.join(prompt.casefold().split())
|
| 87 |
+
if key in seen:
|
| 88 |
+
raise ValueError(f"Sonda duplicata nel corpus: {prompt!r}")
|
| 89 |
+
seen.add(key)
|
| 90 |
+
return corpus
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/request.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"model": "Qwen/Qwen3-Next-80B-A3B-Instruct", "tags": ["agents", "tools", "evals"], "quantization": "Q4_K_M", "architecture": {"schema_version": 1, "id": "qwen3-next-transformers-4.57.6", "model_type": "qwen3_next", "implementation": "softmax_topk_modulelist_v1", "transformers_version": "4.57.6", "layout": {"backbone": "model", "layers": "model.layers", "block": "mlp", "router": "gate", "experts": "experts", "count": "num_experts", "top_k": "top_k", "normalize": "norm_topk_prob"}, "config": {"layers": "num_hidden_layers", "experts": "num_experts", "top_k": "num_experts_per_tok", "normalize": "norm_topk_prob", "context": "max_position_embeddings"}, "layer_selection": "qwen_sparse_step", "shared_experts": [{"module": "shared_expert", "gate": "shared_expert_gate", "activation": "sigmoid"}]}, "requirements": "requirements-qwen3next.txt", "build": {"revision": "9c7f2fbe84465e40164a94cc16cd30b6999b0cc7", "budgets": [64, 128], "eval_tokens": 8, "post_quant_min_first_token": 0.95, "post_quant_min_full_match": 0.4}, "corpus": "corpus.json"}
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/requirements-q4.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-r requirements.txt
|
| 2 |
+
# Imports used by the pinned upstream GGUF converter.
|
| 3 |
+
mistral-common==1.8.5
|
| 4 |
+
sentencepiece>=0.2,<0.3
|
| 5 |
+
protobuf>=4.25,<8
|
| 6 |
+
PyYAML>=6,<7
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/requirements-qwen3next.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Isolated runtime for the qwen3_next profile (local-inference target, HF Jobs).
|
| 2 |
+
# The pin must equal the profile's declared transformers_version exactly:
|
| 3 |
+
# preflight refuses the Job before any upload if the two disagree (fail closed).
|
| 4 |
+
torch>=2.6,<3
|
| 5 |
+
transformers==4.57.6
|
| 6 |
+
safetensors>=0.4.3,<1
|
| 7 |
+
accelerate>=1.0
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Install a PyTorch build for your platform before this file if necessary.
|
| 2 |
+
torch>=2.6,<3
|
| 3 |
+
transformers==4.55.4
|
| 4 |
+
safetensors>=0.4.3,<1
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/routing.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Architecture-independent profiling and compatibility wrappers for adapters."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from adapters import adapter_for
|
| 6 |
+
from architecture import read_path
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def blocks(model):
|
| 10 |
+
return adapter_for(model).blocks(model)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def encode(model, tokenizer, prompt, reserve=0):
|
| 14 |
+
if tokenizer.chat_template:
|
| 15 |
+
ids = tokenizer.apply_chat_template([{'role': 'user', 'content': prompt}], tokenize=True,
|
| 16 |
+
add_generation_prompt=True, return_tensors='pt')
|
| 17 |
+
else:
|
| 18 |
+
ids = tokenizer(prompt, return_tensors='pt')['input_ids']
|
| 19 |
+
adapter = adapter_for(model)
|
| 20 |
+
context = read_path(model.config, adapter.spec['config']['context'])
|
| 21 |
+
if not ids.shape[1] or ids.shape[1] + reserve > context:
|
| 22 |
+
raise ValueError(f'Sonda vuota o oltre il contesto: {ids.shape[1]} token + {reserve} riservati.')
|
| 23 |
+
return ids.to(model.get_input_embeddings().weight.device)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def continuation(model, tokenizer, ids, count):
|
| 27 |
+
pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id
|
| 28 |
+
return model.generate(input_ids=ids, attention_mask=torch.ones_like(ids), max_new_tokens=count,
|
| 29 |
+
do_sample=False, num_beams=1, use_cache=True, pad_token_id=pad_id,
|
| 30 |
+
return_dict_in_generate=False, output_router_logits=False)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@torch.inference_mode()
|
| 34 |
+
def profile(model, tokenizer, groups, tags, penalty):
|
| 35 |
+
from probes import CONTROL
|
| 36 |
+
|
| 37 |
+
adapter = adapter_for(model)
|
| 38 |
+
layers = adapter.blocks(model)
|
| 39 |
+
experts = adapter.topology(model.config)['experts_per_layer']
|
| 40 |
+
means, counts = {}, {}
|
| 41 |
+
for group, prompts in groups.items():
|
| 42 |
+
sums = torch.zeros(len(layers), experts, dtype=torch.float64)
|
| 43 |
+
counts[group] = 0
|
| 44 |
+
for prompt in prompts:
|
| 45 |
+
ids = encode(model, tokenizer, prompt)
|
| 46 |
+
routers = adapter.router_logits(model, ids)
|
| 47 |
+
count = ids.numel()
|
| 48 |
+
for i, (block, logits) in enumerate(zip(layers, routers, strict=True)):
|
| 49 |
+
if tuple(logits.shape) != (count, experts):
|
| 50 |
+
raise ValueError(f'Forma inattesa dei logit del router {i}: {tuple(logits.shape)}')
|
| 51 |
+
weights, chosen = adapter.weights(block, logits)
|
| 52 |
+
mass = torch.zeros_like(logits, dtype=torch.float32).scatter_(-1, chosen, weights)
|
| 53 |
+
sums[i] += mass.sum(dim=0, dtype=torch.float64).cpu()
|
| 54 |
+
counts[group] += count
|
| 55 |
+
means[group] = sums / counts[group]
|
| 56 |
+
target = torch.stack([means[tag] for tag in tags]).mean(0)
|
| 57 |
+
score = target - penalty * means[CONTROL]
|
| 58 |
+
if not torch.isfinite(score).all():
|
| 59 |
+
raise ValueError('Lo score contiene valori non finiti.')
|
| 60 |
+
return score, counts
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def select_experts(score, keep):
|
| 64 |
+
ranked = torch.argsort(score, dim=1, descending=True, stable=True)
|
| 65 |
+
return ranked[:, :keep].sort(dim=1).values.tolist()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def validate_rows(model, rows):
|
| 69 |
+
return adapter_for(model).validate_rows(model, rows)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def masked(model, rows):
|
| 73 |
+
return adapter_for(model).masked(model, rows)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def compact_in_place(model, rows):
|
| 77 |
+
return adapter_for(model).compact(model, rows)
|
requests/fd7c309dd6d8431ba83fda6aa954b87b/run.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Launch the same MoEDiet pipeline locally or on Hugging Face Jobs."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
|
| 12 |
+
from gguf_export import QTYPES, export_run
|
| 13 |
+
from probes import clean_tags, make_probes
|
| 14 |
+
from architecture import check_export, load_profile
|
| 15 |
+
from preflight import JOB_REQUIREMENTS
|
| 16 |
+
|
| 17 |
+
HERE = Path(__file__).resolve().parent
|
| 18 |
+
DEFAULT_MODEL = 'allenai/OLMoE-1B-7B-0125-Instruct'
|
| 19 |
+
BUILD_FLAGS = {'budgets': '--budgets', 'lambda': '--lambda', 'max_kl': '--max-kl',
|
| 20 |
+
'eval_tokens': '--eval-tokens', 'dtype': '--dtype', 'device': '--device', 'revision': '--revision',
|
| 21 |
+
'keep_fractions': '--keep-fractions',
|
| 22 |
+
'post_quant_min_first_token': '--post-quant-min-first-token',
|
| 23 |
+
'post_quant_min_full_match': '--post-quant-min-full-match'}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def normalize_v2(raw):
|
| 27 |
+
"""Translate the public v2 schema to one internal plan; reject ambiguous duplicates."""
|
| 28 |
+
raw = dict(raw)
|
| 29 |
+
version = raw.pop('schema_version', 1)
|
| 30 |
+
if type(version) is not int or version not in (1, 2):
|
| 31 |
+
raise ValueError('schema_version deve essere 1 o 2.')
|
| 32 |
+
if version == 1:
|
| 33 |
+
return raw
|
| 34 |
+
model = raw.get('model')
|
| 35 |
+
if not isinstance(model, dict) or 'id' not in model or set(model) - {'id', 'revision'}:
|
| 36 |
+
raise ValueError('model v2 richiede id e opzionalmente revision.')
|
| 37 |
+
raw['model'] = model['id']
|
| 38 |
+
build = raw.get('build', {})
|
| 39 |
+
if not isinstance(build, dict):
|
| 40 |
+
raise ValueError('build deve essere un oggetto.')
|
| 41 |
+
build = dict(build)
|
| 42 |
+
|
| 43 |
+
def put(key, value):
|
| 44 |
+
if key in build:
|
| 45 |
+
raise ValueError(f'Parametro duplicato: {key}.')
|
| 46 |
+
build[key] = value
|
| 47 |
+
|
| 48 |
+
if 'revision' in model:
|
| 49 |
+
put('revision', model['revision'])
|
| 50 |
+
pruning = raw.pop('pruning', {})
|
| 51 |
+
if not isinstance(pruning, dict) or set(pruning) - {'budgets', 'keep_fractions', 'preserve_top_k', 'shared_experts'}:
|
| 52 |
+
raise ValueError('Parametri pruning sconosciuti.')
|
| 53 |
+
if pruning.get('preserve_top_k', True) is not True or pruning.get('shared_experts', 'preserve') != 'preserve':
|
| 54 |
+
raise ValueError('Questa versione preserva top-k ed esperti condivisi.')
|
| 55 |
+
for key in ('budgets', 'keep_fractions'):
|
| 56 |
+
if key in pruning:
|
| 57 |
+
put(key, pruning[key])
|
| 58 |
+
validation = raw.pop('validation', {})
|
| 59 |
+
if not isinstance(validation, dict) or set(validation) - {
|
| 60 |
+
'max_kl', 'eval_tokens', 'require_control', 'post_quant_min_first_token', 'post_quant_min_full_match'}:
|
| 61 |
+
raise ValueError('Parametri validation sconosciuti.')
|
| 62 |
+
if validation.get('require_control', True) is not True:
|
| 63 |
+
raise ValueError('Il controllo separato resta obbligatorio.')
|
| 64 |
+
for key in ('max_kl', 'eval_tokens', 'post_quant_min_first_token', 'post_quant_min_full_match'):
|
| 65 |
+
if key in validation:
|
| 66 |
+
put(key, validation[key])
|
| 67 |
+
export = raw.pop('export', {'format': 'hf'})
|
| 68 |
+
if (not isinstance(export, dict) or set(export) - {'format', 'quantization'}
|
| 69 |
+
or export.get('format') not in ('hf', 'gguf') or 'quantization' in raw):
|
| 70 |
+
raise ValueError('Export v2: scegliere format hf oppure gguf, senza quantization al livello principale.')
|
| 71 |
+
if export['format'] == 'hf' and 'quantization' in export:
|
| 72 |
+
raise ValueError('La quantizzazione si specifica solo con export.format=gguf.')
|
| 73 |
+
raw['quantization'] = export.get('quantization', 'Q4_K_M') if export['format'] == 'gguf' else None
|
| 74 |
+
if export['format'] == 'gguf' and raw['quantization'] not in QTYPES:
|
| 75 |
+
raise ValueError('Quantizzazione GGUF non supportata.')
|
| 76 |
+
raw['build'] = build
|
| 77 |
+
return raw
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def path_from(base, value):
|
| 81 |
+
expanded = os.path.expandvars(str(value))
|
| 82 |
+
path = Path(expanded).expanduser()
|
| 83 |
+
if path.is_absolute():
|
| 84 |
+
return str(path.resolve())
|
| 85 |
+
return str((base / path).resolve())
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def load_config(filename, tags=None, repo=None, metadata_only=False):
|
| 89 |
+
filename = Path(os.path.expandvars(str(filename))).expanduser().resolve()
|
| 90 |
+
raw = json.loads(filename.read_text(encoding='utf-8-sig'))
|
| 91 |
+
if not isinstance(raw, dict):
|
| 92 |
+
raise ValueError('La configurazione deve essere un oggetto JSON.')
|
| 93 |
+
raw = normalize_v2(raw)
|
| 94 |
+
if not isinstance(raw, dict) or raw.get('mode') not in ('local', 'hf'):
|
| 95 |
+
raise ValueError('Il profilo JSON richiede mode uguale a local o hf.')
|
| 96 |
+
local = raw['mode'] == 'local'
|
| 97 |
+
common = {'mode', 'model', 'tags', 'quantization', 'build', 'corpus', 'architecture_profile'}
|
| 98 |
+
extra = {'out', 'llama_dir', 'bin_dir'} if local else {
|
| 99 |
+
'output_repo', 'flavor', 'timeout', 'requirements', 'allow_public_output'}
|
| 100 |
+
if unknown := set(raw) - common - extra:
|
| 101 |
+
raise ValueError(f'Chiavi di configurazione sconosciute: {sorted(unknown)}')
|
| 102 |
+
names = raw.get('tags') if tags is None else tags
|
| 103 |
+
if not isinstance(names, list) or not all(isinstance(name, str) for name in names):
|
| 104 |
+
raise ValueError('tags deve essere una lista di stringhe.')
|
| 105 |
+
cfg = {'mode': raw['mode'], 'tags': clean_tags(names), 'model': raw.get('model', DEFAULT_MODEL),
|
| 106 |
+
'quantization': raw.get('quantization', 'Q4_K_M'), 'build': raw.get('build', {})}
|
| 107 |
+
if cfg['quantization'] not in (*QTYPES, None):
|
| 108 |
+
raise ValueError(f'quantization deve essere null oppure uno tra {QTYPES}.')
|
| 109 |
+
if 'architecture_profile' in raw:
|
| 110 |
+
value = raw['architecture_profile']
|
| 111 |
+
if not isinstance(value, str) or not value.strip():
|
| 112 |
+
raise ValueError('architecture_profile deve essere un nome o percorso JSON.')
|
| 113 |
+
from architecture import BUILTINS
|
| 114 |
+
if value != 'auto' and not metadata_only:
|
| 115 |
+
cfg['architecture'] = load_profile(value if value in BUILTINS else path_from(filename.parent, value))
|
| 116 |
+
check_export(cfg['architecture'], cfg['quantization'])
|
| 117 |
+
if not isinstance(cfg['model'], str) or not cfg['model'].strip():
|
| 118 |
+
raise ValueError('model deve contenere un ID Hub o una cartella locale.')
|
| 119 |
+
build = cfg['build']
|
| 120 |
+
if not isinstance(build, dict) or set(build) - set(BUILD_FLAGS):
|
| 121 |
+
raise ValueError(f'Parametri build consentiti: {list(BUILD_FLAGS)}')
|
| 122 |
+
for key in ('lambda', 'max_kl'):
|
| 123 |
+
value = build.get(key, 0)
|
| 124 |
+
if type(value) not in (int, float) or not math.isfinite(value) or value < 0:
|
| 125 |
+
raise ValueError(f'Valore non valido per {key}.')
|
| 126 |
+
if type(build.get('eval_tokens', 8)) is not int or build.get('eval_tokens', 8) < 1:
|
| 127 |
+
raise ValueError('eval_tokens deve essere un intero positivo.')
|
| 128 |
+
if 'budgets' in build and (not isinstance(build['budgets'], list) or not build['budgets'] or
|
| 129 |
+
any(type(n) is not int or n < 1 for n in build['budgets'])):
|
| 130 |
+
raise ValueError('budgets deve essere una lista di interi positivi.')
|
| 131 |
+
if 'keep_fractions' in build:
|
| 132 |
+
values = build['keep_fractions']
|
| 133 |
+
if ('budgets' in build or not isinstance(values, list) or not values or any(type(x) not in (int, float)
|
| 134 |
+
or not math.isfinite(x) or not 0 < x <= 1 for x in values)):
|
| 135 |
+
raise ValueError('keep_fractions richiede frazioni in (0, 1] ed esclude budgets.')
|
| 136 |
+
if build.get('device', 'auto') not in ('auto', 'cpu', 'cuda') or build.get('dtype', 'auto') not in (
|
| 137 |
+
'auto', 'float32', 'bfloat16', 'float16'):
|
| 138 |
+
raise ValueError('device o dtype non valido.')
|
| 139 |
+
if 'revision' in build and (not isinstance(build['revision'], str) or not build['revision'].strip()):
|
| 140 |
+
raise ValueError('revision deve essere una stringa non vuota.')
|
| 141 |
+
if raw.get('corpus') and not metadata_only:
|
| 142 |
+
cfg['corpus'] = path_from(filename.parent, raw['corpus'])
|
| 143 |
+
make_probes(cfg['tags'], cfg['corpus'])
|
| 144 |
+
if local:
|
| 145 |
+
if repo:
|
| 146 |
+
raise ValueError('--repo si usa con mode=hf.')
|
| 147 |
+
if not isinstance(raw.get('out'), str) or not raw['out'].strip():
|
| 148 |
+
raise ValueError('Indicare una nuova cartella out.')
|
| 149 |
+
cfg['out'] = path_from(filename.parent, raw['out'])
|
| 150 |
+
local_model = Path(path_from(filename.parent, cfg['model']))
|
| 151 |
+
explicit_path = (cfg['model'].startswith(('.', '~', '$', '%')) or Path(cfg['model']).is_absolute()
|
| 152 |
+
or '\\' in cfg['model'])
|
| 153 |
+
if local_model.is_dir() or explicit_path:
|
| 154 |
+
cfg['model'] = str(local_model)
|
| 155 |
+
for key in ('llama_dir', 'bin_dir'):
|
| 156 |
+
if raw.get(key):
|
| 157 |
+
cfg[key] = path_from(filename.parent, raw[key])
|
| 158 |
+
if cfg.get('bin_dir') and not cfg.get('llama_dir'):
|
| 159 |
+
raise ValueError('bin_dir richiede llama_dir.')
|
| 160 |
+
else:
|
| 161 |
+
from huggingface_hub.utils import validate_repo_id
|
| 162 |
+
cfg['output_repo'] = repo or raw.get('output_repo')
|
| 163 |
+
for name in (cfg['model'], cfg['output_repo']):
|
| 164 |
+
if not isinstance(name, str) or name.count('/') != 1:
|
| 165 |
+
raise ValueError('HF richiede ID nome/modello. Specificare --repo nome/repo-privato per il risultato.')
|
| 166 |
+
validate_repo_id(name)
|
| 167 |
+
if cfg['output_repo'].casefold() == cfg['model'].casefold():
|
| 168 |
+
raise ValueError('Sorgente e repository di destinazione devono essere distinti.')
|
| 169 |
+
cfg.update(flavor=raw.get('flavor', 'l4x1'), timeout=raw.get('timeout', '90m'))
|
| 170 |
+
cfg['allow_public_output'] = bool(raw.get('allow_public_output', False))
|
| 171 |
+
requirements = raw.get('requirements', 'requirements.txt')
|
| 172 |
+
if requirements not in JOB_REQUIREMENTS:
|
| 173 |
+
raise ValueError('requirements deve essere uno tra: ' + ', '.join(JOB_REQUIREMENTS))
|
| 174 |
+
cfg['requirements'] = requirements
|
| 175 |
+
if not isinstance(cfg['timeout'], str) or not re.fullmatch(r'[1-9]\d*[smhd]', cfg['timeout']):
|
| 176 |
+
raise ValueError('Timeout non valido (per esempio 90m).')
|
| 177 |
+
if not isinstance(cfg['flavor'], str) or not re.fullmatch(r'[a-z0-9-]+', cfg['flavor']):
|
| 178 |
+
raise ValueError('Flavor HF non valido.')
|
| 179 |
+
return cfg
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def build_command(cfg, out):
|
| 183 |
+
cmd = [sys.executable, str(HERE / 'moediet.py'), 'build', '--model', cfg['model'],
|
| 184 |
+
'--tags', *cfg['tags'], '--out', str(out)]
|
| 185 |
+
for name, flag in BUILD_FLAGS.items():
|
| 186 |
+
if name in cfg['build']:
|
| 187 |
+
value = cfg['build'][name]
|
| 188 |
+
values = value if isinstance(value, list) else [value]
|
| 189 |
+
cmd.extend([flag, *map(str, values)])
|
| 190 |
+
if cfg.get('corpus'):
|
| 191 |
+
cmd.extend(['--corpus', cfg['corpus']])
|
| 192 |
+
if cfg.get('architecture'):
|
| 193 |
+
cmd.extend(['--architecture-profile', json.dumps(cfg['architecture'], separators=(',', ':'))])
|
| 194 |
+
return cmd
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def execute(cfg, out, publish=None):
|
| 198 |
+
subprocess.run(build_command(cfg, out), check=True)
|
| 199 |
+
if publish:
|
| 200 |
+
publish(out, '') # Keep the audited result even if the subsequent conversion fails.
|
| 201 |
+
if cfg['quantization']:
|
| 202 |
+
folder = export_run(out, cfg['quantization'], cfg.get('llama_dir'), cfg.get('bin_dir'))
|
| 203 |
+
if folder and publish:
|
| 204 |
+
publish(folder, folder.relative_to(out).as_posix())
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def main(argv=None):
|
| 208 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 209 |
+
parser.add_argument('--config', type=lambda p: Path(os.path.expandvars(p)).expanduser(), required=True)
|
| 210 |
+
parser.add_argument('--tags', nargs='+', help='Sostituisce i tag del profilo')
|
| 211 |
+
parser.add_argument('--repo', help='Repository HF privato di destinazione, nome/repo')
|
| 212 |
+
parser.add_argument('--dry-run', action='store_true', help='Convalida il piano senza download, upload o Job')
|
| 213 |
+
parser.add_argument('--preflight', action='store_true', help='Legge solo metadati del modello, senza pesi, upload o Job')
|
| 214 |
+
parser.add_argument('--inspect-safetensors', action='store_true',
|
| 215 |
+
help='Inventaria header e config SafeTensors locali o Hub senza leggere i payload')
|
| 216 |
+
args = parser.parse_args(argv)
|
| 217 |
+
cfg = load_config(args.config, args.tags, args.repo, metadata_only=args.inspect_safetensors)
|
| 218 |
+
selected_modes = sum((args.dry_run, args.preflight, args.inspect_safetensors))
|
| 219 |
+
if selected_modes > 1:
|
| 220 |
+
raise ValueError('Scegliere una sola tra --dry-run, --preflight e --inspect-safetensors.')
|
| 221 |
+
if args.dry_run:
|
| 222 |
+
print(json.dumps(cfg, ensure_ascii=False, indent=2))
|
| 223 |
+
return
|
| 224 |
+
if args.inspect_safetensors:
|
| 225 |
+
from safetensors_metadata import inspect_hub_safetensors, inspect_safetensors
|
| 226 |
+
if cfg['mode'] == 'local':
|
| 227 |
+
if not Path(cfg['model']).is_dir():
|
| 228 |
+
raise ValueError('--inspect-safetensors in mode=local richiede una directory modello esistente.')
|
| 229 |
+
result = inspect_safetensors(cfg['model'])
|
| 230 |
+
else:
|
| 231 |
+
result = inspect_hub_safetensors(cfg['model'], cfg['build'].get('revision'))
|
| 232 |
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
| 233 |
+
return
|
| 234 |
+
if args.preflight:
|
| 235 |
+
from preflight import inspect
|
| 236 |
+
print(json.dumps(inspect(cfg), ensure_ascii=False, indent=2))
|
| 237 |
+
return
|
| 238 |
+
if cfg['mode'] == 'local':
|
| 239 |
+
from preflight import inspect
|
| 240 |
+
plan = inspect(cfg)
|
| 241 |
+
cfg['architecture'] = plan['architecture']
|
| 242 |
+
if plan['source_revision']:
|
| 243 |
+
cfg['build']['revision'] = plan['source_revision']
|
| 244 |
+
execute(cfg, Path(cfg['out']))
|
| 245 |
+
else:
|
| 246 |
+
from hf_jobs import submit
|
| 247 |
+
submit(cfg)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
if __name__ == '__main__':
|
| 251 |
+
try:
|
| 252 |
+
main()
|
| 253 |
+
except (ValueError, OSError, ImportError, subprocess.SubprocessError) as error:
|
| 254 |
+
sys.exit(f'Errore: {error}')
|