import hashlib import json import numpy as np QTYPES = {"choice": 0, "score": 1, "noul": 2} INPUT_NAMES = ("input_ids", "attention_mask", "marker_pos", "marker_mask", "qtype") def state_text(state): return state if isinstance(state, str) else json.dumps(state, ensure_ascii=False, sort_keys=True) def group_key(row): return hashlib.sha256(state_text(row["state"]).encode()).hexdigest() def options_for(question): kind = question["type"] criteria = question.get("criteria") if kind == "choice": if not isinstance(criteria, dict) or not 2 <= len(criteria) <= 20: raise ValueError("choice requires a mapping containing 2 to 20 options") labels = list(criteria) if any(not isinstance(label, str) or not label for label in labels): raise ValueError("choice labels must be nonempty strings") descriptions = [f"{label}: {criteria[label]}" for label in labels] elif kind == "score": if not isinstance(criteria, list) or not 2 <= len(criteria) <= 20: raise ValueError("score requires a list containing 2 to 20 ordered levels") labels = [str(index) for index in range(len(criteria))] descriptions = [f"level {index}: {value}" for index, value in enumerate(criteria)] elif kind == "noul": criteria = criteria or {} if not isinstance(criteria, dict) or set(criteria) - {"false", "true"}: raise ValueError("noul criteria must use false and true") labels = ["false", "true"] wording = question.get("labels", {"false": "false", "true": "true"}) if set(wording) != {"false", "true"}: raise ValueError("noul labels must contain false and true") descriptions = [ f"{wording['false']}: {criteria.get('false', 'no, the statement does not hold')}", f"{wording['true']}: {criteria.get('true', 'yes, the statement holds')}", ] else: raise ValueError(f"Unsupported question type: {kind}") return labels, descriptions def encode_question(tokenizer, state, question, max_length=512): if not 32 <= max_length <= 512: raise ValueError("max_length must be between 32 and 512") labels, descriptions = options_for(question) special = {name: tokenizer.token_to_id(name) for name in ["[CLS]", "[SEP]", "[MASK]"]} if any(value is None for value in special.values()): raise ValueError("The tokenizer is missing required BERT special tokens") def tokenize(text): return tokenizer.encode(str(text).replace("[MASK]", " "), add_special_tokens=False).ids instructions = question.get("instructions", "") if not isinstance(instructions, str) or not instructions.strip(): raise ValueError("A nonempty instructions string is required") prefix = tokenize(f"{question['type']} question: {instructions}") identifiers = [special["[CLS]"]] + prefix + [special["[SEP]"]] markers = [] for description in descriptions: markers.append(len(identifiers)) identifiers.extend([special["[MASK]"]] + tokenize(description)) identifiers.append(special["[SEP]"]) if len(identifiers) > min(192, max_length - 16): raise ValueError("Question/options exceed the prompt budget; shorten them explicitly") content = tokenize(state_text(state)) room = max_length - len(identifiers) - 1 identifiers.extend(content[:room] + [special["[SEP]"]]) return { "input_ids": identifiers, "marker_pos": markers, "qtype": QTYPES[question["type"]], "labels": labels, "truncated_state": len(content) > room, } def collate(features): length = max(len(feature["input_ids"]) for feature in features) option_count = max(len(feature["marker_pos"]) for feature in features) batch_size = len(features) arrays = { "input_ids": np.zeros((batch_size, length), dtype=np.int64), "attention_mask": np.zeros((batch_size, length), dtype=np.int64), "marker_pos": np.zeros((batch_size, option_count), dtype=np.int64), "marker_mask": np.zeros((batch_size, option_count), dtype=np.bool_), "qtype": np.zeros(batch_size, dtype=np.int64), } for index, feature in enumerate(features): sequence_length = len(feature["input_ids"]) count = len(feature["marker_pos"]) arrays["input_ids"][index, :sequence_length] = feature["input_ids"] arrays["attention_mask"][index, :sequence_length] = 1 arrays["marker_pos"][index, :count] = feature["marker_pos"] arrays["marker_mask"][index, :count] = True arrays["qtype"][index] = feature["qtype"] return arrays def normalized_probabilities(values, count): probabilities = np.asarray(values, dtype=np.float64) if probabilities.shape != (count,) or not np.isfinite(probabilities).all(): raise ValueError("Teacher probabilities have an invalid shape or nonfinite values") if (probabilities < 0).any() or probabilities.sum() <= 0: raise ValueError("Teacher probabilities must be nonnegative and have positive mass") return probabilities / probabilities.sum() def read_rows(path): with open(path, encoding="utf-8") as handle: return [json.loads(line) for line in handle if line.strip()]