Initialize optimizer research workspace with official baselines and history-free coverage

Vendor pinned MeZO, AGZO, LOZO and LoREN sources with independent environments. Add direct in-place fix/adjust/node training, derived history-free basis gradients, development-best checkpoints and experiment tooling. Keep models, datasets, caches and credentials outside Git.

Validation: 93 project tests passed; 521 vendored author files verified.
This commit is contained in:
gloamxun committed 2026-11-12 23:32:33 +08:00
commit e0feabec8f
596 files changed
+87356

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Princeton Natural Language Processing
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+96
View File
@@ -0,0 +1,96 @@
{
"commit": "552cb1b710767f9a6e1dc8f9645d7640376f9941",
"files": {
"templates.py": {
"upstream": "baselines/mezo/large_models/templates.py",
"upstream_sha256": "bc80e8f55c4d7cfdd3ca8493131297b6c7687d7ebc714ee5aebe16c6856ec2f6",
"reused_sha256": "bc80e8f55c4d7cfdd3ca8493131297b6c7687d7ebc714ee5aebe16c6856ec2f6",
"changes": []
},
"metrics.py": {
"upstream": "baselines/mezo/large_models/metrics.py",
"upstream_sha256": "a9146177b85b5aa654583ac2ed1f0c6aefb8940bf86aa4964ad02bd46165c94c",
"reused_sha256": "a9146177b85b5aa654583ac2ed1f0c6aefb8940bf86aa4964ad02bd46165c94c",
"changes": []
},
"tasks.py": {
"upstream": "baselines/mezo/large_models/tasks.py",
"upstream_sha256": "693c28ccc7e02997a7dced601f15a89d67a514581f98d1bc642768ef3271ed58",
"reused_sha256": "11f2904364f63f462aebb64adc191dc59fb0e0ad632c474f80c1d8617af45376",
"changes": [
{
"old": "from templates import *",
"new": "from .templates import *"
},
{
"old": "from utils import temp_seed",
"new": "from .utils import temp_seed"
},
{
"old": "from datasets import load_dataset",
"new": "from .assets import load_dataset"
}
]
},
"utils.py": {
"upstream": "baselines/mezo/large_models/utils.py",
"upstream_sha256": "04686e63041fcc9efce7284ead16c8b5a5aa6f6e648ede447b587cad9531b0aa",
"reused_sha256": "2b4df62167638e61f63ab7d90857d0d7114bb656f84b61f8e4f4ff68d0495570",
"changes": [
{
"old": "if tokenizer.add_bos_token:",
"new": "if getattr(tokenizer, \"add_bos_token\", False):"
}
]
},
"_upstream_run.py": {
"upstream": "baselines/mezo/large_models/run.py",
"upstream_sha256": "00b864c0e53c28f02572a510e6d612bfcca38682be843054bc1806354815bd81",
"reused_sha256": "32d6dc17ab9da185912c813b80487ce2db28fd213ac31b03cab6c801e9d742ec",
"changes": [
{
"old": "import tasks",
"new": "from . import tasks"
},
{
"old": "from tasks import get_task",
"new": "from .tasks import get_task"
},
{
"old": "from metrics import calculate_metric",
"new": "from .metrics import calculate_metric"
},
{
"old": "from utils import *",
"new": "from .utils import *"
},
{
"old": "from trainer import OurTrainer",
"new": "from .trainer import OurTrainer"
},
{
"old": "free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3)",
"new": "free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) if torch.cuda.is_available() else 0"
},
{
"old": "config=config,\n )",
"new": "config=config,\n torch_dtype=torch.float32, attn_implementation=\"eager\", local_files_only=True,\n )"
},
{
"old": "tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast=False)",
"new": "tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast=\"qwen\" in self.args.model_name.lower(), local_files_only=True)\n if tokenizer.pad_token_id is None:\n tokenizer.pad_token = tokenizer.eos_token"
},
{
"old": "if self.args.save_on_interrupt:\n trainer.add_callback",
"new": "self.trainer = trainer\n if self.args.save_on_interrupt:\n trainer.add_callback"
}
]
}
},
"trainer_reuse": {
"upstream": "baselines/mezo/large_models/trainer.py:OurTrainer.zo_forward",
"ast_identical": true,
"base": "transformers.Trainer (modern supported API)",
"reason": "MeZO 2023 copied Trainer imports removed private APIs; retain original zo_forward and Framework, replace only inner loop with structured branches"
}
}
+1
View File
@@ -0,0 +1 @@
"""MeZO-style shared implementation for our structured optimizers."""
+532
View File
@@ -0,0 +1,532 @@
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
import argparse
import time
from . import tasks
from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM, Trainer, HfArgumentParser, Trainer, TrainingArguments, DataCollatorWithPadding, DataCollatorForTokenClassification
from typing import Union, Optional
import torch
from torch.nn.parameter import Parameter
import numpy as np
from dataclasses import dataclass, is_dataclass, asdict
from tqdm import tqdm
from .tasks import get_task
import json
import torch.nn.functional as F
from torch.utils.data import Dataset
from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
from .metrics import calculate_metric
from .utils import *
from .trainer import OurTrainer
import random
@dataclass
class OurArguments(TrainingArguments):
# dataset and sampling strategy
task_name: str = "SST2" # task name should match the string before Dataset in the Dataset class name. We support the following task_name: SST2, RTE, CB, BoolQ, WSC, WIC, MultiRC, Copa, ReCoRD, SQuAD, DROP
# Number of examples
num_train: int = 0 # ICL mode: number of demonstrations; training mode: number of training samples
num_dev: int = None # (only enabled with training) number of development samples
num_eval: int = None # number of evaluation samples
num_train_sets: int = None # how many sets of training samples/demos to sample; if None and train_set_seed is None, then we will sample one set for each evaluation sample
train_set_seed: int = None # designated seed to sample training samples/demos
result_file: str = None # file name for saving performance; if None, then use the task name, model name, and config
# Model loading
model_name: str = "facebook/opt-125m" # HuggingFace model name
load_float16: bool = False # load model parameters as float16
load_bfloat16: bool = False # load model parameters as bfloat16
load_int8: bool = False # load model parameters as int8
max_length: int = 2048 # max length the model can take
no_auto_device: bool = False # do not load model by auto device; should turn this on when using FSDP
# Calibration
sfc: bool = False # whether to use SFC calibration
icl_sfc: bool = False # whether to use SFC calibration for ICL samples
# Training
trainer: str = "none"
## options
## - none: no training -- for zero-shot or in-context learning (ICL)
## - regular: regular huggingface trainer -- for fine-tuning
## - zo: zeroth-order (MeZO) training
only_train_option: bool = True # whether to only train the option part of the input
train_as_classification: bool = False # take the log likelihood of all options and train as classification
# MeZO
zo_eps: float = 1e-3 # eps in MeZO
# Prefix tuning
prefix_tuning: bool = False # whether to use prefix tuning
num_prefix: int = 5 # number of prefixes to use
no_reparam: bool = True # do not use reparameterization trick
prefix_init_by_real_act: bool = True # initialize prefix by real activations of random words
# LoRA
lora: bool = False # whether to use LoRA
lora_alpha: int = 16 # alpha in LoRA
lora_r: int = 8 # r in LoRA
# Generation
sampling: bool = False # whether to use sampling
temperature: float = 1.0 # temperature for generation
num_beams: int = 1 # number of beams for generation
top_k: int = None # top-k for generation
top_p: float = 0.95 # top-p for generation
max_new_tokens: int = 50 # max number of new tokens to generate
eos_token: str = "\n" # end of sentence token
# Saving
save_model: bool = False # whether to save the model
no_eval: bool = False # whether to skip evaluation
tag: str = "" # saving tag
# Linear probing
linear_probing: bool = False # whether to do linear probing
lp_early_stopping: bool = False # whether to do early stopping in linear probing
head_tuning: bool = False # head tuning: only tune the LM head
# Untie emb/lm_head weights
untie_emb: bool = False # untie the embeddings and LM head
# Display
verbose: bool = False # verbose output
# Non-diff objective
non_diff: bool = False # use non-differentiable objective (only support F1 for SQuAD for now)
# Auto saving when interrupted
save_on_interrupt: bool = False # save model when interrupted (useful for long training)
def parse_args():
parser = argparse.ArgumentParser()
parser = HfArgumentParser(OurArguments)
args = parser.parse_args_into_dataclasses()[0]
print(args)
return args
def set_seed(seed: int):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
class Framework:
def __init__(self, args, task):
self.args = args
self.task = task
self.model, self.tokenizer = self.load_model()
def load_model(self):
"""
Load HuggingFace models
"""
with count_time("Loading model with FP%d" % (16 if self.args.load_float16 else 32)):
free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) if torch.cuda.is_available() else 0
config = AutoConfig.from_pretrained(self.args.model_name)
if self.args.untie_emb:
# Untie embeddings/LM head
logger.warn("Untie embeddings and LM head")
config.tie_word_embeddings = False
if self.args.head_tuning:
# Head tuning
from ht_opt import OPTForCausalLM
model = OPTForCausalLM.from_pretrained(
self.args.model_name,
config=config,
torch_dtype=torch.float32, attn_implementation="eager", local_files_only=True,
)
elif self.args.no_auto_device:
# No auto device (use for FSDP)
model = AutoModelForCausalLM.from_pretrained(
self.args.model_name,
config=config,
torch_dtype=torch.float32, attn_implementation="eager", local_files_only=True,
)
else:
# Auto device loading
torch_dtype = torch.float32
if self.args.load_float16:
torch_dtype = torch.float16
elif self.args.load_bfloat16:
torch_dtype = torch.bfloat16
model = AutoModelForCausalLM.from_pretrained(
self.args.model_name,
config=config,
device_map='auto',
torch_dtype=torch_dtype,
max_memory={i: f'{free_in_GB-5}GB' for i in range(torch.cuda.device_count())},
load_in_8bit=self.args.load_int8,
)
model.eval()
# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast="qwen" in self.args.model_name.lower(), local_files_only=True)
if tokenizer.pad_token_id is None:
tokenizer.pad_token = tokenizer.eos_token
# HF tokenizer bug fix
if "opt" in self.args.model_name:
tokenizer.bos_token_id = 0
if "llama" in self.args.model_name:
# LLaMA padding token
tokenizer.pad_token_id = 0 # technically <unk>
# Prefix tuning/LoRA
if self.args.prefix_tuning:
from prefix import PrefixTuning
PrefixTuning(model, num_prefix=self.args.num_prefix, reparam=not self.args.no_reparam, float16=self.args.load_float16, init_by_real_act=self.args.prefix_init_by_real_act)
if self.args.lora:
from lora import LoRA
LoRA(model, r=self.args.lora_r, alpha=self.args.lora_alpha, float16=self.args.load_float16)
if self.args.head_tuning:
if model.config.model_type == "opt":
head_name = "lm_head" if self.args.untie_emb else "embed_tokens"
else:
raise NotImplementedError
for n, p in model.named_parameters():
if head_name not in n:
p.requires_grad = False
else:
logger.info(f"Only tuning {n}")
return model, tokenizer
def forward(self, input_ids, option_len=None, generation=False):
"""
Given input_ids and the length of the option, return the log-likelihood of each token in the option.
For generation tasks, return the generated text.
This function is only for inference
"""
input_ids = torch.tensor([input_ids]).to(self.model.device)
if generation:
args = self.args
# Autoregressive generation
outputs = self.model.generate(
input_ids, do_sample=args.sampling, temperature=args.temperature,
num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, max_new_tokens=min(args.max_new_tokens, args.max_length - input_ids.size(1)),
num_return_sequences=1, eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], self.tokenizer.eos_token_id],
)
# For generation, directly return the text output
output_text = self.tokenizer.decode(outputs[0][input_ids.size(1):], skip_special_tokens=True).strip()
return output_text
else:
with torch.inference_mode():
self.model.eval()
logits = self.model(input_ids=input_ids).logits
labels = input_ids[0, 1:]
logits = logits[0, :-1]
log_probs = F.log_softmax(logits, dim=-1)
selected_log_probs = log_probs[torch.arange(len(labels)).to(labels.device), labels]
selected_log_probs = selected_log_probs.cpu().detach()
# Only return the option (candidate) part
return selected_log_probs[-option_len:]
def one_step_pred(self, train_samples, eval_sample, verbose=False):
"""
Return the prediction on the eval sample. In ICL, use train_samples as demonstrations
"""
verbose = verbose or self.args.verbose
if verbose:
logger.info("========= Example =========")
logger.info(f"Candidate: {eval_sample.candidates}")
logger.info(f"Correct candidate: {eval_sample.correct_candidate}")
# Encode (add prompt and tokenize) the sample; if multiple-choice/classification, encode all candidates (options)
encoded_candidates, option_lens = encode_prompt(
self.task, self.task.get_template(), train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length,
generation=self.task.generation, max_new_tokens=self.args.max_new_tokens
)
# Calibration
if self.args.sfc or self.args.icl_sfc:
sfc_encoded_candidates, sfc_option_lens = encode_prompt(self.task, self.task.get_template(),
train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length,
sfc=self.args.sfc, icl_sfc=self.args.icl_sfc, generation=self.task.generation,
max_new_tokens=self.args.max_new_tokens
)
outputs = []
if self.task.generation:
# For generation tasks, return the autoregressively-generated text
output_text = self.forward(encoded_candidates[0], generation=True)
if verbose:
logger.info("=== Prompt ===")
logger.info(self.tokenizer.decode(encoded_candidates[0]))
logger.info(f"Output: {output_text}")
return Prediction(correct_candidate=eval_sample.correct_candidate, predicted_candidate=output_text)
else:
# For classification/multiple-choice, calculate the probabilities of all candidates
for candidate_id, encoded_candidate in enumerate(encoded_candidates):
selected_log_probs = self.forward(encoded_candidate, option_len=option_lens[candidate_id])
if verbose:
if candidate_id == 0:
logger.info("=== Candidate %d ===" % candidate_id)
logger.info(self.tokenizer.decode(encoded_candidate))
else:
logger.info("=== Candidate %d (without context)===" % candidate_id)
logger.info(self.tokenizer.decode(encoded_candidate).split(self.task.train_sep)[-1])
logger.info(f"Log probabilities of the option tokens: {selected_log_probs}")
if self.args.sfc or self.args.icl_sfc:
sfc_selected_log_probs = self.forward(sfc_encoded_candidates[candidate_id], option_len=sfc_option_lens[candidate_id])
if verbose:
logger.info("=== Candidate %d (without context) SFC ===" % candidate_id)
logger.info(self.tokenizer.decode(sfc_encoded_candidates[candidate_id]).split(self.task.train_sep)[-1])
logger.info(f"Log probabilities of the option tokens: {sfc_selected_log_probs}")
outputs.append({"log_probs": selected_log_probs, "sfc_log_probs": sfc_selected_log_probs if self.args.sfc or self.args.icl_sfc else None})
if self.args.sfc or self.args.icl_sfc:
# Calibrated probabilities (surface form competition; https://arxiv.org/pdf/2104.08315.pdf)
# log p(candidate | input) = log p_lm(candidate | input) - log p_lm(candidate | sfc prompt)
scores = [x['log_probs'].sum().item() - x['sfc_log_probs'].sum().item() for x in outputs]
else:
# (Default) length-normalized log probabilities
# log p(candidate | input) = log p_lm(candidate | input) / |candidate #tokens|
scores = [x['log_probs'].mean().item() for x in outputs]
if verbose:
logger.info(f"Prediction scores: {scores}")
if isinstance(eval_sample.correct_candidate, list):
# For some datasets there are multiple correct answers
correct_candidate_id = [eval_sample.candidates.index(c) for c in eval_sample.correct_candidate]
else:
correct_candidate_id = eval_sample.candidates.index(eval_sample.correct_candidate)
return Prediction(correct_candidate=correct_candidate_id, predicted_candidate=int(np.argmax(scores)))
def evaluate(self, train_samples, eval_samples, one_train_set_per_eval_sample=False):
"""
Evaluate function. If one_train_set_per_eval_sample is True, then each eval sample has its own training (demonstration) set.
"""
if one_train_set_per_eval_sample:
logger.info(f"There are {len(eval_samples)} validation samples and one train set per eval sample")
else:
logger.info(f"There are {len(train_samples)} training samples and {len(eval_samples)} validation samples")
# Prediction loop
predictions = []
for eval_id, eval_sample in enumerate(tqdm(eval_samples)):
predictions.append(
self.one_step_pred(train_samples[eval_id] if one_train_set_per_eval_sample else train_samples, eval_sample, verbose=(eval_id < 3))
)
# Calculate metrics
metric_name = getattr(self.task, "metric_name", "accuracy")
metrics = {metric_name: calculate_metric(predictions, metric_name)}
return metrics
def train(self, train_samples, eval_samples):
"""
Training function
"""
# Set tokenizer to left padding (so that all the options are right aligned)
self.tokenizer.padding_side = "left"
class HFDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.data[idx]
def _convert(samples):
"""
Convert samples to HF-compatible dataset
"""
data = []
for sample in samples:
encoded_candidates, option_lens = encode_prompt(
self.task, self.task.get_template(), [], sample, self.tokenizer,
max_length=self.args.max_length, generation=self.task.generation, generation_with_gold=True,
max_new_tokens=self.args.max_new_tokens
)
if self.task.generation:
correct_candidate_id = 0
elif isinstance(sample.correct_candidate, list):
correct_candidate_id = sample.candidates.index(sample.correct_candidate[0])
else:
correct_candidate_id = sample.candidates.index(sample.correct_candidate)
if self.args.non_diff:
# For non-differentiable objective, there is no teacher forcing thus the
# current answer part is removed
encoded_candidates[correct_candidate_id] = encoded_candidates[correct_candidate_id][:-option_lens[correct_candidate_id]]
if self.args.train_as_classification:
# For classification, we provide the label as the correct candidate id
data.append([{"input_ids": encoded_candidates[_i], "labels": correct_candidate_id, "option_len": option_lens[_i], "num_options": len(sample.candidates)} for _i in range(len(encoded_candidates))])
elif self.args.only_train_option:
# Otherwise, it is just LM-style teacher forcing
if self.args.non_diff:
# For non-differentiable objective, we need to provide the gold answer to calculate F1/acc
data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id], "gold": sample.correct_candidate})
else:
data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id]})
else:
data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id]})
return data
with count_time("Tokenizing training samples"):
train_dataset = HFDataset(_convert(train_samples))
eval_dataset = HFDataset(_convert(eval_samples))
if self.args.only_train_option and not self.args.non_diff:
# If --only_train_option and not with a non-differentiable objective, we wrap the forward function
self.model.original_forward = self.model.forward
self.model.forward = forward_wrap_with_option_len.__get__(self.model, type(self.model))
if self.args.non_diff:
collator = NondiffCollator
else:
collator = DataCollatorForTokenClassification
trainer = OurTrainer(
model=self.model,
args=self.args,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
tokenizer=self.tokenizer,
data_collator=DataCollatorWithPaddingAndNesting(self.tokenizer, pad_to_multiple_of=8) if self.args.train_as_classification else collator(self.tokenizer, pad_to_multiple_of=8),
)
self.trainer = trainer
if self.args.save_on_interrupt:
trainer.add_callback(SIGUSR1Callback())
# Resume training from a last checkpoint
last_checkpoint = None
from transformers.trainer_utils import get_last_checkpoint
if os.path.isdir(self.args.output_dir) and not self.args.overwrite_output_dir:
last_checkpoint = get_last_checkpoint(self.args.output_dir)
if last_checkpoint is not None and self.args.resume_from_checkpoint is None:
logger.info(
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
)
if self.args.resume_from_checkpoint is not None:
last_checkpoint = self.args.resume_from_checkpoint
trainer.train(resume_from_checkpoint=last_checkpoint)
# Explicitly save the model
if self.args.save_model:
logger.warn("Save model..")
trainer.save_model()
# FSDP compatibility
self.model = trainer.model
# Reset the forward function for evaluation
if self.args.only_train_option and not self.args.non_diff:
if type(self.model) == FSDP:
logger.info("This is an FSDP model now. Be careful when assigning back the original forward function")
self.model._fsdp_wrapped_module.forward = self.model._fsdp_wrapped_module.original_forward
else:
self.model.forward = self.model.original_forward
def result_file_tag(args):
"""
Get the result file tag
"""
save_model_name = args.model_name.split("/")[-1]
sfc_tag = "-sfc" if args.sfc else ""
icl_sfc_tag = "-icl_sfc" if args.icl_sfc else ""
sample_eval_tag = "-sampleeval%d" % args.num_eval if args.num_eval is not None else ""
sample_train_tag = "-ntrain%d" % args.num_train if args.num_train > 0 else ""
sample_dev_tag = "-ndev%d" % args.num_dev if args.num_dev is not None else ""
customized_tag = f"-{args.tag}" if len(args.tag) > 0 else ""
return f"{args.task_name}-{save_model_name}" + sfc_tag + icl_sfc_tag + sample_eval_tag + sample_train_tag + sample_dev_tag + customized_tag
def main():
args = parse_args()
set_seed(args.seed)
task = get_task(args.task_name)
train_sets = task.sample_train_sets(num_train=args.num_train, num_dev=args.num_dev, num_eval=args.num_eval, num_train_sets=args.num_train_sets, seed=args.train_set_seed)
# Initialize trainer and load model
framework = Framework(args, task)
if args.train_set_seed is not None or args.num_train_sets is not None:
# Eval samples share one (or multiple) training set(s)
for train_set_id, train_samples in enumerate(train_sets):
train_set_seed = train_set_id if args.train_set_seed is None else args.train_set_seed
# Sample eval samples
if args.num_eval is not None:
eval_samples = task.sample_subset(data_split="valid", seed=train_set_seed, num=args.num_eval)
else:
eval_samples = task.valid_samples
if args.trainer != "none":
if args.num_dev is not None:
# Dev samples
dev_samples = train_samples[-args.num_dev:]
train_samples = train_samples[:-args.num_dev]
else:
dev_samples = None
# Training
framework.train(train_samples, dev_samples if dev_samples is not None else eval_samples)
if not args.no_eval:
metrics = framework.evaluate([], eval_samples) # No in-context learning if there is training
if dev_samples is not None:
dev_metrics = framework.evaluate([], dev_samples)
for m in dev_metrics:
metrics["dev_" + m] = dev_metrics[m]
else:
assert args.num_dev is None
# Zero-shot / in-context learning
metrics = framework.evaluate(train_samples, eval_samples)
if not args.no_eval:
logger.info("===== Train set %d =====" % train_set_seed)
logger.info(metrics)
if args.local_rank <= 0:
write_metrics_to_file(metrics, "result/" + result_file_tag(args) + f"-trainset{train_set_id}.json" if args.result_file is None else args.result_file)
else:
# For each eval sample, there is a training set. no training is allowed
# This is for in-context learning (ICL)
assert args.trainer == "none"
if args.num_eval is not None:
eval_samples = task.sample_subset(data_split="valid", seed=0, num=args.num_eval)
else:
eval_samples = task.valid_samples
metrics = framework.evaluate(train_sets, eval_samples, one_train_set_per_eval_sample=True)
logger.info(metrics)
if args.local_rank <= 0:
write_metrics_to_file(metrics, "result/" + result_file_tag(args) + "-onetrainpereval.json" if args.result_file is None else args.result_file)
if __name__ == "__main__":
main()
+9
View File
@@ -0,0 +1,9 @@
"""MeZO's Dataset API backed by the shared local assets, without global monkeypatching."""
from datasets import load_from_disk
from experiments_codebase.paths import paths
def load_dataset(name,config=None,**kwargs):
alias='sst2' if name in ('glue','nyu-mll/glue') and config=='sst2' else ('drop' if name in ('drop','ucinlp/drop') else None)
if alias is None:raise ValueError('This audited integration supports SST2 and DROP only')
dataset=load_from_disk(str(paths()['data']/alias))
return dataset[kwargs['split']] if 'split' in kwargs else dataset
+69
View File
@@ -0,0 +1,69 @@
"""Legacy protocol compatibility and deterministic HF data loading."""
import math
import numpy as np
import torch
from torch.utils.data import Dataset,Sampler
from datasets import load_from_disk
from experiments_codebase.paths import paths
def seed_for(seed, stream, step=0):
"""由总种子、用途编号和步数隔开数据采样、训练和选基的随机流。"""
return int(np.random.SeedSequence([seed, stream, step]).generate_state(1, dtype=np.uint64)[0] % (2 ** 63 - 1))
class HFDataset(Dataset):
def __init__(self,rows):self.data=rows
def __len__(self):return len(self.data)
def __getitem__(self,index):return self.data[index]
class ProtocolSampler(Sampler):
"""Same independent PCG batch-order stream as the previous implementation."""
def __init__(self,dataset,seed):self.dataset=dataset;self.rng=np.random.default_rng(seed_for(seed,11))
def __iter__(self):return iter(self.rng.permutation(len(self.dataset)).tolist())
def __len__(self):return len(self.dataset)
class LegacyCollator:
def __init__(self,tokenizer):self.tokenizer=tokenizer
def __call__(self,rows):
width=math.ceil(max(len(r['input_ids']) for r in rows)/8)*8
ids=torch.full((len(rows),width),self.tokenizer.pad_token_id,dtype=torch.long)
mask=torch.zeros_like(ids);targets=torch.full_like(ids,-100)
for i,row in enumerate(rows):
size=len(row['input_ids']);ids[i,-size:]=torch.tensor(row['input_ids']);mask[i,-size:]=1
if row.get('answer_length',0):targets[i,-row['answer_length']:]=ids[i,-row['answer_length']:]
labels=torch.tensor([r['label'] for r in rows]) if 'label' in rows[0] else targets
return dict(input_ids=ids,attention_mask=mask,labels=labels)
def legacy_rows(args,tokenizer):
ds=load_from_disk(str(paths()['data']/args.task_name.lower()));rng=np.random.default_rng(args.seed)
n=args.num_train+args.num_dev
if n>len(ds['train']):raise ValueError('Train and development counts exceed available data')
ids=rng.permutation(len(ds['train']))[:n];groups={}
for split,source,indices in [('train','train',ids[:args.num_train]),('development','train',ids[args.num_train:]),('validation','validation',range(min(args.num_eval,len(ds['validation']))))]:
rows=[]
for i in indices:
row=ds[source][int(i)]
if args.task_name=='SST2':
tokens=tokenizer.encode(f"{row['sentence'].strip()} It was",add_special_tokens=True,truncation=True,max_length=args.max_length)
rows.append(dict(input_ids=tokens,label=int(row['label']),source_index=int(i),source_split=source))
else:
answers=[str(v) for v in row['answers_spans']['spans']]
answer=tokenizer.encode(' '+answers[0],add_special_tokens=False)[:min(32,args.max_length//4)]
prompt=f"Passage: {row['passage']}\nQuestion: {row['question']}\nAnswer:"
tokens=tokenizer.encode(prompt,add_special_tokens=True,truncation=True,max_length=args.max_length-len(answer))
if not tokens or not answer:raise ValueError('Empty DROP prompt or answer')
rows.append(dict(input_ids=tokens+answer,prompt_ids=tokens,answer_length=len(answer),answers=answers,source_index=int(i),source_split=source))
groups[split]=rows
return groups
def convert_samples(task,samples,tokenizer,args):
"""MeZO Framework._convert for evaluation; unsupported modes are rejected by CLI."""
from .utils import encode_prompt
data=[]
for sample in samples:
candidates,lengths=encode_prompt(task,task.get_template(),[],sample,tokenizer,max_length=args.max_length,
generation=task.generation,generation_with_gold=True,max_new_tokens=args.max_new_tokens)
correct=0 if task.generation else sample.candidates.index(sample.correct_candidate[0] if isinstance(sample.correct_candidate,list) else sample.correct_candidate)
if args.train_as_classification:
data.append([{'input_ids':candidates[i],'labels':correct,'option_len':lengths[i],'num_options':len(sample.candidates)} for i in range(len(candidates))])
else:data.append({'input_ids':candidates[correct],'labels':candidates[correct],'option_len':lengths[correct]})
return data
+34
View File
@@ -0,0 +1,34 @@
"""Shared output helpers; no model loading or optimizer dependencies."""
from contextlib import contextmanager,redirect_stdout,redirect_stderr
import sys
import torch
def memory():
if not torch.cuda.is_available():return {}
torch.cuda.synchronize();free,total=torch.cuda.mem_get_info();g=2**30
return dict(allocated_GiB=torch.cuda.memory_allocated()/g,reserved_GiB=torch.cuda.memory_reserved()/g,
peak_allocated_GiB=torch.cuda.max_memory_allocated()/g,device_used_GiB=(total-free)/g,device_total_GiB=total/g)
def figures(out,curve):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
for key,name in [('loss','loss_curve.png'),('accuracy','acc_curve.png')]:
fig,ax=plt.subplots(figsize=(8,4));found=False
for split in ('train_probe','development'):
points=[p for p in curve if key in p[split]]
if points:ax.plot([p['main_forwards'] for p in points],[p[split][key] for p in points],label=split);found=True
if found:
ax.set(xlabel='Cumulative main forwards (including probes)',ylabel=key);ax.grid(alpha=.2);ax.legend();fig.tight_layout();fig.savefig(out/name,dpi=160)
plt.close(fig)
class Tee:
def __init__(self,*streams):self.streams=streams
def write(self,text):
for stream in self.streams:stream.write(text);stream.flush()
def flush(self):
for stream in self.streams:stream.flush()
@staticmethod
@contextmanager
def redirect(log):
with redirect_stdout(Tee(sys.stdout,log)),redirect_stderr(Tee(sys.stderr,log)):yield
+22
View File
@@ -0,0 +1,22 @@
import torch
import torch.nn.functional as F
class LegacyLoss:
"""Keep the previous loss and efficient readout exactly for equivalence testing."""
def __init__(self,model,tokenizer,task):
from types import SimpleNamespace
self.model=model;self.args=SimpleNamespace(task=task.lower())
self.label_ids=[tokenizer.encode(w,add_special_tokens=False)[0] for w in (' terrible',' great')]
def __call__(self,inputs):
hidden=self.model.model(input_ids=inputs['input_ids'],attention_mask=inputs['attention_mask'],use_cache=False).last_hidden_state
if self.args.task=='sst2':
logits=self.model.lm_head(hidden[:,-1])[:,self.label_ids]
losses=F.cross_entropy(logits.float(),inputs['labels'],reduction='none')
else:
shifted=inputs['labels'][:,1:];valid=shifted!=-100
logits=self.model.lm_head(hidden[:,:-1][valid]).float()
token_loss=F.cross_entropy(logits,shifted[valid],reduction='none')
owner=torch.arange(len(hidden),device=hidden.device)[:,None].expand_as(valid)[valid]
losses=torch.zeros(len(hidden),device=hidden.device).scatter_add_(0,owner,token_loss)/valid.sum(1).clamp_min(1)
if not bool(torch.isfinite(losses).all()):raise FloatingPointError('Nonfinite loss')
return losses,logits
+78
View File
@@ -0,0 +1,78 @@
import numpy as np
import collections
import re
import string
from collections import Counter
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
return re.sub(r'\b(a|an|the)\b', ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
return ''.join(ch for ch in text if ch not in exclude)
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def calculate_metric(predictions, metric_name):
if metric_name == "accuracy":
if isinstance(predictions[0].correct_candidate, list):
return np.mean([pred.predicted_candidate in pred.correct_candidate for pred in predictions])
else:
return np.mean([pred.correct_candidate == pred.predicted_candidate for pred in predictions])
elif metric_name == "em":
# For question answering
return np.mean([any([normalize_answer(ans) == normalize_answer(pred.predicted_candidate) for ans in pred.correct_candidate]) for pred in predictions])
elif metric_name == "f1":
# For question answering
f1 = []
for pred in predictions:
all_f1s = []
if pred.correct_candidate[0] == "CANNOTANSWER" or pred.correct_candidate[0] == "no answer":
f1.append(int(normalize_answer(pred.correct_candidate[0]) == normalize_answer(pred.predicted_candidate)))
else:
for ans in pred.correct_candidate:
prediction_tokens = normalize_answer(pred.predicted_candidate).split()
ground_truth_tokens = normalize_answer(ans).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
all_f1s.append(0)
else:
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
all_f1s.append((2 * precision * recall) / (precision + recall))
f1.append(max(all_f1s))
return np.mean(f1)
def f1(pred, gold):
"""
This separate F1 function is used as non-differentiable metric for SQuAD
"""
if gold[0] == "CANNOTANSWER" or gold[0] == "no answer":
return int(normalize_answer(gold[0]) == normalize_answer(pred))
else:
all_f1s = []
for ans in gold:
prediction_tokens = normalize_answer(pred).split()
ground_truth_tokens = normalize_answer(ans).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
all_f1s.append(0)
else:
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
all_f1s.append((2 * precision * recall) / (precision + recall))
return np.max(all_f1s)
+26
View File
@@ -0,0 +1,26 @@
"""Diagnostics around the unchanged MeZO option-loss wrapper; its scalar loss is authoritative."""
import torch
import torch.nn.functional as F
class MeZOLoss:
def __init__(self,model):self.model=model;self.last_weight=None
def __call__(self,inputs):
output=self.model(**inputs,return_dict=True)
labels=inputs['input_ids'][:,1:].clone();labels[labels==self.model.config.pad_token_id]=-100
for index,length in enumerate(inputs['option_len']):
if int(length)<=0:raise ValueError('Empty MeZO option after encoding/truncation')
labels[index,:-int(length)]=-100
valid=labels!=-100
if 'num_options' in inputs:
options=int(inputs['num_options'][0])
if options!=2 or not bool((inputs['num_options']==2).all()):raise ValueError('Current node/diagnostic integration supports binary SST2 options only')
log_probs=output.logits[:,:-1].log_softmax(-1)
selected=log_probs.gather(-1,labels.masked_fill(~valid,0).unsqueeze(-1)).squeeze(-1)
scores=((selected*valid).sum(-1)/valid.sum(-1)).view(-1,2)
# Repeat per-example scores for the two candidate activation rows.
logits=scores.repeat_interleave(2,dim=0);self.last_weight=len(scores)
else:
logits=output.logits.new_empty((len(labels),0));self.last_weight=int(valid.sum())
# Preserve the author's scalar/token-weighted objective, rather than
# replacing it with a mean of per-example token losses.
return output.loss.expand(len(inputs['input_ids'])),logits
+258
View File
@@ -0,0 +1,258 @@
"""MeZO project structure with fix/adjust/node Trainer branches and explicit data protocols."""
import sys
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
sys.path.insert(0,str(ROOT/'src'))
if __package__ in (None,''):
sys.path.insert(0,str(ROOT))
from methods.large_models.run import main
if __name__=='__main__':main()
raise SystemExit
from dataclasses import dataclass,field,asdict
from datetime import datetime,timezone
import hashlib
import importlib.metadata
import json
from typing import Optional
import torch
from transformers import HfArgumentParser
from experiments_codebase.paths import paths,model_path,save
from ._upstream_run import Framework as MeZOFramework,OurArguments as MeZOArguments,set_seed
from .tasks import get_task
from .trainer import OurTrainer
from .data import HFDataset,LegacyCollator,legacy_rows,convert_samples
from .utils import DataCollatorWithPaddingAndNesting,forward_wrap_with_option_len
from .logging_utils import Tee
@dataclass
class OurArguments(MeZOArguments):
trainer: str='fix'
model_name: str='facebook/opt-1.3b'
data_protocol: str='mezo'
main_forward_budget: int=6000
num_train: int=1000
num_dev: int=500
num_eval: int=872
max_length: int=128
max_new_tokens: int=32
seed: int=2026110791
per_device_train_batch_size: int=16
per_device_eval_batch_size: int=16
calibration_samples: int=16
refresh_every: Optional[int]=None
node_queries: int=2
node_epsilon: float=1e-3
node_update: str='original'
basis_lr: float=1e-5
basis_radius: float=1e-3
history_beta: float=.9
zo_schedule: Optional[str]=None
decay_start: int=3000
lr_min: Optional[float]=None
eval_main_forwards: int=600
rank: int=1
q: int=1
save_final_checkpoint: bool=True
select_best_checkpoint: bool=True
preflight_only: bool=False
action: str='train'
checkpoint: Optional[str]=None
prompt: Optional[str]=None
dtype: str='float32'
resume_from_checkpoint: Optional[str]=None
no_auto_device: bool=True
optim: str='sgd'
weight_decay: float=0.
fp16: bool=False
bf16: Optional[bool]=False
remove_unused_columns: bool=False
dataloader_drop_last: Optional[bool]=None
dataloader_num_workers: int=0
report_to: list[str]=field(default_factory=list)
disable_tqdm: bool=True
ALIASES={'--method':'--trainer','--model':'--model_name','--task':'--task_name','--budget':'--main_forward_budget','--lr':'--learning_rate','--mu':'--zo_eps',
'--batch-size':'--per_device_train_batch_size','--eval-batch-size':'--per_device_eval_batch_size','--train-samples':'--num_train','--dev-samples':'--num_dev','--eval-samples':'--num_eval',
'--calibration-samples':'--calibration_samples','--max-length':'--max_length','--eval-every':'--eval_main_forwards','--refresh-every':'--refresh_every',
'--node-queries':'--node_queries','--node-epsilon':'--node_epsilon','--history-beta':'--history_beta','--schedule':'--zo_schedule',
'--decay-start':'--decay_start','--lr-min':'--lr_min','--max-new-tokens':'--max_new_tokens','--out':'--output_dir','--weight-decay':'--weight_decay','--data-protocol':'--data_protocol'}
def parse_args(argv=None,forced_method=None):
raw=list(sys.argv[1:] if argv is None else argv);normalized=[];i=0
while i<len(raw):
value=raw[i]
if value=='--no-save-checkpoint':normalized+=['--save_final_checkpoint','false']
elif value=='--preflight-only':normalized+=['--preflight_only','true']
elif value=='--device':
raise ValueError('Use HF --use_cpu for CPU diagnostics; the supported training configuration is one CUDA device')
else:
name,separator,parameter=value.partition('=');name=ALIASES.get(name,name)
if name=='--task_name':
if separator:value=name+'='+parameter.upper()
else:
normalized+=[name,raw[i+1].upper()];i+=2;continue
else:value=name+(separator+parameter if separator else '')
normalized.append(value)
i+=1
if forced_method:normalized+=['--trainer',forced_method]
if not any(v.split('=')[0]=='--output_dir' for v in normalized):
normalized+=['--output_dir',str(paths()['results']/('mezo_style_'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')))]
args=HfArgumentParser(OurArguments).parse_args_into_dataclasses(normalized)[0]
if args.trainer not in ('fix','adjust','node'):raise ValueError('Use --trainer fix, adjust or node')
if args.node_update not in ('original','local_curvature','history_free') or (args.trainer!='node' and args.node_update!='original'):
raise ValueError('Use --trainer node --node_update original, local_curvature or history_free')
if args.trainer=='node':
import math
if not math.isfinite(args.node_epsilon) or args.node_epsilon<=0:
raise ValueError('Node requires a positive finite epsilon')
if not all(math.isfinite(x) and x>0 for x in (args.basis_lr,args.basis_radius)):
raise ValueError('Basis learning rate and radius must be positive finite')
if not any(v.split('=')[0]=='--learning_rate' for v in normalized):args.learning_rate=1.5e-6 if args.trainer=='node' else 1e-6
if any(v.split('=')[0]=='--lr_scheduler_type' for v in normalized):
requested=args.lr_scheduler_type.value
if requested not in ('constant','cosine') or args.zo_schedule not in (None,requested):raise ValueError('Use one consistent constant/cosine schedule')
args.zo_schedule=requested
args.zo_schedule=args.zo_schedule or ('cosine' if args.trainer=='node' else 'constant')
from transformers.trainer_utils import SchedulerType
args.lr_scheduler_type=SchedulerType(args.zo_schedule)
args.lr_min=args.lr_min if args.lr_min is not None else args.learning_rate*.1
args.refresh_every=args.refresh_every or (128 if args.trainer=='node' else 256)
args.train_set_seed=args.seed if args.train_set_seed is None else args.train_set_seed
args.overwrite_output_dir=True
if args.data_protocol not in ('legacy','mezo') or args.task_name not in ('SST2','DROP'):raise ValueError('Unknown protocol or task')
if args.dataloader_drop_last is None:args.dataloader_drop_last=args.data_protocol=='legacy'
if args.action not in ('train','evaluate','generate') or args.zo_schedule not in ('constant','cosine'):raise ValueError('Unknown action or schedule')
counts=[args.num_train,args.num_dev,args.num_eval,args.per_device_train_batch_size,args.per_device_eval_batch_size,args.calibration_samples,args.refresh_every,args.eval_main_forwards,args.node_queries]
if min(counts)<=0 or args.num_train<args.per_device_train_batch_size or args.main_forward_budget<3 or args.learning_rate<=0 or args.zo_eps<=0:raise ValueError('Invalid sample counts, budget or learning rate')
if args.gradient_accumulation_steps!=1 or args.rank!=1 or args.q!=1 or args.weight_decay!=0 or args.dtype!='float32' or args.fp16 or args.bf16:raise ValueError('Audited variant: rank=q=1, FP32, no weight decay/gradient accumulation')
unsupported=[n for n in ('prefix_tuning','lora','head_tuning','linear_probing','non_diff','untie_emb','save_on_interrupt','gradient_checkpointing','load_float16','load_bfloat16','load_int8','fp16_full_eval','bf16_full_eval','load_best_model_at_end') if getattr(args,n,False)]
if unsupported or args.world_size!=1 or args.dataloader_num_workers!=0 or (args.data_protocol=='legacy' and not args.dataloader_drop_last) or args.remove_unused_columns:raise ValueError(f'Unsupported mode: {unsupported}; use the documented single-device deterministic configuration')
if str(args.optim) not in ('sgd','OptimizerNames.SGD') or args.resume_from_checkpoint:raise ValueError('This variant uses SGD and supports inference checkpoints, not training resume')
if not args.no_auto_device:raise ValueError('Use the default single-device loader (--no_auto_device true)')
if any(v.split('=')[0]=='--max_grad_norm' for v in normalized) and args.max_grad_norm!=0:raise ValueError('Gradient clipping is not part of the audited zeroth-order update')
args.max_grad_norm=0.
if args.num_train_sets is not None:raise ValueError('Run one training seed per output directory')
# MeZO SST2 uses two option likelihoods; DROP uses gold-answer teacher forcing.
args.train_as_classification=args.task_name=='SST2';args.only_train_option=True
if args.checkpoint:
if args.action=='train':raise ValueError('--checkpoint is for inference, not resume')
if not Path(args.checkpoint).is_dir():raise ValueError('New entry expects a merged HF model directory; old .pt checkpoints are unsupported by this entry')
args.model_name=args.checkpoint
return args
class Framework(MeZOFramework):
def load_model(self):
model,tokenizer=super().load_model()
model.to(self.args.device).eval();model.config.use_cache=False;tokenizer.padding_side='left'
if self.args.load_float16 or self.args.load_bfloat16 or self.args.load_int8:raise ValueError('Only FP32 is audited')
return model,tokenizer
def train(self,train_samples,eval_samples):
if self.args.data_protocol=='mezo':
# Reuse the actual author's training-data conversion, nested collator,
# option-loss wrapper and Trainer construction from Framework.train.
return super().train(train_samples,eval_samples)
groups=self.legacy_groups
self.trainer=OurTrainer(model=self.model,args=self.args,tokenizer=self.tokenizer,
train_dataset=HFDataset(groups['train']),eval_dataset=HFDataset(groups['development']),data_collator=LegacyCollator(self.tokenizer))
self.trainer.train()
@torch.no_grad()
def validation_loss(self,samples):
if self.args.data_protocol=='legacy':return self.trainer.evaluate_dataset(HFDataset(self.legacy_groups['validation']))
previous=self.model.forward
self.model.forward=forward_wrap_with_option_len.__get__(self.model,type(self.model))
try:return self.trainer.evaluate_dataset(HFDataset(convert_samples(self.task,samples,self.tokenizer,self.args)))
finally:self.model.forward=previous
def main(argv=None,forced_method=None):
args=parse_args(argv,forced_method);storage=paths()['results'].resolve();out=Path(args.output_dir).resolve()
if not out.is_relative_to(storage):raise ValueError(f'Output must be under {storage}')
out.mkdir(parents=True,exist_ok=False);args.output_dir=str(out)
identifier=args.model_name;args.model_name=str(model_path(identifier));set_seed(args.seed)
torch.set_num_threads(4);torch.backends.cuda.matmul.allow_tf32=False;torch.backends.cudnn.allow_tf32=False
save(out/'hyperparameters.json',json.loads(json.dumps(args.to_dict(),default=str)))
save(out/'environment.json',dict(python=sys.version,executable=sys.executable,versions={name:importlib.metadata.version(name) for name in ('torch','transformers','datasets','huggingface-hub','numpy')}))
save(out/'protocol.json',dict(data_protocol=args.data_protocol,model_identifier=identifier,entry='MeZO Framework + structured OurTrainer',
algorithm_variant='history_free_coverage_gradient_v1' if args.node_update=='history_free' else ('local_curvature_gradient_v1' if args.node_update=='local_curvature' else {'fix':'fix', 'adjust':'adjust_single_probe_v1', 'node':'node_unconditional_refresh_control_v1'}[args.trainer]),
coverage_objective='Current-batch ||G_l d_l||^2; shared Gaussian response, one joint node probe, all untied Linear bases' if args.node_update=='history_free' else None,
coverage_update_order='Old-basis SGD followed by normalize(d+rho*gradient); no EMA or gate' if args.node_update=='history_free' else None,
curvature_interpretation='Three-point local Hessian; no certified upper-bound guarantee' if args.node_update=='local_curvature' else None,
selection_sampling='Three independent training-subset draws; training retains HF RandomSampler' if args.node_update=='local_curvature' else None,
inherited_mezo_commit=json.loads((ROOT/'upstream.lock.json').read_text())['mezo']['commit'],
batch_order='HF RandomSampler (MeZO author default)' if args.data_protocol=='mezo' else 'Independent PCG sampler (legacy)',dataloader_drop_last=args.dataloader_drop_last,query_unit='One model forward on the collated batch; native SST2 has two candidate rows per example',
parameterization='direct_weights_inplace_v2', optimizer='SGD, no momentum, no clipping',checkpoint='Standard HF weights for inference; resume unsupported',
cache_reuse='Do not reuse results across protocol/data hashes'))
save(out/'checkpoint_protocol.json',dict(select_best=args.select_best_checkpoint,
criterion='minimum development loss at post-update evaluation points',
ties='retain earlier checkpoint', final_evaluation='reload development-best weights' if args.select_best_checkpoint else 'final iterate',
resume_supported=False))
files=list(Path(__file__).parent.glob('*.py'))
save(out/'source_manifest.json',{str(f.relative_to(ROOT)):hashlib.sha256(f.read_bytes()).hexdigest() for f in files})
print(f'Output: {out}',flush=True)
with (out/'run.log').open('w') as stream,Tee.redirect(stream):
framework=None
try:
task=get_task(args.task_name);framework=Framework(args,task)
if args.action=='generate':
if not args.prompt:raise ValueError('--prompt is required')
text=framework.forward(framework.tokenizer.encode(args.prompt),generation=True)
save(out/'generation.json',{'text':text});return
if args.data_protocol=='legacy':
groups=legacy_rows(args,framework.tokenizer);framework.legacy_groups=groups
for split,rows in groups.items():save(out/'data'/f'{split}.json',rows)
train=[task.samples['train'][r['source_index']] for r in groups['train']]
dev=[task.samples['train'][r['source_index']] for r in groups['development']]
valid=[task.samples['valid'][r['source_index']] for r in groups['validation']]
else:
sampled=task.sample_train_sets(num_train=args.num_train,num_dev=args.num_dev,num_eval=args.num_eval,seed=args.train_set_seed)[0]
train,dev=sampled[:-args.num_dev],sampled[-args.num_dev:]
valid=task.sample_subset(data_split='valid',seed=args.train_set_seed,num=args.num_eval)
for split,rows in [('train',train),('development',dev),('validation',valid)]:save(out/'data'/f'{split}.json',[asdict(r) for r in rows])
hashes={p.stem:hashlib.sha256(p.read_bytes()).hexdigest() for p in (out/'data').glob('*.json')}
save(out/'data_manifest.json',dict(protocol=args.data_protocol,sha256=hashes,counts={'train':len(train),'development':len(dev),'validation':len(valid)}))
if args.action=='train':
framework.train(train,dev)
if args.preflight_only:return
framework.trainer.progress('final_validation')
validation=framework.validation_loss(valid)
summary=json.loads((out/'summary.json').read_text());summary['validation']=validation;summary['counts']=framework.trainer.counts;save(out/'summary.json',summary)
# Refresh the ledger after final validation loss (evaluation only).
ledger=json.loads((out/'query_ledger.json').read_text());ledger['counts']=framework.trainer.counts;save(out/'query_ledger.json',ledger)
else:
# Standard merged HF checkpoint: evaluate without installing new bases.
from transformers import DataCollatorForTokenClassification
if args.data_protocol=='legacy':
training=HFDataset(groups['train']);development=HFDataset(groups['development']);collator=LegacyCollator(framework.tokenizer)
else:
training=HFDataset(convert_samples(task,train,framework.tokenizer,args));development=HFDataset(convert_samples(task,dev,framework.tokenizer,args))
collator=DataCollatorWithPaddingAndNesting(framework.tokenizer,pad_to_multiple_of=8) if args.train_as_classification else DataCollatorForTokenClassification(framework.tokenizer,pad_to_multiple_of=8)
framework.model.original_forward=framework.model.forward
framework.trainer=OurTrainer(model=framework.model,args=args,tokenizer=framework.tokenizer,train_dataset=training,eval_dataset=development,data_collator=collator)
validation=framework.validation_loss(valid);save(out/'evaluation.json',validation)
if not args.no_eval:
if args.data_protocol=='mezo':
# The original author's prediction templates/metric implementation.
calls=[0]
framework.trainer.progress('prediction_evaluation')
def count_forward(*unused):
calls[0]+=1;framework.trainer.counts['evaluation']+=1
if calls[0]%20==0:framework.trainer.progress('prediction_evaluation')
handle=framework.model.register_forward_pre_hook(count_forward)
try:metrics=framework.evaluate([],valid)
finally:handle.remove()
save(out/'result.json',{'metrics':metrics,'metric_implementation':'MeZO Framework.evaluate / metrics.py','prediction_model_forwards':calls[0]})
if (out/'query_ledger.json').exists():
ledger=json.loads((out/'query_ledger.json').read_text());ledger['counts']=framework.trainer.counts;ledger['prediction_forwards']=calls[0];save(out/'query_ledger.json',ledger)
else:save(out/'result.json',{'metrics':validation,'metric_implementation':'Preserved legacy batched readout','prediction_model_forwards':0})
if hasattr(framework,'trainer'):
if (out/'summary.json').exists():
summary=json.loads((out/'summary.json').read_text())
summary['counts']=framework.trainer.counts;save(out/'summary.json',summary)
framework.trainer.progress('complete')
except BaseException:
import traceback
save(out/'failure.json',{'traceback':traceback.format_exc()});raise
if __name__=='__main__':main()
+425
View File
@@ -0,0 +1,425 @@
from .templates import *
from .utils import temp_seed
import json
import os
from .assets import load_dataset
from dataclasses import dataclass
from typing import List, Union
import string
import random
import datasets
import sys
import numpy as np
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def get_task(task_name):
aa = task_name.split("__")
if len(aa) == 2:
task_group, subtask = aa
else:
task_group = aa[0]
subtask = None
class_ = getattr(sys.modules[__name__], f"{task_group}Dataset")
instance = class_(subtask)
return instance
@dataclass
class Sample:
id: int = None
data: dict = None
correct_candidate: Union[str, List[str]] = None
candidates: List[str] = None
class Dataset:
mixed_set = False
train_sep = "\n\n"
generation = False # whether this is a generation task
def __init__(self, subtask=None, **kwargs) -> None:
self.subtask = subtask
def get_task_name(self):
return self.subtask
def load_dataset():
raise NotImplementedError
def get_template(self, template_version=0):
templates = {0: Template}
return templates[template_version]
def build_sample(self, example):
return
def sample_train_sets(self, num_train=32, num_dev=None, num_eval=None, num_train_sets=None, seed=None):
if seed is not None:
# one train/demo set using the designated seed
seeds = [seed]
elif num_train_sets is not None:
# num_train_sets train/demo sets
seeds = list(range(num_train_sets))
else:
# one train/demo set per evaluation sample
assert num_dev is None # not supported
len_valid_samples = len(self.samples["valid"]) if num_eval is None else num_eval
with temp_seed(0):
seeds = np.random.randint(0, 10000, len_valid_samples)
train_samples = []
for i, set_seed in enumerate(seeds):
if self.mixed_set:
raise NotImplementedError
train_samples.append(self.sample_subset(data_split="valid", seed=set_seed, num=num_train, exclude=i))
else:
if num_dev is not None:
train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train+num_dev)) # dev set is included at the end of train set
if num_train + num_dev > len(self.samples["train"]):
logger.warn("num_train + num_dev > available training examples")
else:
train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train))
if num_dev is not None:
logger.info(f"Sample train set {len(train_samples[-1])}/{len(self.samples['train'])}")
logger.info(f"... including dev set {num_dev} samples")
return train_samples
def sample_subset(self, data_split="train", seed=0, num=100, exclude=None):
with temp_seed(seed):
samples = self.samples[data_split]
lens = len(samples)
index = np.random.permutation(lens).tolist()[:num if exclude is None else num+1]
if exclude is not None and exclude in index:
index.remove(exclude)
else:
index = index[:num]
return [samples[i] for i in index]
@property
def valid_samples(self):
return self.samples["valid"]
class SST2Dataset(Dataset):
train_sep = "\n\n"
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset('glue', 'sst2')
train_d = d["train"]
validation_d = d["validation"]
train_samples = [self.build_sample(example) for example in train_d]
valid_samples = [self.build_sample(example) for example in validation_d]
self.samples = {"train": train_samples, "valid": valid_samples}
# for generative tasks, candidates are []
def build_sample(self, example):
label = int(example["label"])
return Sample(id=example["idx"], data=example, correct_candidate=label, candidates=[0, 1])
def get_template(self, template_version=0):
return {0: SST2Template}[template_version]()
class CopaDataset(Dataset):
train_sep = "\n\n"
mixed_set = False
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
train_examples = load_dataset('super_glue', "copa")["train"]
valid_examples = load_dataset('super_glue', "copa")["validation"]
train_samples = [self.build_sample(example) for example in train_examples]
valid_samples = [self.build_sample(example) for example in valid_examples]
self.samples = {"train": train_samples, "valid": valid_samples}
# for generative tasks, candidates are []
def build_sample(self, example):
sample = \
Sample(
id=example["idx"],
data=example,
candidates=[example["choice1"], example["choice2"]],
correct_candidate=example[f"choice{example['label'] + 1}"],
)
return sample
def get_template(self, template_version=0):
return {0: CopaTemplate}[template_version]()
class BoolQDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("boolq")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=["Yes", "No"],
correct_candidate="Yes" if example["answer"] else "No",
)
return sample
def get_template(self, template_version=2):
return {0: BoolQTemplate, 1: BoolQTemplateV2, 2: BoolQTemplateV3}[template_version]()
class MultiRCDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "multirc")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: MultiRCTemplate}[template_version]()
class CBDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "cb")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1, 2],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: CBTemplate}[template_version]()
class WICDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "wic")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: WICTemplate}[template_version]()
class WSCDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "wsc.fixed")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: WSCTemplate}[template_version]()
class ReCoRDDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "record")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=example['entities'],
correct_candidate=example['answers']
)
return sample
def get_template(self, template_version=0):
return {0: ReCoRDTemplateGPT3}[template_version]()
class RTEDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "rte")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: RTETemplate}[template_version]()
class SQuADDataset(Dataset):
metric_name = "f1"
generation = True
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset()
def load_dataset(self):
dataset = load_dataset("squad")
train_examples = dataset["train"]
valid_examples = dataset["validation"]
train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)]
valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)]
self.samples = {"train": train_samples, "valid": valid_samples}
# for generative tasks, candidates are []
def build_sample(self, example, idx):
answers = example['answers']['text']
assert len(answers) > 0
return Sample(
id=idx,
data={
"title": example['title'],
"context": example['context'],
"question": example['question'],
"answers": answers
},
candidates=None,
correct_candidate=answers
)
def get_template(self, template_version=0):
return {0: SQuADv2Template}[template_version]()
class DROPDataset(Dataset):
metric_name = "f1"
generation = True
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset()
def load_dataset(self):
dataset = load_dataset("drop")
train_examples = dataset["train"]
valid_examples = dataset["validation"]
train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)]
valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)]
self.samples = {"train": train_samples, "valid": valid_samples}
# for generative tasks, candidates are []
def build_sample(self, example, idx):
answers = example['answers_spans']['spans']
assert len(answers) > 0
return Sample(
id=idx,
data={
"context": example['passage'],
"question": example['question'],
"answers": answers
},
candidates=None,
correct_candidate=answers
)
def get_template(self, template_version=0):
return {0: DROPTemplate}[template_version]()
+379
View File
@@ -0,0 +1,379 @@
class Template:
def encode(self, sample):
"""
Return prompted version of the example (without the answer/candidate)
"""
raise NotImplementedError
def verbalize(self, sample, candidate):
"""
Return the prompted version of the example (with the answer/candidate)
"""
return candidate
def encode_sfc(self, sample):
"""
Same as encode, but for SFC (calibration) -- this usually means the input is not included
"""
return "<mask>"
def verbalize_sfc(self, sample, candidate):
"""
Same as verbalize, but for SFC (calibration) -- this usually means the input is not included
"""
return candidate
class SST2Template(Template):
verbalizer = {0: "terrible", 1: "great"}
def encode(self, sample):
text = sample.data["sentence"].strip()
return f"{text} It was"
def verbalize(self, sample, candidate):
text = sample.data["sentence"].strip()
return f"{text} It was {self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f" It was"
def verbalize_sfc(self, sample, candidate):
return f" It was {self.verbalizer[candidate]}"
class CopaTemplate(Template):
capitalization: str = "correct"
effect_conj: str = " so "
cause_conj: str = " because "
def get_conjucture(self, sample):
if sample.data["question"] == "effect":
conjunction = self.effect_conj
elif sample.data["question"] == "cause":
conjunction = self.cause_conj
else:
raise NotImplementedError
return conjunction
def get_prompt(self, sample):
premise = sample.data["premise"].rstrip()
if premise.endswith("."): # TODO Add other scripts with different punctuation
premise = premise[:-1]
conjunction = self.get_conjucture(sample)
prompt = premise + conjunction
if self.capitalization == "upper":
prompt = prompt.upper()
elif self.capitalization == "lower":
prompt = prompt.lower()
return prompt
def encode(self, sample):
prompt = self.get_prompt(sample)
return prompt
def capitalize(self, c):
if self.capitalization == "correct":
words = c.split(" ")
if words[0] != "I":
words[0] = words[0].lower()
return " ".join(words)
elif self.capitalization == "bug":
return c
elif self.capitalization == "upper":
return c.upper()
elif self.capitalization == "lower":
return c.lower()
else:
raise NotImplementedError
def verbalize(self, sample, candidate):
prompt = self.get_prompt(sample)
return prompt + self.capitalize(candidate)
def encode_sfc(self, sample):
conjunction = self.get_conjucture(sample)
return conjunction.strip()
def verbalize_sfc(self, sample, candidate):
conjunction = self.get_conjucture(sample)
sfc_prompt = conjunction.strip() + " " + self.capitalize(candidate)
return sfc_prompt
class BoolQTemplate(Template):
def encode(self, sample):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}"
def verbalize(self, sample, candidate):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question} {candidate}"
def encode_sfc(self, sample):
return ""
def verbalize_sfc(self, sample, candidate):
return candidate
class BoolQTemplateV2(Template):
def encode(self, sample):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}\\n\\n"
def verbalize(self, sample, candidate):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}\\n\\n{candidate}"
def encode_sfc(self, sample):
return ""
def verbalize_sfc(self, sample, candidate):
return candidate
class BoolQTemplateV3(Template):
def encode(self, sample):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}\n"
def verbalize(self, sample, candidate):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}\n{candidate}"
def encode_sfc(self, sample):
return ""
def verbalize_sfc(self, sample, candidate):
return candidate
class MultiRCTemplate(Template):
# From PromptSource 1
verbalizer = {0: "No", 1: "Yes"}
def encode(self, sample):
paragraph = sample.data["paragraph"]
question = sample.data["question"]
answer = sample.data["answer"]
return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n"
def verbalize(self, sample, candidate):
paragraph = sample.data["paragraph"]
question = sample.data["question"]
answer = sample.data["answer"]
return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class CBTemplate(Template):
# From PromptSource 1
verbalizer = {0: "Yes", 1: "No", 2: "Maybe"}
def encode(self, sample):
premise = sample.data["premise"]
hypothesis = sample.data["hypothesis"]
return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n"
def verbalize(self, sample, candidate):
premise = sample.data["premise"]
hypothesis = sample.data["hypothesis"]
return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class WICTemplate(Template):
# From PromptSource 1
verbalizer = {0: "No", 1: "Yes"}
def encode(self, sample):
sent1 = sample.data["sentence1"]
sent2 = sample.data["sentence2"]
word = sample.data["word"]
return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n"
def verbalize(self, sample, candidate):
sent1 = sample.data["sentence1"]
sent2 = sample.data["sentence2"]
word = sample.data["word"]
return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class WSCTemplate(Template):
# From PromptSource 1
verbalizer = {0: "No", 1: "Yes"}
def encode(self, sample):
text = sample.data['text']
span1 = sample.data['span1_text']
span2 = sample.data['span2_text']
return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n"
def verbalize(self, sample, candidate):
text = sample.data['text']
span1 = sample.data['span1_text']
span2 = sample.data['span2_text']
return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class ReCoRDTemplate(Template):
# From PromptSource 1 but modified
def encode(self, sample):
passage = sample.data['passage']
query = sample.data['query']
return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer:"
def verbalize(self, sample, candidate):
passage = sample.data['passage']
query = sample.data['query']
return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}"
def encode_sfc(self, sample):
return f"Answer:"
def verbalize_sfc(self, sample, candidate):
return f"Answer: {candidate}"
class ReCoRDTemplateGPT3(Template):
# From PromptSource 1 but modified
def encode(self, sample):
passage = sample.data['passage'].replace("@highlight\n", "- ")
return f"{passage}\n-"
def verbalize(self, sample, candidate):
passage = sample.data['passage'].replace("@highlight\n", "- ")
query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate)
return f"{passage}\n- {query}"
# passage = sample.data['passage']
# query = sample.data['query']
# return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}"
def encode_sfc(self, sample):
return f"-"
def verbalize_sfc(self, sample, candidate):
query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate)
return f"- {query}"
class RTETemplate(Template):
# From PromptSource 1
verbalizer={0: "Yes", 1: "No"}
def encode(self, sample):
premise = sample.data['premise']
hypothesis = sample.data['hypothesis']
return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n"
def verbalize(self, sample, candidate):
premise = sample.data['premise']
hypothesis = sample.data['hypothesis']
return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class SQuADv2Template(Template):
def encode(self, sample):
question = sample.data['question'].strip()
title = sample.data['title']
context = sample.data['context']
answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one
return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer:"
def verbalize(self, sample, candidate):
question = sample.data['question'].strip()
title = sample.data['title']
context = sample.data['context']
answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one
return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer: {answer}\n"
def encode_sfc(self, sample):
raise NotImplementedError
def verbalize_sfc(self, sample, candidate):
raise NotImplementedError
class DROPTemplate(Template):
def encode(self, sample):
question = sample.data['question'].strip()
# title = sample.data['title']
context = sample.data['context']
answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one
return f"Passage: {context}\nQuestion: {question}\nAnswer:"
def verbalize(self, sample, candidate):
question = sample.data['question'].strip()
# title = sample.data['title']
context = sample.data['context']
answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one
return f"Passage: {context}\nQuestion: {question}\nAnswer: {answer}\n"
def encode_sfc(self, sample):
raise NotImplementedError
def verbalize_sfc(self, sample, candidate):
raise NotImplementedError
+701
View File
@@ -0,0 +1,701 @@
"""MeZO-style OurTrainer on the supported HF Trainer API, with structured ZO branches."""
from datetime import datetime,timezone
import math
import os
from pathlib import Path
import time
import numpy as np
import torch
from transformers import Trainer
from transformers.trainer_utils import TrainOutput
from experiments_codebase.paths import save,append
from .data import ProtocolSampler,seed_for
from .losses import LegacyLoss
from .native_losses import MeZOLoss
from .logging_utils import figures,memory
def top_basis(x, rank=1):
"""从[token数, 输入维度]的激活提取主方向,返回[输入维度, rank]。
这里按未中心化激活做SVD,不减去均值;当前训练入口只支持rank=1。
"""
x = x.float()
if x.shape[0] < x.shape[1]:
values, vectors = torch.linalg.eigh(x @ x.T)
ids = torch.arange(len(values) - 1, len(values) - rank - 1, -1, device=x.device)
if values[ids[-1]] <= values[-1] * 1e-08:
raise ValueError('Insufficient activation rank')
d = x.T @ (vectors[:, ids] / values[ids].sqrt())
return torch.linalg.qr(d, mode='reduced').Q.contiguous()
return torch.linalg.svd(x, full_matrices=False).Vh[:rank].T.contiguous()
def curvature_descent_reference(g, h, p, lr, n=1, quadratic_mu=0.):
"""Small-matrix numerical reference, not a model-training estimator.
Implements Proposition 2.1 with supplied g and effective upper bound h.
Nonzero quadratic_mu is exact only for a quadratic with Hessian equal to h.
Returns the value and its Euclidean derivative with respect to p.
"""
if n < 1 or int(n) != n or lr <= 0 or quadratic_mu < 0:
raise ValueError('Invalid reference parameters')
a = torch.outer(g, g)
pg = p @ g
s = g @ pg
t = torch.trace(p @ h)
alpha, beta = lr * (1 + 1/n) / 2, lr / (2*n)
value = s - alpha * (pg @ h @ pg) - beta * s * t
gradient = a - alpha * (h @ p @ a + a @ p @ h) - beta * (t*a + s*h)
if quadratic_mu:
ph = p @ h
t2 = torch.trace(ph @ ph)
t3 = torch.trace(ph @ ph @ ph)
factor = lr * quadratic_mu**2 / (8*n)
value = value - factor * (t**3 + 6*t*t2 + 8*t3)
gradient = gradient - factor * ((3*t**2 + 6*t2)*h
+ 12*t*(h @ p @ h) + 24*(h @ p @ h @ p @ h))
return value, gradient
def curvature_input_gradient_reference(projection_gradient, d, output_size):
"""Contract one Linear block of grad_P for P=I_out kron dd.T; small tests only."""
k = d.numel()
blocks = projection_gradient.reshape(output_size, k, output_size, k)
c = sum(blocks[a, :, a, :] for a in range(output_size))
gradient = 2 * c @ d
return gradient - d * (d * gradient).sum()
class OurTrainer(Trainer):
def __init__(self,*args,tokenizer=None,**kwargs):
if tokenizer is not None:kwargs['processing_class']=tokenizer
super().__init__(*args,**kwargs)
self.tokenizer_for_zo=self.processing_class
self.loss_backend=LegacyLoss(self.model,self.processing_class,self.args.task_name) if self.args.data_protocol=='legacy' else MeZOLoss(self.model)
self.init_zo()
self._last_outputs=None;self._estimate=None;self.current_lr=self.args.learning_rate
self.curve=[];self.latest={};self.started=time.monotonic()
def _get_train_sampler(self,train_dataset=None):
if self.args.data_protocol=='mezo':return super()._get_train_sampler(train_dataset)
return ProtocolSampler(self.train_dataset if train_dataset is None else train_dataset,self.args.seed)
def compute_loss(self,model,inputs,return_outputs=False,num_items_in_batch=None):
self._last_outputs=self.loss_backend(inputs)
loss=self._last_outputs[0].mean()
return (loss,{'loss':loss,'logits':self._last_outputs[1]}) if return_outputs else loss
# This function is copied verbatim from pinned MeZO OurTrainer. See MEZO_REUSE.json.
def zo_forward(self, model, inputs):
"""
Get (no gradient) loss from the model. Dropout is turned off too.
"""
model.eval()
if self.args.non_diff:
# Non-differentiable objective (may require autoregressive generation)
return self.zo_forward_nondiff(model, inputs)
with torch.inference_mode():
inputs = self._prepare_inputs(inputs)
with self.compute_loss_context_manager():
loss = self.compute_loss(model, inputs)
if self.args.n_gpu > 1:
# Warning: this is copied from the original Huggingface Trainer. Untested.
loss = loss.mean() # mean() to average on multi-gpu parallel training
return loss.detach()
def _forward_outputs(self,inputs):
self.zo_forward(self.model,inputs)
return self._last_outputs
def init_zo(self):
"""只保存模型参数、各层输入基和node历史;不创建B、C或常驻hook。"""
self.named_parameters = list(self.model.named_parameters()) # tied权重只出现一次。
self.parameter_map = dict(self.named_parameters)
self.parameters = list(self.parameter_map.values())
self.linear_map = {
name+'.weight': module for name, module in self.model.named_modules()
if isinstance(module, torch.nn.Linear) and name+'.weight' in self.parameter_map
}
self.basis = {}
self.history = {}
self.counts = dict(training=0, calibration=0, evaluation=0, diagnostic=0)
def call(self, inputs, category='training'):
self.counts[category] += 1
loss, logits = self._forward_outputs(inputs)
if not bool(torch.isfinite(loss).all()):
raise FloatingPointError('Nonfinite loss')
return loss, logits
def collect_basis(self, inputs, category='training'):
"""一次前向读取各Linear的有效token输入,求未中心化激活的首个右奇异向量。"""
mask = inputs['attention_mask'].bool().reshape(-1)
bases, handles = {}, []
for name, module in self.linear_map.items():
def capture(module, args, name=name):
x = args[0].reshape(-1, args[0].shape[-1])[mask]
d = top_basis(x).to(dtype=self.parameter_map[name].dtype)
if name in self.basis and float((d.T @ self.basis[name]).sum()) < 0:
d = -d
bases[name] = d
handles.append(module.register_forward_pre_hook(capture))
try:
self.call(inputs, category)
finally:
for handle in handles:
handle.remove()
if len(bases) != len(self.linear_map):
raise RuntimeError('Not every linear layer executed')
return bases
def configure_basis(self, inputs):
self.basis = self.collect_basis(inputs, 'calibration')
self.model.requires_grad_(False)
def directions(self, seed):
"""按种子逐参数重建方向;不保存全模型噪声。Linear方向为z @ D.T。"""
generator = torch.Generator(device=self.args.device).manual_seed(seed)
for name, p in self.named_parameters:
z = torch.randn((p.shape[0], 1) if name in self.basis else p.shape,
device=p.device, dtype=p.dtype, generator=generator)
yield name, p, z
def shifted(self, inputs, bases, seed, scale, response=None):
"""原地加扰动查询,再按同一种子减回;无权重备份,FP32恢复允许舍入误差。"""
applied = 0
try:
for name, p, z in self.directions(seed):
direction = z if response is None else z * response
if name in bases:
direction = direction @ bases[name].T
p.add_(direction, alpha=scale)
applied += 1
return self.call(inputs)[0].detach().clone()
finally:
# 前向异常也减回;扰动中途失败时,只恢复已经加过扰动的参数。
for index, (name, p, z) in enumerate(self.directions(seed)):
if index >= applied:
break
direction = z if response is None else z * response
if name in bases:
direction = direction @ bases[name].T
p.add_(direction, alpha=-scale)
def zo_step(self, model, inputs, seed):
clean = self.call(inputs)[0]
plus = self.shifted(inputs, self.basis, seed, self.args.zo_eps)
slope = float((plus - clean).double().mean()) / self.args.zo_eps
if not math.isfinite(slope):
raise FloatingPointError('Nonfinite ZO response')
self.projected_grad = slope
self._estimate = dict(seed=seed, clean=clean, slope=slope)
return clean.mean()
@torch.no_grad()
def coverage_gradient_probe(self, inputs, seed, node_seed, targets):
"""Two ordinary ZO queries plus one joint node query.
At fixed weights/bases, estimate 2 (I-dd.T) G.T G d without history.
See HISTORY_FREE_COVERAGE.md for the linear-response proof and bias.
Clean hooks retain only X.T @ signs; perturbed downstream inputs must
not replace these clean sketches. Only selected output-sized Gaussian
vectors are retained, never full parameter noise or activations.
This helper does not select/install bases; coverage_step owns the update.
The pending SGD estimate belongs to the OLD bases: consume it with
zo_update before installing any candidate for the next iteration.
"""
if getattr(self, '_estimate', None) is not None:
raise RuntimeError('Consume the pending weight update before probing')
targets = list(targets)
if not targets or len(set(targets)) != len(targets):
raise ValueError('Coverage targets must be nonempty and unique')
if any(n not in self.basis or n not in self.linear_map for n in targets):
raise ValueError('Coverage targets must be initialized Linear weights')
mu, epsilon = self.args.zo_eps, self.args.node_epsilon
if not all(math.isfinite(x) and x > 0 for x in (mu, epsilon)):
raise ValueError('Coverage perturbation scales must be positive and finite')
aliases = list(self.model.named_parameters(remove_duplicate=False))
for n in targets:
if sum(p is self.parameter_map[n] for _, p in aliases) != 1:
raise ValueError('Coverage probes require untied target weights')
# Reuse exactly the Gaussian coefficients of the ordinary weight query.
noises = {n: z for n, _, z in self.directions(seed) if n in targets}
sketches = {}
shapes = {}
before = self.used()
def query(inject):
handles, seen = [], set()
def hook_for(n, index):
def hook(module, args, output):
if n in seen:
raise ValueError('Coverage target Linear must execute once per forward')
seen.add(n)
x = args[0]
if inject and tuple(x.shape) != shapes[n]:
raise ValueError('Coverage target shape changed across queries')
gen = torch.Generator(device=x.device).manual_seed(seed_for(node_seed, index))
signs = (2*torch.randint(0, 2, x.shape[:-1], device=x.device,
generator=gen)-1).to(x.dtype)
if inject:
return output + epsilon*signs[..., None]*noises[n].flatten()
shapes[n] = tuple(x.shape)
# The scalar loss already contains its batch/token reduction.
# Summation here is essential: another mean changes the gradient.
sketches[n] = x.reshape(-1, x.shape[-1]).T @ signs.reshape(-1, 1)
return hook
try:
for index, n in enumerate(targets):
handles.append(self.linear_map[n].register_forward_hook(hook_for(n, index)))
loss = self.call(inputs)[0]
if seen != set(targets):
raise ValueError('Every coverage target must execute in each forward')
return loss
finally:
for handle in handles:
handle.remove()
clean = query(False)
plus = self.shifted(inputs, self.basis, seed, mu)
slope = float((plus-clean).double().mean())/mu # Same arithmetic as zo_step.
node_loss = query(True)
node_slope = float((node_loss-clean).double().mean())/epsilon
if not all(math.isfinite(x) for x in (slope, node_slope)):
raise FloatingPointError('Nonfinite coverage response')
gradients = {}
for n in targets:
d, v = self.basis[n], sketches[n]
gradients[n] = 2*slope*node_slope*(v-d*(d*v).sum())
if not bool(torch.isfinite(gradients[n]).all()):
raise FloatingPointError('Nonfinite coverage gradient')
self._estimate = dict(seed=seed, clean=clean, slope=slope)
return dict(variant='history_free_coverage_probe_v1', gradients=gradients,
response=slope, node_response=node_slope, cost=self.used()-before)
@torch.no_grad()
def coverage_step(self, inputs, seed):
"""Current-batch coverage gradient; old-basis SGD, then retract new bases."""
step, args = self.state.global_step, self.args
if step == 0 or step % args.refresh_every or self.used()+3 > args.main_forward_budget:
return self.fix_step(inputs, seed)
before = self.used()
node_seed = seed_for(args.seed, 1801, step)
probe = self.coverage_gradient_probe(inputs, seed, node_seed, list(self.basis))
new, layers = {}, {}
for n, gradient in probe['gradients'].items():
d = self.basis[n]
candidate = d+args.basis_lr*gradient
norm = float(candidate.norm())
if not math.isfinite(norm) or norm == 0:
raise FloatingPointError('Nonfinite coverage basis retraction')
new[n] = candidate/norm
layers[n] = dict(gradient_norm=float(gradient.norm()),
overlap=float((d*new[n]).sum().square()))
# The saved response belongs to the old direction. Install only after SGD.
result = self.zo_update(self.model)
self.basis.update(new)
event = dict(step=step, variant='history_free_coverage_gradient_v1',
seed=seed, node_seed=node_seed, response=probe['response'],
node_response=probe['node_response'], basis_lr=args.basis_lr,
layers=layers, cost=self.used()-before-2, total_step_cost=self.used()-before,
main_forwards=self.used(), basis_installation='after_old_basis_sgd')
return result, event
def zo_update(self, model):
estimate = self._estimate
lr = self.current_lr
self._estimate = None
slope = estimate['slope']
square = 0
for n, p, z in self.directions(estimate['seed']):
g = z.mul_(slope)
square += float(g.float().square().sum()) * lr ** 2
# Linear: g is [dout, 1]; lift it into the full weight matrix.
delta = g @ self.basis[n].T if n in self.basis else g
p.add_(delta, alpha=-lr)
if n in self.history:
self.history[n].mul_(self.args.history_beta).add_(g, alpha=1 - self.args.history_beta)
return dict(batch_loss=float(estimate['clean'].mean()), response=slope, update_norm=math.sqrt(square), learning_rate=lr)
def fix_step(self, inputs, seed):
"""The basis is initialized once; every step is two forwards and SGD."""
before = self.used()
self.zo_step(self.model, inputs, seed)
result = self.zo_update(self.model)
assert self.used() - before == 2
return result, None
def adjust_step(self, inputs, seed):
"""Every r updates, compare one old/new virtual SGD step."""
args = self.args
step = self.state.global_step
event = None
due = step > 0 and step % args.refresh_every == 0
if due and self.used() + 6 + 2 <= args.main_forward_budget:
before = self.used()
new = self.collect_basis(self.probe_batch())
trial = self.adjust_probe(self.probe_batch(), self.probe_batch(), new,
seed_for(args.seed, 91, step), self.current_lr)
accept = trial['gain'] > 0
if accept:
self.basis.update(new)
event = dict(step=step, variant='adjust_single_probe_v1', trial=trial,
accepted=bool(accept), main_forwards=self.used(), cost=self.used()-before)
result, _ = self.fix_step(inputs, seed)
return result, event
def node_step(self, inputs, seed):
"""Control: refresh every r updates, without comparing old/new bases."""
args = self.args
step = self.state.global_step
cost = 1 + len(self.history) * args.node_queries
due = step > 0 and step % args.refresh_every == 0
if not due or self.used() + cost + 2 > args.main_forward_budget:
return self.fix_step(inputs, seed)
before = self.used()
new, metrics = self.node_proposal(self.probe_batch(), seed_for(args.seed, 705, step))
self.basis.update(new)
for name in new:
self.history[name].zero_()
event = dict(step=step, variant='node_unconditional_refresh_control_v1', layers=metrics,
learning_rate=self.current_lr, accepted=bool(new),
main_forwards=self.used(), cost=self.used()-before)
return self.fix_step(inputs, seed)[0], event
def adjust_probe(self, inputs, reference, new, seed, lr):
clean = self.call(inputs)[0]
a0 = float((self.shifted(inputs, self.basis, seed, self.args.zo_eps) - clean).double().mean()) / self.args.zo_eps
a1 = float((self.shifted(inputs, new, seed, self.args.zo_eps) - clean).double().mean()) / self.args.zo_eps
l0 = self.shifted(reference, self.basis, seed, -lr, response=a0)
l1 = self.shifted(reference, new, seed, -lr, response=a1)
return dict(gain=float((l0 - l1).double().mean()), old_loss=float(l0.mean()), new_loss=float(l1.mean()))
@torch.no_grad()
def curvature_refresh(self, batches, seed, tangent_seed, *, certified_smoothness=None,
basis_lr, basis_radius):
"""Plan section 6: full n=1 anisotropic objective, 13 main forwards.
Caller supplies independent A/B/C batches and a proven global L for F.
Numeric positivity below does not certify L. This conditional API is not
With certified_smoothness=None, explicitly use the user-authorized local
Hessian engineering variant; no upper-bound guarantee is claimed.
"""
mu, lr = self.args.zo_eps, self.current_lr
values = (basis_lr, basis_radius, mu, lr)
if certified_smoothness is not None:
values += (certified_smoothness,)
if not all(math.isfinite(x) and x > 0 for x in values):
raise ValueError('Curvature selection requires positive finite L, rho, delta, mu and eta')
if len(batches) != 3 or not self.basis:
raise ValueError('Curvature selection requires three independent batches and initialized bases')
before = self.used()
generator = torch.Generator(device=self.args.device).manual_seed(tangent_seed)
tangents, plus, minus = {}, {}, {}
for name, d in self.basis.items():
v = torch.randn(d.shape, device=d.device, dtype=d.dtype, generator=generator)
v -= d * (d * v).sum() # Tangent Gaussian; do not normalize v.
tangents[name] = v
plus[name] = torch.nn.functional.normalize(d + basis_radius*v, dim=0)
minus[name] = torch.nn.functional.normalize(d - basis_radius*v, dim=0)
# Stream the shared latent noise. Unit bases imply ||U z||^2=||z||^2.
norm_square = sum(float(z.double().square().sum()) for _, _, z in self.directions(seed))
clean_c = self.call(batches[2])[0].detach().clone().double().mean()
scores, observations = [], []
for bases in (plus, minus):
responses = []
for batch in batches[:2]:
fp = self.shifted(batch, bases, seed, mu).double().mean()
fm = self.shifted(batch, bases, seed, -mu).double().mean()
responses.append(float(fp-fm)/(2*mu))
fp = self.shifted(batches[2], bases, seed, mu).double().mean()
fm = self.shifted(batches[2], bases, seed, -mu).double().mean()
curvature = float(fp-2*clean_c+fm)/mu**2
upper_curvature = curvature + (0. if certified_smoothness is None else 2*certified_smoothness*norm_square)
score = responses[0]*responses[1]*(1-lr*upper_curvature/2)
scores.append(score)
observations.append(dict(responses=responses, curvature=curvature,
upper_curvature=upper_curvature, score=score))
q = (scores[0]-scores[1])/(2*basis_radius)
if not all(math.isfinite(x) for x in (*scores, q)):
raise FloatingPointError('Nonfinite curvature basis score/gradient')
updated, overlaps = {}, {}
gradient_square = 0.
for name, d in self.basis.items():
gradient = q*tangents[name] # Keep magnitude; no sign or clipping.
candidate = d + basis_lr*gradient
norm = float(candidate.double().norm())
if not math.isfinite(norm) or norm == 0:
raise FloatingPointError('Nonfinite curvature basis update')
updated[name] = candidate/norm
gradient_square += float(gradient.double().square().sum())
overlaps[name] = float((d.double()*updated[name].double()).sum().square())
assert self.used()-before == 13
self.basis.update(updated)
return dict(variant='local_curvature_gradient_v1' if certified_smoothness is None else 'curvature_descent_cross_batch_v1', cost=self.used()-before,
curvature_quantity='local_hessian' if certified_smoothness is None else 'certified_quadratic_upper_bound',
main_forwards=self.used(), seed=seed, tangent_seed=tangent_seed,
certified_smoothness=certified_smoothness, basis_lr=basis_lr,
basis_radius=basis_radius, weight_radius=mu, learning_rate=lr,
probes=observations, score_difference=scores[0]-scores[1],
difference_quotient=q, gradient_norm=math.sqrt(gradient_square),
direction_norm_square=norm_square, overlaps=overlaps)
@torch.no_grad()
def curvature_step(self, inputs, seed, *, selection_batches, certified_smoothness=None,
basis_lr, basis_radius):
"""Conditional full step; inputs/seed must be fresh versus selection.
selection_batches is a callable drawing independent A/B/C on refresh only.
Existing HF RandomSampler training is not asserted to be an iid oracle.
"""
step = self.state.global_step
event = None
if step > 0 and step % self.args.refresh_every == 0 and self.used()+15 <= self.args.main_forward_budget:
selection_seed = seed_for(self.args.seed, 1701, step)
tangent_seed = seed_for(self.args.seed, 1702, step)
if seed == selection_seed:
raise ValueError('Training and selection directions must have independent seeds')
event = self.curvature_refresh(selection_batches(), selection_seed, tangent_seed,
certified_smoothness=certified_smoothness, basis_lr=basis_lr,
basis_radius=basis_radius)
event['step'] = step
return self.fix_step(inputs, seed)[0], event
def configure_history(self):
names = [n for n in self.basis if n.endswith('self_attn.v_proj.weight')]
if len(names) < 3:
raise ValueError('Node proposal needs three v_proj layers')
ids = sorted(set((min(len(names) - 1, int(len(names) * v / 24)) for v in (15, 17, 19))))
if len(ids) < 3:
ids = list(range(len(names) - 3, len(names)))
self.history = {names[i]: self.parameter_map[names[i]].new_zeros(self.parameter_map[names[i]].shape[0], 1) for i in ids}
def node_proposal(self, inputs, seed):
"""Estimate G.T @ p using node probes, then normalize it into a basis.
p is the normalized EMA of projected coefficient gradients G @ d.
The sketch estimates a vector, not the scalar coverage s = ||G @ d||^2.
"""
clean, logits = self.call(inputs)
mask = inputs['attention_mask'].bool()
new = {}
metrics = {}
if self.args.task_name.lower() == 'sst2':
residual = logits.softmax(1)[:, 1] - inputs['labels']
margin = logits[:, 1] - logits[:, 0]
for ni, (n, hist) in enumerate(self.history.items()):
norm = float(hist.norm())
if norm <= 1e-20:
metrics[n] = {'skipped': 'zero history'}
continue
p = hist.flatten() / norm
est = []
for k in range(self.args.node_queries):
gen = torch.Generator(device=self.args.device).manual_seed(seed_for(seed, ni, k))
eta = (torch.randint(0, 2, mask.shape, generator=gen, device=self.args.device) * 2 - 1) * mask
features = {}
def hook(mod, args, output):
x = args[0].reshape(*mask.shape, -1)
features['x'] = (x * eta[:, :, None]).sum(1)
return output + (self.args.node_epsilon * eta[:, :, None] * p).reshape_as(output)
handle = self.linear_map[n].register_forward_hook(hook)
try:
pert_loss, pert_logits = self.call(inputs)
finally:
handle.remove()
if self.args.task_name.lower() == 'sst2':
d = residual * (pert_logits[:, 1] - pert_logits[:, 0] - margin) / self.args.node_epsilon
else:
d = (pert_loss - clean) / self.args.node_epsilon
est.append((features['x'] * d[:, None]).mean(0))
sketch = torch.stack(est).mean(0)
sn = float(sketch.norm())
if sn <= 1e-20:
metrics[n] = {'skipped': 'zero sketch'}
continue
d = sketch[:, None] / sn
old = self.basis[n]
if float((d.T @ old).sum()) < 0:
d = -d
new[n] = d
metrics[n] = dict(history_norm=norm, sketch_norm=sn, overlap=float((d.T @ old).square().sum()))
return (new, metrics)
def descent_probe(self, inputs, candidates, seed, lr):
"""Predict the actual one-sided SGD step from three same-batch loss values.
Exact for a quadratic objective; no virtual update or diagnostic gradient.
All candidates share the clean forward and coefficient-space Gaussian z.
"""
mu = self.args.zo_eps
clean = self.call(inputs)[0].detach().clone()
trials = []
for bases in candidates:
plus = self.shifted(inputs, bases, seed, mu)
minus = self.shifted(inputs, bases, seed, -mu)
slope = float((plus.double() - minus.double()).mean()) / (2 * mu)
curvature = float((plus.double() - 2 * clean.double() + minus.double()).mean()) / mu ** 2
response = float((plus - clean).double().mean()) / mu
first_order = lr * slope * response
second_order = 0.5 * lr ** 2 * response ** 2 * curvature
predicted = first_order - second_order
if not all((math.isfinite(v) for v in (slope, curvature, response, predicted))):
raise FloatingPointError('Nonfinite node descent prediction')
trials.append(dict(clean_loss=float(clean.double().mean()), plus_loss=float(plus.double().mean()), minus_loss=float(minus.double().mean()), slope=slope, curvature=curvature, response=response, first_order=first_order, second_order=second_order, predicted_descent=predicted))
return trials
def used(self):return self.counts['training']+self.counts['calibration']
def learning_rate_at(self,q):
a=self.args
if a.zo_schedule=='constant':return a.learning_rate
f=min(1,max(0,(q-a.decay_start)/max(1,a.main_forward_budget-a.decay_start)))
return a.lr_min+(a.learning_rate-a.lr_min)*.5*(1+math.cos(math.pi*f))
def progress(self,stage):
out=Path(self.args.output_dir);point=self.curve[-1] if self.curve else None
best=min(self.curve,key=lambda p:p['development']['loss']) if self.curve else None
value=dict(stage=stage,completed=self.used(),total=self.args.main_forward_budget,current_unit=self.args.trainer,pid=os.getpid(),output_directory=str(out),
elapsed_seconds=time.monotonic()-self.started,last_update=datetime.now(timezone.utc).isoformat(),step=self.state.global_step,latest_training_batch=self.latest,evaluation=point,query_counts=self.counts.copy(),
best_development=None if best is None else {'loss':best['development']['loss'],'main_forwards':best['main_forwards']},current_lr=self.current_lr,memory=memory(),data_protocol=self.args.data_protocol)
save(out/'progress.json',value)
text=f"# {self.args.trainer}: {stage}\n\nMain forwards: {self.used()}/{self.args.main_forward_budget}; updates: {self.state.global_step}; PID: {os.getpid()}\n\nLatest batch: {self.latest}\n\nLast evaluation (actual query count): {point}\n\nBest development: {value['best_development']}\n\nLR: {self.current_lr}; elapsed: {value['elapsed_seconds']:.1f}s\n\nUpdated UTC: {value['last_update']}\n"
tmp=out/'progress.md.tmp';tmp.write_text(text);tmp.replace(out/'progress.md')
print(value,flush=True)
def collate(self,indices,dataset=None):
dataset=self.train_dataset if dataset is None else dataset
return self._prepare_inputs(self.data_collator([dataset[int(i)] for i in indices]))
@torch.no_grad()
def evaluate_dataset(self,dataset,indices=None):
indices=list(range(len(dataset))) if indices is None else list(indices)
total=weight_sum=correct=label_count=0
size=self.args.per_device_eval_batch_size
for start in range(0,len(indices),size):
chosen=indices[start:start+size];inputs=self.collate(chosen,dataset)
losses,logits=self.call(inputs,'evaluation')
weight=self.loss_backend.last_weight if self.args.data_protocol=='mezo' else len(chosen)
total+=float(losses.double().mean())*weight;weight_sum+=weight
if self.args.task_name=='SST2':
correct+=int((logits.argmax(1)==inputs['labels']).sum());label_count+=len(inputs['labels'])
result=dict(loss=total/weight_sum,examples=len(indices))
if label_count:result['accuracy']=correct/label_count
return result
def measure(self):
point=dict(step=self.state.global_step,main_forwards=self.used(),elapsed_seconds=time.monotonic()-self.started,
train_probe=self.evaluate_dataset(self.train_dataset,range(min(128,len(self.train_dataset)))),development=self.evaluate_dataset(self.eval_dataset))
if getattr(self.args, 'select_best_checkpoint', False) and self.state.global_step > 0:
if not hasattr(self, 'best_checkpoint') or point['development']['loss'] < self.best_checkpoint['development']['loss']:
self.save_model(str(Path(self.args.output_dir)/'best_model'))
self.best_checkpoint = dict(step=point['step'], main_forwards=point['main_forwards'],
development=point['development'], criterion='minimum development loss',
evaluation_forwards=self.counts['evaluation'])
save(Path(self.args.output_dir)/'best_checkpoint.json', self.best_checkpoint)
self.curve.append(point);out=Path(self.args.output_dir);save(out/'curve.json',self.curve);figures(out,self.curve);self.progress('evaluation')
@torch.no_grad()
def restore_best_model(self):
"""Stream saved tensors into the existing model, preserving tied weights."""
import json
from safetensors import safe_open
folder = Path(self.args.output_dir)/'best_model'
index = folder/'model.safetensors.index.json'
files = sorted(set(json.loads(index.read_text())['weight_map'].values())) if index.exists() else ['model.safetensors']
state = self.model.state_dict() # References, not a weight snapshot.
key = lambda t: (t.data_ptr(), t.storage_offset(), tuple(t.shape))
missing = {key(t) for t in state.values()}
for filename in files:
with safe_open(str(folder/filename), framework='pt', device='cpu') as handle:
for name in handle.keys():
state[name].copy_(handle.get_tensor(name))
missing.discard(key(state[name]))
if missing:
raise RuntimeError('Best checkpoint does not cover all model tensors')
@torch.no_grad()
def _inner_training_loop(self,batch_size=None,args=None,resume_from_checkpoint=None,trial=None,ignore_keys_for_eval=None):
args=args or self.args
if resume_from_checkpoint:raise ValueError('Resume is not implemented; use a fresh run or load a merged HF model for inference')
self._train_batch_size=batch_size or args.per_device_train_batch_size
out=Path(args.output_dir);self.progress('calibration')
try:
self.configure_basis(self.collate(range(min(args.calibration_samples,len(self.train_dataset)))))
local_curvature = args.trainer=='node' and getattr(args,'node_update','original')=='local_curvature'
history_free = args.trainer=='node' and getattr(args,'node_update','original')=='history_free'
if args.trainer=='node' and not (local_curvature or history_free):self.configure_history()
save(out/'parameter_inventory.json',dict(unique_tensors=len(self.parameters),unique_parameters=sum(p.numel() for p in self.parameters),
structured_weights=len(self.basis),node_targets=list(self.basis) if history_free else list(self.history),coverage='direct_weights_inplace_v2: Linear low-rank SGD on W; dense embedding/norm/bias SGD; tied head once'))
if args.preflight_only:
inputs=self.collate(range(min(2,len(self.train_dataset))));before=self.call(inputs,'diagnostic')[0].clone()
self.shifted(inputs,self.basis,71,args.zo_eps)
torch.testing.assert_close(before,self.call(inputs,'diagnostic')[0],rtol=1e-5,atol=1e-6)
self.basis.update({n:-d for n,d in self.basis.items()})
torch.testing.assert_close(before,self.call(inputs,'diagnostic')[0],rtol=1e-5,atol=1e-6)
save(out/'preflight.json',dict(passed=True,counts=self.counts));self.progress('complete')
return TrainOutput(0,0.,{'main_forwards':self.used()})
dataloader=self.get_train_dataloader();iterator=iter(dataloader)
rng_probe=np.random.default_rng(seed_for(args.seed,12))
def probe_batch():
ids=rng_probe.choice(len(self.train_dataset),min(args.per_device_train_batch_size,len(self.train_dataset)),replace=False)
return self.collate(ids)
self.probe_batch = probe_batch
# Independent selection draws; preserve the author's HF training sampler.
rng_selection = np.random.default_rng(seed_for(args.seed,1710))
def selection_batches():
return [self.collate(rng_selection.choice(len(self.train_dataset),
args.per_device_train_batch_size,replace=False)) for _ in range(3)]
self.measure();next_eval=args.eval_main_forwards;sum_loss=0.
while self.used()+2<=args.main_forward_budget and (args.max_steps<=0 or self.state.global_step<args.max_steps):
step=self.state.global_step;self.current_lr=self.learning_rate_at(self.used())
try:inputs=next(iterator)
except StopIteration:iterator=iter(dataloader);inputs=next(iterator)
step+=1;inputs=self._prepare_inputs(inputs)
np.random.seed(seed_for(args.seed,33,step)%2**32);torch.manual_seed(seed_for(args.seed,22,step))
update_seed = seed_for(args.seed,33,step)
if args.trainer == 'fix':
self.latest, event = self.fix_step(inputs, update_seed)
elif args.trainer == 'adjust':
self.latest, event = self.adjust_step(inputs, update_seed)
elif history_free:
self.latest, event = self.coverage_step(inputs, update_seed)
elif local_curvature:
self.latest, event = self.curvature_step(inputs, update_seed,
selection_batches=selection_batches, basis_lr=args.basis_lr,
basis_radius=args.basis_radius)
else:
self.latest, event = self.node_step(inputs, update_seed)
if event is not None:
append(out/'refresh.jsonl', event)
self.state.global_step=step;sum_loss+=self.latest['batch_loss'];append(out/'records.jsonl',dict(step=step,main_forwards=self.used(),**self.latest))
if step%10==0:self.progress('training')
if self.used()>=next_eval:self.measure();next_eval=(self.used()//args.eval_main_forwards+1)*args.eval_main_forwards
if self.curve[-1]['main_forwards']!=self.used():self.measure()
save(out/'query_ledger.json',dict(main_forwards=self.used(),counts=self.counts,all_detection_charged=True,evaluations_separate=True))
if getattr(args, 'select_best_checkpoint', False):self.restore_best_model()
save(out/'summary.json',dict(status='complete',steps=self.state.global_step,main_forwards=self.used(),counts=self.counts,memory=memory(),elapsed_seconds=time.monotonic()-self.started,data_protocol=args.data_protocol,
evaluated_weights='development_best' if getattr(args,'select_best_checkpoint',False) else 'final_iterate',
best_checkpoint=getattr(self,'best_checkpoint',None)))
if args.save_final_checkpoint:self.save_model(str(out/'model'))
self.progress('complete')
return TrainOutput(self.state.global_step,sum_loss/max(1,self.state.global_step),{'main_forwards':self.used()})
except BaseException:
import traceback
save(out/'failure.json',{'traceback':traceback.format_exc()});self.progress('failed');raise
@torch.no_grad()
def save_model(self, output_dir=None, _internal_call=False):
"""W already contains all learned updates; export an ordinary HF model."""
out = Path(output_dir or self.args.output_dir)
out.mkdir(parents=True, exist_ok=True)
self.model.save_pretrained(out)
self.processing_class.save_pretrained(out)
save(out/'weights_export.json', dict(format='Standard HF weights',
parameterization='direct_weights_inplace_v2', resume_supported=False,
source_protocol=self.args.data_protocol))
+355
View File
@@ -0,0 +1,355 @@
import json
import os
import contextlib
from typing import Optional, Union
import numpy as np
from dataclasses import dataclass, is_dataclass, asdict
import logging
import time
from torch.nn import CrossEntropyLoss
import torch.nn.functional as F
from transformers.modeling_outputs import CausalLMOutputWithPast
import torch
from transformers.utils import PaddingStrategy
from transformers import PreTrainedTokenizerBase
from transformers.data.data_collator import DataCollatorMixin
import transformers
from typing import Optional, Union, List, Dict, Any
import signal
from subprocess import call
from collections.abc import Mapping
from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union
InputDataClass = NewType("InputDataClass", Any)
from dataclasses import dataclass
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
logger = logging.getLogger(__name__)
def forward_wrap_with_option_len(self, input_ids=None, labels=None, option_len=None, num_options=None, return_dict=None, **kwargs):
"""
This is to replace the original forward function of Transformer models to enable:
(1) Partial target sequence: loss will only be calculated on part of the sequence
(2) Classification-style training: a classification loss (CE) will be calculated over several options
Input:
- input_ids, labels: same as the original forward function
- option_len: a list of int indicating the option lengths, and loss will be calculated only on the
last option_len tokens
- num_options: a list of int indicating the number of options for each example (this will be #label
words for classification tasks and #choices for multiple choice tasks), and a classification loss
will be calculated.
"""
outputs = self.original_forward(input_ids=input_ids, **kwargs)
if labels is None:
return outputs
logits = outputs.logits
loss = None
# Shift so that tokens < n predict n
shift_logits = logits[..., :-1, :].contiguous()
# Here we use input_ids (which should always = labels) bc sometimes labels are correct candidate IDs
shift_labels = torch.clone(input_ids)[..., 1:].contiguous()
shift_labels[shift_labels == self.config.pad_token_id] = -100
# Apply option len (do not calculate loss on the non-option part)
for _i, _len in enumerate(option_len):
shift_labels[_i, :-_len] = -100
# Calculate the loss
loss_fct = CrossEntropyLoss(ignore_index=-100)
if num_options is not None:
# Train as a classification tasks
log_probs = F.log_softmax(shift_logits, dim=-1)
mask = shift_labels != -100 # Option part
shift_labels[~mask] = 0 # So that it doesn't mess up with indexing
selected_log_probs = torch.gather(log_probs, dim=-1, index=shift_labels.unsqueeze(-1)).squeeze(-1) # (bsz x num_options, len)
selected_log_probs = (selected_log_probs * mask).sum(-1) / mask.sum(-1) # (bsz x num_options)
if any([x != num_options[0] for x in num_options]):
# Multi choice tasks with different number of options
loss = 0
start_id = 0
count = 0
while start_id < len(num_options):
end_id = start_id + num_options[start_id]
_logits = selected_log_probs[start_id:end_id].unsqueeze(0) # (1, num_options)
_labels = labels[start_id:end_id][0].unsqueeze(0) # (1)
loss = loss_fct(_logits, _labels) + loss
count += 1
start_id = end_id
loss = loss / count
else:
num_options = num_options[0]
selected_log_probs = selected_log_probs.view(-1, num_options) # (bsz, num_options)
labels = labels.view(-1, num_options)[:, 0] # Labels repeat so we only take the first one
loss = loss_fct(selected_log_probs, labels)
else:
loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
if not return_dict:
output = (logits,) + outputs[1:]
return (loss,) + output if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def encode_prompt(task, template, train_samples, eval_sample, tokenizer, max_length, sfc=False, icl_sfc=False, generation=False, generation_with_gold=False, max_new_tokens=None):
"""
Encode prompts for eval_sample
Input:
- task, template: task and template class
- train_samples, eval_sample: demonstrations and the actual sample
- tokenizer, max_length: tokenizer and max length
- sfc: generate prompts for calibration (surface form competition; https://arxiv.org/abs/2104.08315)
- icl_sfc: generate prompts for ICL version calibration
- generation: whether it is an generation task
- generation_with_gold: whether to include the generation-task gold answers (for training)
- max_new_tokens: max number of new tokens to generate so that we can save enough space
(only for generation tasks)
Output:
- encodings: a list of N lists of tokens. N is the number of options for classification/multiple-choice.
- option_lens: a list of N integers indicating the number of option tokens.
"""
# Demonstrations for ICL
train_prompts = [template.verbalize(sample, sample.correct_candidate).strip() for sample in train_samples]
train_prompts = task.train_sep.join(train_prompts).strip()
# sfc or icl_sfc indicates that this example is used for calibration
if sfc or icl_sfc:
encode_fn = template.encode_sfc; verbalize_fn = template.verbalize_sfc
else:
encode_fn = template.encode; verbalize_fn = template.verbalize
unverbalized_eval_prompt = encode_fn(eval_sample).strip(' ')
if not generation:
# We generate one prompt for each candidate (different classes in classification)
# or different choices in multiple-choice tasks
verbalized_eval_prompts = [verbalize_fn(eval_sample, cand).strip(' ') for cand in eval_sample.candidates]
unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt))
option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for verbalized_eval_prompt in verbalized_eval_prompts]
if sfc:
# Without demonstrations
final_prompts = verbalized_eval_prompts
else:
# With demonstrations
final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in verbalized_eval_prompts]
else:
assert not sfc and not icl_sfc, "Generation tasks do not support SFC"
if generation_with_gold:
verbalized_eval_prompts = [verbalize_fn(eval_sample, eval_sample.correct_candidate)]
unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt))
option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for verbalized_eval_prompt in verbalized_eval_prompts]
final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in verbalized_eval_prompts]
else:
option_lens = [0]
final_prompts = [(train_prompts + task.train_sep + unverbalized_eval_prompt).lstrip().strip(' ')]
# Tokenize
encodings = [tokenizer.encode(final_prompt) for final_prompt in final_prompts]
# Truncate (left truncate as demonstrations are less important)
if generation and max_new_tokens is not None:
max_length = max_length - max_new_tokens
if any([len(encoding) > max_length for encoding in encodings]):
logger.warn("Exceed max length")
if getattr(tokenizer, "add_bos_token", False):
encodings = [encoding[0:1] + encoding[1:][-(max_length-1):] for encoding in encodings]
else:
encodings = [encoding[-max_length:] for encoding in encodings]
return encodings, option_lens
@dataclass
class ICLCollator:
"""
Collator for ICL
"""
tokenizer: PreTrainedTokenizerBase
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
if not isinstance(features[0], Mapping):
features = [vars(f) for f in features]
first = features[0]
batch = {}
pad_id = self.tokenizer.pad_token_id
pad_ids = {"input_ids": pad_id, "attention_mask": 0, "sfc_input_ids": pad_id, "sfc_attention_mask": 0, "labels": pad_id}
for key in first:
pp = pad_ids[key]
lens = [len(f[key]) for f in features]
max_len = max(lens)
feature = np.stack([np.pad(f[key], (0, max_len - lens[i]), "constant", constant_values=(0, pp)) for i, f in enumerate(features)])
padded_feature = torch.from_numpy(feature).long()
batch[key] = padded_feature
return batch
@dataclass
class DataCollatorWithPaddingAndNesting:
"""
Collator for training
"""
tokenizer: PreTrainedTokenizerBase
padding: Union[bool, str, PaddingStrategy] = True
max_length: Optional[int] = None
pad_to_multiple_of: Optional[int] = None
return_tensors: str = "pt"
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
features = [ff for f in features for ff in f]
batch = self.tokenizer.pad(
features,
padding=self.padding,
max_length=self.max_length,
pad_to_multiple_of=self.pad_to_multiple_of,
return_tensors=self.return_tensors,
)
if "label" in batch:
batch["labels"] = batch["label"]
del batch["label"]
if "label_ids" in batch:
batch["labels"] = batch["label_ids"]
del batch["label_ids"]
return batch
@dataclass
class NondiffCollator(DataCollatorMixin):
"""
Collator for non-differentiable objectives
"""
tokenizer: PreTrainedTokenizerBase
padding: Union[bool, str, PaddingStrategy] = True
max_length: Optional[int] = None
pad_to_multiple_of: Optional[int] = None
label_pad_token_id: int = -100
return_tensors: str = "pt"
def torch_call(self, features):
import torch
label_name = "label" if "label" in features[0].keys() else "labels"
labels = [feature[label_name] for feature in features] if label_name in features[0].keys() else None
no_labels_features = [{k: v for k, v in feature.items() if k != label_name and k != "gold"} for feature in features]
batch = self.tokenizer.pad(
no_labels_features,
padding=self.padding,
max_length=self.max_length,
pad_to_multiple_of=self.pad_to_multiple_of,
return_tensors="pt",
)
if labels is None:
return batch
sequence_length = batch["input_ids"].shape[1]
padding_side = self.tokenizer.padding_side
def to_list(tensor_or_iterable):
if isinstance(tensor_or_iterable, torch.Tensor):
return tensor_or_iterable.tolist()
return list(tensor_or_iterable)
if padding_side == "right":
batch[label_name] = [
to_list(label) + [self.label_pad_token_id] * (sequence_length - len(label)) for label in labels
]
else:
batch[label_name] = [
[self.label_pad_token_id] * (sequence_length - len(label)) + to_list(label) for label in labels
]
batch[label_name] = torch.tensor(batch[label_name], dtype=torch.int64)
if "gold" in features[0]:
batch["gold"] = [feature["gold"] for feature in features]
return batch
class SIGUSR1Callback(transformers.TrainerCallback):
"""
This callback is used to save the model when a SIGUSR1 signal is received
(SLURM stop signal or a keyboard interruption signal).
"""
def __init__(self) -> None:
super().__init__()
self.signal_received = False
signal.signal(signal.SIGUSR1, self.handle_signal)
signal.signal(signal.SIGINT, self.handle_signal)
logger.warn("Handler registered")
def handle_signal(self, signum, frame):
self.signal_received = True
logger.warn("Signal received")
def on_step_end(self, args, state, control, **kwargs):
if self.signal_received:
control.should_save = True
control.should_training_stop = True
def on_train_end(self, args, state, control, **kwargs):
if self.signal_received:
exit(0)
@dataclass
class Prediction:
correct_candidate: Union[int, str]
predicted_candidate: Union[int, str]
@contextlib.contextmanager
def count_time(name):
logger.info("%s..." % name)
start_time = time.time()
try:
yield
finally:
logger.info("Done with %.2fs" % (time.time() - start_time))
@contextlib.contextmanager
def temp_seed(seed):
state = np.random.get_state()
np.random.seed(seed)
try:
yield
finally:
np.random.set_state(state)
class EnhancedJSONEncoder(json.JSONEncoder):
def default(self, o):
if is_dataclass(o):
return asdict(o)
return super().default(o)
def write_predictions_to_file(final_preds, output):
with open(output, "w") as f:
for pred in final_preds:
f.write(json.dumps(pred, cls=EnhancedJSONEncoder) + "\n")
def write_metrics_to_file(metrics, output):
json.dump(metrics, open(output, "w"), cls=EnhancedJSONEncoder, indent=4)