Datasets:
compactfact-training-data / sources /base-semantic /src /compact_fact_extraction /factsetnet /semantic_init.py
Download sources/base-semantic/src/compact_fact_extraction/factsetnet/semantic_init.py from Monyzik/compactfact-training-data: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/datasets/Monyzik/compactfact-training-data/resolve/main/sources/base-semantic/src/compact_fact_extraction/factsetnet/semantic_init.py
- Command line
-
hf download hf://datasets/Monyzik/compactfact-training-data/sources/base-semantic/src/compact_fact_extraction/factsetnet/semantic_init.py
-
curl -L -o semantic_init.py https://huggingface.co/datasets/Monyzik/compactfact-training-data/resolve/main/sources/base-semantic/src/compact_fact_extraction/factsetnet/semantic_init.py
10.7 kB
| """Optional classifier initialization from train/catalog label descriptions.""" | |
| import hashlib | |
| import json | |
| import random | |
| import torch | |
| from torch.nn import functional as F | |
| def _json_hash(value): | |
| return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, | |
| separators=(",", ":")).encode()).hexdigest() | |
| def _tensor_hash(values): | |
| digest = hashlib.sha256() | |
| for value in values: | |
| value = value.detach().float().cpu().contiguous() | |
| digest.update(json.dumps(list(value.shape)).encode()) | |
| digest.update(value.numpy().tobytes()) | |
| return digest.hexdigest() | |
| def _summary(values): | |
| if not values.numel(): | |
| return None | |
| values = values.float() | |
| return {"min": float(values.min()), "max": float(values.max()), | |
| "mean": float(values.mean()), "p50": float(values.quantile(.5)), | |
| "p95": float(values.quantile(.95))} | |
| def _cosine_diagnostics(texts, prototypes, label_rows, limit=128): | |
| # Local RNG and deterministic pair order do not perturb training randomness. | |
| rng = random.Random(0) | |
| count = len(texts) | |
| if count * (count - 1) // 2 <= limit: | |
| pairs = {(a, b) for a in range(count) for b in range(a + 1, count) | |
| if texts[a] != texts[b]} | |
| else: | |
| pairs = set() | |
| for _ in range(limit * 20): | |
| a, b = sorted(rng.sample(range(count), 2)) | |
| if texts[a] != texts[b]: | |
| pairs.add((a, b)) | |
| if len(pairs) == limit: | |
| break | |
| pairs = sorted(pairs) | |
| values = (F.cosine_similarity(prototypes[[a for a, _ in pairs]], | |
| prototypes[[b for _, b in pairs]], dim=-1) | |
| if pairs else torch.empty(0)) | |
| return {"pairs": len(pairs), | |
| "pair_classifier_rows": [[label_rows[a], label_rows[b]] for a, b in pairs], | |
| "pair_texts_sha256": _json_hash( | |
| [[texts[a], texts[b]] for a, b in pairs]), | |
| "cosine": _summary(values), | |
| "fraction_at_least_0p99": float((values >= .99).float().mean()) if pairs else None, | |
| "selection": "local Random(0), distinct non-identical label strings"} | |
| def initialize_semantic_labels(model, tokenizer, vocabulary, *, batch_size=16, max_length=None): | |
| """Replace nonempty rows1: directions; copy0/empty rows, norms and biases persist. | |
| Every label token contributes once, including descriptions longer than a | |
| backbone window. Inserted special tokens and padding do not enter pooling. | |
| No training/inference modules or state-dict keys are introduced. | |
| """ | |
| if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size < 1: | |
| raise ValueError("Semantic initialization batch size must be a positive integer") | |
| length = model.config.max_length if max_length is None else max_length | |
| if isinstance(length, bool) or not isinstance(length, int) or length < 1: | |
| raise ValueError("Semantic initialization window length must be positive") | |
| native_limit = getattr(model.backbone.config, "max_position_embeddings", None) | |
| if native_limit is not None and length > native_limit: | |
| raise ValueError("Semantic initialization window exceeds backbone position limit") | |
| capacity = length - tokenizer.num_special_tokens_to_add(False) | |
| if capacity < 1 or not tokenizer.is_fast: | |
| raise ValueError("Semantic initialization requires a fast tokenizer and a content window") | |
| groups = [("objects", "object"), ("values", "value")] | |
| texts, ranges = [], {} | |
| for key, name in groups: | |
| labels = vocabulary[key] | |
| if not labels or labels[0] is not None or len(labels) != model.classifiers[name].out_features: | |
| raise ValueError("Semantic initialization vocabulary/classifier mismatch: " + key) | |
| if any(not isinstance(text, str) for text in labels[1:]): | |
| raise ValueError("Semantic initialization labels must be strings") | |
| start = len(texts) | |
| texts.extend(labels[1:]) | |
| ranges[key] = (start, len(texts)) | |
| backend = json.loads(tokenizer.backend_tokenizer.to_str()) | |
| backend.update(padding=None, truncation=None) # Exclude transient batching state. | |
| tokenizer_hash = _json_hash({"class": type(tokenizer).__name__, "backend": backend}) | |
| token_hash = hashlib.sha256() | |
| device = next(model.parameters()).device | |
| width = model.classifiers["object"].in_features | |
| totals = torch.zeros(len(texts), width, dtype=torch.float64) | |
| counts = torch.zeros(len(texts), dtype=torch.long) | |
| modes = [(module, module.training) for module in model.modules()] | |
| padding_side = tokenizer.padding_side | |
| windows, masks, owners = [], [], [] | |
| preserved = {} | |
| window_count = max_batch = max_window = 0 | |
| def flush(): | |
| nonlocal window_count, max_batch, max_window | |
| if not windows: | |
| return | |
| padded = tokenizer.pad(windows, return_tensors="pt") | |
| width_tokens = padded["input_ids"].shape[1] | |
| mask = torch.tensor([row + [0] * (width_tokens - len(row)) for row in masks], | |
| device=device, dtype=torch.bool) | |
| inputs = {key: value.to(device) for key, value in padded.items()} | |
| states = model.projection(model.backbone(**inputs).last_hidden_state).float() | |
| pooled = (states * mask.unsqueeze(-1)).sum(1).cpu().double() | |
| if not torch.isfinite(pooled).all(): | |
| raise FloatingPointError("Nonfinite semantic label prototype") | |
| indices = torch.tensor(owners) | |
| totals.index_add_(0, indices, pooled) | |
| counts.index_add_(0, indices, mask.sum(1).cpu()) | |
| window_count += len(windows) | |
| max_batch = max(max_batch, len(windows)) | |
| max_window = max(max_window, width_tokens) | |
| windows.clear(); masks.clear(); owners.clear() | |
| try: | |
| model.eval() | |
| tokenizer.padding_side = "right" | |
| for index, text in enumerate(texts): | |
| ids = tokenizer(text, add_special_tokens=False, truncation=False, | |
| return_attention_mask=False, return_token_type_ids=False, | |
| verbose=False)["input_ids"] | |
| token_hash.update(json.dumps([index, ids], separators=(",", ":")).encode() + b"\n") | |
| if not ids: | |
| preserved[index] = "empty_or_whitespace" if not text.strip() else "tokenizer_empty" | |
| continue | |
| for start in range(0, len(ids), capacity): | |
| piece = ids[start:start + capacity] | |
| inputs = tokenizer.build_inputs_with_special_tokens(piece) | |
| template = tokenizer.build_inputs_with_special_tokens([-1] * len(piece)) | |
| windows.append({"input_ids": inputs, "attention_mask": [1] * len(inputs)}) | |
| masks.append([int(token == -1) for token in template]) | |
| owners.append(index) | |
| if len(windows) == batch_size: | |
| flush() | |
| flush() | |
| available = counts > 0 | |
| if any(index not in preserved for index in torch.where(~available)[0].tolist()): | |
| raise ValueError("A semantic label has no pooled content tokens") | |
| prototypes = (totals / counts.clamp_min(1).unsqueeze(1)).float() | |
| norms = prototypes.norm(dim=1) | |
| if (not torch.isfinite(prototypes).all() or not torch.isfinite(norms).all() or | |
| bool((norms[available] <= 0).any())): | |
| raise FloatingPointError("Semantic prototypes must be finite and nonzero") | |
| initialized, diagnostics, replacements = [], {}, {} | |
| # Validate every prototype before modifying either classifier. | |
| for key, name in groups: | |
| start, end = ranges[key] | |
| values = prototypes[start:end] | |
| head = model.classifiers[name] | |
| valid = available[start:end] | |
| original_norms = head.weight[1:].float().norm(dim=1).cpu() | |
| if not torch.isfinite(original_norms).all(): | |
| raise FloatingPointError("Nonfinite original classifier row norms") | |
| rows = head.weight[1:].float().cpu().clone() | |
| rows[valid] = F.normalize(values[valid], dim=1) * original_norms[valid].unsqueeze(1) | |
| replacements[name] = rows.to(head.weight) | |
| initialized.append(rows) | |
| label_rows = (torch.where(valid)[0] + 1).tolist() | |
| unembedded = [{"field": key, "row": index - start + 1, "reason": preserved[index], | |
| "text_sha256": _json_hash(texts[index]), | |
| "original_row_sha256": _tensor_hash([head.weight[index - start + 1]])} | |
| for index in range(start, end) if index in preserved] | |
| diagnostics[key] = {"labels": end - start, | |
| "initialized_labels": int(valid.sum()), | |
| "preserved_unembedded_count": len(unembedded), | |
| "preserved_unembedded_rows": unembedded, | |
| "prototype_norm": _summary(norms[start:end][valid]), | |
| "preserved_row_norm": _summary(original_norms), | |
| "nonidentical_pairs": _cosine_diagnostics( | |
| [texts[start + row - 1] for row in label_rows], values[valid], label_rows)} | |
| report = {"version": 1, "method": "backbone+projection content-token mean; original per-row L2 scale", | |
| "copy_row0": "unchanged", "biases": "unchanged", "dropout": "disabled during initialization", | |
| "vocabulary_sha256": _json_hash(vocabulary), "label_texts_sha256": _json_hash(texts), | |
| "label_token_ids_sha256": token_hash.hexdigest(), "tokenizer_sha256": tokenizer_hash, | |
| "prototype_tensors_sha256": _tensor_hash([prototypes]), | |
| "initialized_rows_sha256": _tensor_hash(initialized), | |
| "batch_size": batch_size, "window_length": length, | |
| "content_tokens": int(counts.sum()), "windows": window_count, | |
| "max_batch_windows": max_batch, "max_window_tokens": max_window, | |
| "long_labels": "all tokens, disjoint windows, token-count-weighted pooling", | |
| "groups": diagnostics, "dev_or_val_labels_used": False} | |
| # All validations and allocations finish before either head is changed. | |
| for name, rows in replacements.items(): | |
| model.classifiers[name].weight[1:].copy_(rows) | |
| return report | |
| finally: | |
| tokenizer.padding_side = padding_side | |
| for module, mode in modes: | |
| module.training = mode | |