repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/mixtral/benchmark.py
examples/language/mixtral/benchmark.py
# modified from llama benchmark import argparse import resource import time import warnings from contextlib import nullcontext import torch import torch.distributed as dist from data_utils import RandomDataset from model_utils import format_numel_str, get_model_numel from performance_evaluator import PerformanceEvaluator, get_profile_context from tqdm import tqdm from transformers import AutoConfig from transformers.models.mixtral import MixtralConfig, MixtralForCausalLM import colossalai from colossalai.accelerator import get_accelerator from colossalai.booster import Booster from colossalai.booster.plugin import MoeHybridParallelPlugin from colossalai.cluster import DistCoordinator from colossalai.lazy import LazyInitContext from colossalai.nn.optimizer import HybridAdam from colossalai.pipeline.schedule.v_schedule import PipelineGraph from colossalai.shardformer import PipelineGradientCheckpointConfig warnings.filterwarnings("ignore") # ============================== # Constants # ============================== # We have lots of llamas for your choice! MODEL_CONFIGS = { "100m": MixtralConfig( max_position_embeddings=4096, num_hidden_layers=4, num_attention_heads=32, intermediate_size=768, hidden_size=768, attn_implementation="flash_attention_2", ), "7b": MixtralConfig( max_position_embeddings=4096, num_hidden_layers=5, attn_implementation="flash_attention_2", ), "14b": MixtralConfig( max_position_embeddings=4096, num_hidden_layers=10, attn_implementation="flash_attention_2", ), } def main(): # ============================== # Parse Arguments # ============================== parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", type=str, default="100m", help="Model configuration") parser.add_argument( "-p", "--plugin", choices=["3d"], default="3d", help="Choose which plugin to use", ) parser.add_argument("-b", "--batch_size", type=int, default=1, help="Batch size") parser.add_argument("-s", "--num_steps", type=int, default=5, help="Number of steps to run") parser.add_argument("-i", "--ignore_steps", type=int, default=2, help="Number of steps to ignore") parser.add_argument("-g", "--grad_checkpoint", action="store_true", help="Use gradient checkpointing") parser.add_argument("-l", "--max_length", type=int, default=4096, help="Max sequence length") parser.add_argument( "-w", "--warmup_ratio", type=float, default=0.8, help="warm up ratio of non-model data. Only for gemini-auto" ) parser.add_argument("-m", "--memory_limit", type=int, help="Gemini memory limit in mb") parser.add_argument("-x", "--xformers", action="store_true", help="Use xformers") parser.add_argument("--shard_param_frac", type=float, default=1.0, help="Shard param fraction. Only for gemini") parser.add_argument("--offload_optim_frac", type=float, default=0.0, help="Offload optim fraction. Only for gemini") parser.add_argument("--offload_param_frac", type=float, default=0.0, help="Offload param fraction. Only for gemini") parser.add_argument("--tp", type=int, default=1, help="Tensor parallel size") parser.add_argument("--ep", type=int, default=1, help="Expert parallel size") parser.add_argument("--sp", type=int, default=1, help="Sequence parallel size") parser.add_argument("--extra_dp", type=int, default=1, help="Extra data parallel size, used for Gemini") parser.add_argument("--pp", type=int, default=1, help="Pipeline parallel size") parser.add_argument("--mbs", type=int, default=1, help="Micro batch size of pipeline parallel") parser.add_argument("--zero", type=int, default=1, help="Zero Stage when hybrid plugin is enabled") parser.add_argument("--custom-ckpt", action="store_true", help="Customize checkpoint", default=False) parser.add_argument("--pp_style", default="1f1b", choices=["1f1b", "interleaved", "zbv"]) parser.add_argument("--n_chunks", default=1, help="number of model chunks", type=eval) parser.add_argument("--profile", action="store_true", help="Profile the code") parser.add_argument( "--nsys", action="store_true", help="Use nsys for profiling. \ You should put something like this before colossalai launch: \ nsys profile -w true -t cuda,cudnn,cublas -s cpu --capture-range=cudaProfilerApi --capture-range-end=stop --cudabacktrace=true -x true --python-backtrace=cuda -o prof_out", ) parser.add_argument("--disable-async-reduce", action="store_true", help="Disable the asynchronous reduce operation") parser.add_argument("--prefetch_num", type=int, default=0, help="chunk prefetch max number") parser.add_argument("--no_cache", action="store_true") parser.add_argument("--use_fp8_comm", action="store_true", default=False, help="for using fp8 during communication") parser.add_argument("--use_fp8", action="store_true", default=False, help="for using fp8 linear") parser.add_argument("--overlap_allgather", action="store_true") parser.add_argument( "--sp_mode", default="all_to_all", choices=["all_to_all"], help="Sequence parallelism mode", ) parser.add_argument("--debug", action="store_true", help="Enable debug mode") args = parser.parse_args() colossalai.launch_from_torch() coordinator = DistCoordinator() # ckpt config for LLaMA3-70B on 64 H100 GPUs hybrid_kwargs = ( { "gradient_checkpoint_config": PipelineGradientCheckpointConfig( num_ckpt_layers_per_stage=[19, 19, 19, 13], ), "num_layers_per_stage": [19, 20, 20, 21], "pp_style": "interleaved", } if args.custom_ckpt else {} ) # ============================== # Initialize Booster # ============================== if args.config in MODEL_CONFIGS: config = MODEL_CONFIGS[args.config] else: config = AutoConfig.from_pretrained(args.config, trust_remote_code=True) if args.plugin == "3d": if args.pp_style == "zbv": mem_f = 34 * config.hidden_size + 5 * config.num_attention_heads * args.max_length mem_w = -32 * config.hidden_size mem_b = -mem_w - mem_f scheduler_nodes = PipelineGraph( n_stage=args.pp, n_micro=args.batch_size // args.mbs, f_cost=1000, b_cost=1000, w_cost=1000, c_cost=1, f_mem=mem_f, b_mem=mem_b, w_mem=mem_w, ).get_v_schedule() else: scheduler_nodes = None plugin = MoeHybridParallelPlugin( ep_size=args.ep, tp_size=args.tp, pp_size=args.pp, pp_style=args.pp_style, num_model_chunks=args.n_chunks, zero_stage=args.zero, sp_size=args.sp, sequence_parallelism_mode=args.sp_mode, enable_sequence_parallelism=args.sp > 1, enable_fused_normalization=torch.cuda.is_available(), enable_flash_attention=args.xformers, microbatch_size=args.mbs, num_microbatches=args.batch_size // args.mbs, precision="bf16", enable_metadata_cache=not args.no_cache, overlap_allgather=args.overlap_allgather, use_fp8=args.use_fp8, fp8_communication=args.use_fp8_comm, scheduler_nodes=scheduler_nodes, **hybrid_kwargs, ) else: raise ValueError(f"Unknown plugin {args.plugin}") booster = Booster(plugin=plugin) # ============================== # Initialize Dataset and Dataloader # ============================== dp_size = getattr(plugin, "dp_size", coordinator.world_size) if args.config in MODEL_CONFIGS: config = MODEL_CONFIGS[args.config] else: config = MixtralConfig.from_pretrained(args.config, trust_remote_code=True) torch.cuda.manual_seed(42) dataset = RandomDataset( num_samples=args.batch_size * args.num_steps * dp_size, max_length=args.max_length, vocab_size=config.vocab_size ) dataloader = plugin.prepare_dataloader(dataset, batch_size=args.batch_size, shuffle=True, drop_last=True, seed=42) # ============================== # Initialize Model and Optimizer # ============================== init_ctx = ( LazyInitContext(default_device=get_accelerator().get_current_device()) if isinstance(plugin, MoeHybridParallelPlugin) else nullcontext() ) with init_ctx: model = MixtralForCausalLM(config=config).to(torch.bfloat16) # if args.grad_checkpoint: # model.gradient_checkpointing_enable() if args.grad_checkpoint: model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) model_numel = get_model_numel(model) coordinator.print_on_master(f"Model params: {format_numel_str(model_numel)}") performance_evaluator = PerformanceEvaluator( model_numel, model.config.num_hidden_layers, model.config.hidden_size, model.config.vocab_size, args.grad_checkpoint, args.ignore_steps, dp_world_size=dp_size, ) optimizer = HybridAdam(model.parameters()) torch.set_default_dtype(torch.bfloat16) model, optimizer, _, dataloader, _ = booster.boost(model, optimizer, dataloader=dataloader) torch.set_default_dtype(torch.float) coordinator.print_on_master( f"Booster init max CUDA memory: {get_accelerator().max_memory_allocated()/1024**2:.2f} MB" ) coordinator.print_on_master( f"Booster init max CPU memory: {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024:.2f} MB" ) with get_profile_context( args.profile, args.ignore_steps, 1, # avoid creating massive log files save_dir=f"profile/{time.strftime('%H:%M', time.localtime())}-{args.plugin}-llama-{args.config}", nsys=args.nsys, ) as prof: if isinstance(plugin, MoeHybridParallelPlugin) and args.pp > 1: data_iter = iter(dataloader) for step in tqdm(range(len(dataloader)), desc="Step", disable=not coordinator.is_master()): performance_evaluator.on_step_start(step) outputs = booster.execute_pipeline( data_iter, model, criterion=lambda outputs, inputs: outputs[0], optimizer=optimizer, return_loss=True, ) loss = outputs["loss"] if args.pp_style == "zbv": if dist.get_rank() == 0: print(f"Step {step} loss: {loss}") else: if dist.get_rank() == dist.get_world_size() - 1: print(f"Step {step} loss: {loss}") optimizer.step() optimizer.zero_grad() performance_evaluator.on_step_end(input_ids=torch.empty(args.batch_size, args.max_length)) prof.step() else: for step, batch in enumerate(tqdm(dataloader, desc="Step", disable=not coordinator.is_master())): performance_evaluator.on_step_start(step) outputs = model(**batch) loss = outputs[0] del outputs # free memory if dist.get_rank() == dist.get_world_size() - 1: print(f"Step {step} loss: {loss}") booster.backward(loss, optimizer) optimizer.step() optimizer.zero_grad() performance_evaluator.on_step_end(**batch) prof.step() performance_evaluator.on_fit_end() coordinator.print_on_master(f"Max CUDA memory usage: {get_accelerator().max_memory_allocated()/1024**2:.2f} MB") if __name__ == "__main__": main()
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/mixtral/performance_evaluator.py
examples/language/mixtral/performance_evaluator.py
from time import time from typing import Optional import torch import torch.distributed as dist from torch import Tensor from torch.profiler import ProfilerActivity, profile, schedule, tensorboard_trace_handler from colossalai.cluster import DistCoordinator from colossalai.utils import get_current_device def divide(x: float, y: float) -> float: if y == 0: return float("inf") elif y == float("inf"): return float("nan") return x / y @torch.no_grad() def all_reduce_mean(x: float, world_size: int) -> float: if world_size == 1: return x # BUG: RuntimeError: Invalid scalar type when use dist.all_reduce(tensor, group=gloo_group) # # Use CPU tensor to avoid OOM/weird NCCl error # gloo_group = dist.new_group(backend="gloo") # tensor = torch.tensor([x], device="cpu") # dist.all_reduce(tensor, group=gloo_group) # tensor = tensor / world_size # return tensor.item() tensor = torch.tensor([x], device=get_current_device(), dtype=torch.float) dist.all_reduce(tensor) tensor = tensor / world_size return tensor.item() def get_profile_context(enable_flag, warmup_steps, active_steps, save_dir, nsys=False): class DummyProfiler: def __init__(self): self.step_number = 0 def step(self): self.step_number += 1 def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass class NsysProfiler: def __init__(self, warmup_steps, active_steps): self.step_number = 0 self.warmup_steps = warmup_steps self.active_steps = active_steps def step(self): if self.step_number == self.warmup_steps: torch.cuda.cudart().cudaProfilerStart() elif self.step_number == self.warmup_steps + self.active_steps: torch.cuda.cudart().cudaProfilerStop() self.step_number += 1 def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass if enable_flag: if nsys: return NsysProfiler(warmup_steps, active_steps) return profile( activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], schedule=schedule(wait=0, warmup=warmup_steps, active=active_steps), on_trace_ready=tensorboard_trace_handler(save_dir), record_shapes=True, profile_memory=True, with_stack=True, ) else: return DummyProfiler() class Timer: def __init__(self) -> None: self.start_time: Optional[float] = None self.duration: float = 0.0 def start(self) -> None: self.start_time = time() def end(self) -> None: assert self.start_time is not None self.duration += time() - self.start_time self.start_time = None def reset(self) -> None: self.duration = 0.0 class PerformanceEvaluator: """ Callback for valuate the performance of the model. Args: actor_num_params: The number of parameters of the actor model. critic_num_params: The number of parameters of the critic model. initial_model_num_params: The number of parameters of the initial model. reward_model_num_params: The number of parameters of the reward model. enable_grad_checkpoint: Whether to enable gradient checkpointing. ignore_episodes: The number of episodes to ignore when calculating the performance. """ def __init__( self, model_numel: int, num_layers: int, hidden_size: int, vocab_size: int, enable_grad_checkpoint: bool = False, ignore_steps: int = 0, dp_world_size: Optional[int] = None, ) -> None: self.model_numel = model_numel self.enable_grad_checkpoint = enable_grad_checkpoint self.ignore_steps = ignore_steps self.num_layers = num_layers self.hidden_size = hidden_size self.vocab_size = vocab_size self.coordinator = DistCoordinator() self.dp_world_size = dp_world_size or self.coordinator.world_size self.disable: bool = False self.timer = Timer() self.num_samples: int = 0 self.flop_megatron = 0 self.flop: int = 0 def on_step_start(self, step: int) -> None: self.disable = self.ignore_steps > 0 and step < self.ignore_steps if self.disable: return # get_accelerator().synchronize() self.timer.start() def on_step_end(self, input_ids: Tensor, **kwargs) -> None: if self.disable: return # get_accelerator().synchronize() self.timer.end() batch_size, seq_len = input_ids.shape self.num_samples += batch_size checkpoint_activations_factor = 3 + int(self.enable_grad_checkpoint) self.flop_megatron += ( 24 * checkpoint_activations_factor * batch_size * seq_len * self.num_layers * (self.hidden_size**2) ) * ( 1.0 + (seq_len / (6.0 * self.hidden_size)) + (self.vocab_size / (16.0 * self.num_layers * self.hidden_size)) ) self.flop += batch_size * seq_len * self.model_numel * 2 * (3 + int(self.enable_grad_checkpoint)) def on_fit_end(self) -> None: avg_duration = all_reduce_mean(self.timer.duration, self.coordinator.world_size) avg_throughput = self.num_samples * self.dp_world_size / (avg_duration + 1e-12) mp_world_size = self.coordinator.world_size // self.dp_world_size avg_tflops_per_gpu_megatron = self.flop_megatron / 1e12 / (avg_duration + 1e-12) / mp_world_size avg_tflops_per_gpu = self.flop / 1e12 / (avg_duration + 1e-12) / mp_world_size self.coordinator.print_on_master( f"num_samples: {self.num_samples}, dp_world_size: {self.dp_world_size}, flop_megatron: {self.flop_megatron}, flop: {self.flop}, avg_duration: {avg_duration}, " f"avg_throughput: {avg_throughput}" ) self.coordinator.print_on_master( f"Throughput: {avg_throughput:.2f} samples/sec, TFLOPS per GPU by Megatron: {avg_tflops_per_gpu_megatron:.2f}, TFLOPS per GPU: {avg_tflops_per_gpu:.2f}" )
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/experiments/auto_offload/model_zoo.py
examples/language/gpt/experiments/auto_offload/model_zoo.py
import torch import torch.nn as nn from transformers import GPT2Config, GPT2LMHeadModel class GPTLMModel(nn.Module): def __init__(self, hidden_size=768, num_layers=12, num_attention_heads=12, max_seq_len=1024, vocab_size=50257): super().__init__() self.model = GPT2LMHeadModel( GPT2Config( n_embd=hidden_size, n_layer=num_layers, n_head=num_attention_heads, n_positions=max_seq_len, n_ctx=max_seq_len, vocab_size=vocab_size, ) ) def forward(self, input_ids, attention_mask): # Only return lm_logits return self.model(input_ids=input_ids, attention_mask=attention_mask, use_cache=True)[0] class GPTLMLoss(nn.Module): def __init__(self): super().__init__() self.loss_fn = nn.CrossEntropyLoss() def forward(self, logits, labels): shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens return self.loss_fn(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)) def get_gpt2_components(model_type: str, batch_size: int): vocab_size = 1024 seq_len = 8 def gpt2_model_builder(): if model_type == "gpt2_medium": return GPTLMModel(hidden_size=1024, num_layers=24, num_attention_heads=16) elif model_type == "gpt2_xl": return GPTLMModel(hidden_size=1600, num_layers=48, num_attention_heads=32) elif model_type == "gpt2_10b": return GPTLMModel(hidden_size=4096, num_layers=50, num_attention_heads=16) elif model_type == "gpt2_14b": return GPTLMModel(hidden_size=4096, num_layers=70, num_attention_heads=16) elif model_type == "gpt2_20b": return GPTLMModel(hidden_size=8192, num_layers=25, num_attention_heads=16) elif model_type == "gpt2_24b": return GPTLMModel(hidden_size=8192, num_layers=30, num_attention_heads=16) else: raise TypeError(f"model_builder {model_type}") def gpt2_data_gen(device="cuda"): input_ids = torch.randint(0, vocab_size, (batch_size, seq_len), device=device) attention_mask = torch.ones_like(input_ids, device=device) kwargs = dict(input_ids=input_ids, attention_mask=attention_mask) return kwargs return gpt2_model_builder, gpt2_data_gen
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/experiments/auto_offload/train_gpt_offload.py
examples/language/gpt/experiments/auto_offload/train_gpt_offload.py
import argparse import time import pytest import torch from model_zoo import GPTLMLoss, get_gpt2_components from torch.utils._pytree import tree_map import colossalai from colossalai.accelerator import get_accelerator from colossalai.auto_parallel.offload.amp_optimizer import AMPOptimizer from colossalai.auto_parallel.offload.mem_optimize import memory_optimize from colossalai.auto_parallel.offload.solver import NOT_NVML from colossalai.fx.profiler import parameter_size from colossalai.nn.optimizer import HybridAdam from colossalai.testing import spawn def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--model_type", type=str, default="gpt2_medium") parser.add_argument("--batch_size", type=int, default=64) parser.add_argument("--solver_type", type=str, default="asyn") parser.add_argument("--memory_budget", type=float, default=16) return parser.parse_args() @pytest.mark.skipif(NOT_NVML, reason="pynvml is not installed") def train_gpt(args): memory_budget = args.memory_budget * 1024 * 1024 * 1024 solver_type = args.solver_type model_type = args.model_type batch_size = args.batch_size # build model model_builder, data_gen = get_gpt2_components(model_type=model_type, batch_size=batch_size) label = torch.randint( low=0, high=128, size=( 64, 8, ), device=get_accelerator().get_current_device(), ) criterion = GPTLMLoss() start_time = time.time() model = model_builder() model.train() param_size = parameter_size(model) / 1024**2 / 2 init_time = time.time() - start_time print(f"init_param_size={param_size:.3f} MB | init_model_time={init_time:.3f} s") data_args = data_gen(device="cpu") wrap_fn = lambda x: x.to(dtype=torch.half) if isinstance(x, torch.Tensor) and torch.is_floating_point(x) else x data_args = tree_map(wrap_fn, data_args) start_time = time.time() model = memory_optimize(model, data_args, memory_budget, solver_type) solver_time = time.time() - start_time print(f"solver_time={solver_time:.3f} s") hybrid_optimizer = HybridAdam(model.model.parameters(), lr=1e-3) optim = AMPOptimizer(hybrid_optimizer, model) torch.cuda.empty_cache() torch.cuda.synchronize() torch.cuda.reset_peak_memory_stats() time_list = [] data_args = data_gen(device="cuda") data_args = tree_map(wrap_fn, data_args) for step in range(10): optim.zero_grad() torch.cuda.synchronize() start_time = time.time() loss = criterion(model(**data_args), label) optim.backward(loss) torch.cuda.synchronize() time_list.append(time.time() - start_time) optim.step() torch.cuda.synchronize() exec_time = sum(sorted(time_list)[:5]) / 5 runtime_peak_mem_alc = torch.cuda.max_memory_allocated() / 1024**2 runtime_peak_mem_res = torch.cuda.max_memory_reserved() / 1024**2 print(f"solver_type: {solver_type} | model_type: {model_type}") print( f"| exec_time={exec_time:.3f} s | param_size={param_size:.3f} MB " f"| runtime_peak_mem_alc={runtime_peak_mem_alc:.3f} MB| runtime_peak_mem_res={runtime_peak_mem_res:.3f} MB|" ) print(time_list) def run(rank, world_size, port, args): colossalai.launch(rank=rank, world_size=world_size, host="localhost", port=port, backend="nccl") train_gpt(args) if __name__ == "__main__": args = parse_args() spawn(run, 1, args=args)
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/experiments/auto_parallel/auto_parallel_with_gpt.py
examples/language/gpt/experiments/auto_parallel/auto_parallel_with_gpt.py
from functools import partial from time import time import psutil import torch import transformers from gpt_modules import GPT2LMHeadModel, GPTLMLoss from colossalai.auto_parallel.tensor_shard.initialize import autoparallelize from colossalai.initialize import launch_from_torch from colossalai.legacy.core import global_context as gpc from colossalai.logging import disable_existing_loggers, get_dist_logger BATCH_SIZE = 16 SEQ_LENGTH = 1024 HIDDEN_DIM = 4096 NUM_HEADS = 16 NUM_LAYERS = 4 VOCAB_SIZE = 50257 NUM_STEPS = 10 FP16 = True def get_cpu_mem(): return psutil.Process().memory_info().rss / 1024**2 def get_gpu_mem(): return torch.cuda.memory_allocated() / 1024**2 def get_mem_info(prefix=""): return f"{prefix}GPU memory usage: {get_gpu_mem():.2f} MB, CPU memory usage: {get_cpu_mem():.2f} MB" def get_tflops(model_numel, batch_size, seq_len, step_time): # Tflops_per_GPU = global_batch * global_numel * seq_len * 8 / #gpu return model_numel * batch_size * seq_len * 8 / 1e12 / (step_time + 1e-12) / 8 # Randomly Generated Data def get_data(batch_size, seq_len, vocab_size): input_ids = torch.randint(0, vocab_size, (batch_size, seq_len), device=torch.cuda.current_device()) attention_mask = torch.ones_like(input_ids) return input_ids, attention_mask def main(): disable_existing_loggers() launch_from_torch() logger = get_dist_logger() config = transformers.GPT2Config(n_position=SEQ_LENGTH, n_layer=NUM_LAYERS, n_head=NUM_HEADS, n_embd=HIDDEN_DIM) if FP16: model = GPT2LMHeadModel(config=config).half().to("cuda") else: model = GPT2LMHeadModel(config=config).to("cuda") global_numel = sum([p.numel() for p in model.parameters()]) meta_input_sample = { "input_ids": torch.zeros((BATCH_SIZE, SEQ_LENGTH), dtype=torch.int64).to("meta"), "attention_mask": torch.zeros((BATCH_SIZE, SEQ_LENGTH), dtype=torch.int64).to("meta"), } gm, solution = autoparallelize(model, meta_input_sample, return_solution=True) # print solution on rank 0 if gpc.get_global_rank() == 0: for node_strategy in solution: print(node_strategy) # build criterion criterion = GPTLMLoss() optimizer = torch.optim.Adam(gm.parameters(), lr=0.01) logger.info(get_mem_info(prefix="After init model, "), ranks=[0]) get_tflops_func = partial(get_tflops, global_numel, BATCH_SIZE, SEQ_LENGTH) torch.cuda.synchronize() model.train() for n in range(10): # we just use randomly generated data here input_ids, attn_mask = get_data(BATCH_SIZE, SEQ_LENGTH, VOCAB_SIZE) optimizer.zero_grad() start = time() outputs = gm(input_ids, attn_mask) loss = criterion(outputs, input_ids) loss.backward() optimizer.step() torch.cuda.synchronize() step_time = time() - start logger.info( f"[{n+1}/{NUM_STEPS}] Loss:{loss.item():.3f}, Step time: {step_time:.3f}s, TFLOPS: {get_tflops_func(step_time):.3f}", ranks=[0], ) torch.cuda.synchronize() if __name__ == "__main__": main()
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/experiments/auto_parallel/gpt_modules.py
examples/language/gpt/experiments/auto_parallel/gpt_modules.py
from typing import Optional, Tuple, Union import torch import torch.nn as nn from transformers.activations import ACT2FN from transformers.models.gpt2.modeling_gpt2 import BaseModelOutputWithPastAndCrossAttentions, GPT2PreTrainedModel from transformers.pytorch_utils import Conv1D class GPT2MLP(nn.Module): def __init__(self, intermediate_size, config): super().__init__() embed_dim = config.hidden_size self.c_fc = Conv1D(intermediate_size, embed_dim) self.c_proj = Conv1D(embed_dim, intermediate_size) self.act = ACT2FN[config.activation_function] self.dropout = nn.Dropout(config.resid_pdrop) def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor: hidden_states = self.c_fc(hidden_states) hidden_states = self.act(hidden_states) hidden_states = self.c_proj(hidden_states) return hidden_states # The reason Why we don't import GPT2Attention from transformers directly is that: # 1. The tracer will not work correctly when we feed meta_args and concrete_args at same time, # so we have to build the customized GPT2Attention class and remove the conditional branch manually. # 2. The order of split and view op has been changed in the customized GPT2Attention class, the new # order is same as megatron-lm gpt model. class GPT2Attention(nn.Module): def __init__(self, config, layer_idx=None): super().__init__() max_positions = config.max_position_embeddings self.register_buffer( "bias", torch.tril(torch.ones((max_positions, max_positions), dtype=torch.uint8)).view( 1, 1, max_positions, max_positions ), ) self.register_buffer("masked_bias", torch.tensor(-1e4)) self.embed_dim = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.embed_dim // self.num_heads self.split_size = self.embed_dim self.scale_attn_weights = config.scale_attn_weights # Layer-wise attention scaling, reordering, and upcasting self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx self.layer_idx = layer_idx self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim) self.c_proj = Conv1D(self.embed_dim, self.embed_dim) self.attn_dropout = nn.Dropout(config.attn_pdrop) self.resid_dropout = nn.Dropout(config.resid_pdrop) self.pruned_heads = set() def _attn(self, query, key, value, attention_mask=None, head_mask=None): attn_weights = torch.matmul(query, key.transpose(-1, -2)) if self.scale_attn_weights: attn_weights = attn_weights / (value.size(-1) ** 0.5) # Layer-wise attention scaling if self.scale_attn_by_inverse_layer_idx: attn_weights = attn_weights / float(self.layer_idx + 1) # if only "normal" attention layer implements causal mask query_length, key_length = query.size(-2), key.size(-2) causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length].to(torch.bool) attn_weights = torch.where(causal_mask, attn_weights, self.masked_bias.to(attn_weights.dtype)) if attention_mask is not None: # Apply the attention mask attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1) attn_weights = attn_weights.type(value.dtype) # Mask heads if we want to if head_mask is not None: attn_weights = attn_weights * head_mask attn_output = torch.matmul(attn_weights, value) return attn_output, attn_weights def _split_heads(self, tensor, num_heads, attn_head_size): new_shape = tensor.size()[:-1] + (num_heads, attn_head_size) tensor = tensor.view(new_shape) return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features) def _merge_heads(self, tensor, num_heads, attn_head_size): tensor = tensor.permute(0, 2, 1, 3).contiguous() new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,) return tensor.view(new_shape) def forward( self, hidden_states: Optional[Tuple[torch.FloatTensor]], attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]: qkv = self.c_attn(hidden_states) query, key, value = self._split_heads(qkv, self.num_heads, 3 * self.head_dim).split(self.head_dim, dim=3) (key, value) attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask) attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim) attn_output = self.c_proj(attn_output) return attn_output class GPT2Block(nn.Module): def __init__(self, config, layer_idx=None): super().__init__() hidden_size = config.hidden_size inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon) self.attn = GPT2Attention(config, layer_idx=layer_idx) self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon) self.mlp = GPT2MLP(inner_dim, config) def forward( self, hidden_states: Optional[Tuple[torch.FloatTensor]], attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]: residual = hidden_states hidden_states = self.ln_1(hidden_states) attn_outputs = self.attn( hidden_states, attention_mask=attention_mask, head_mask=head_mask, ) # residual connection hidden_states = attn_outputs + residual residual = hidden_states hidden_states = self.ln_2(hidden_states) feed_forward_hidden_states = self.mlp(hidden_states) # residual connection hidden_states = residual + feed_forward_hidden_states return hidden_states class GPT2Model(GPT2PreTrainedModel): def __init__(self, config): super().__init__(config) self.embed_dim = config.hidden_size self.wte = nn.Embedding(config.vocab_size, self.embed_dim) self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim) self.drop = nn.Dropout(config.embd_pdrop) self.h = nn.ModuleList([GPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)]) self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon) # Initialize weights and apply final processing self.post_init() def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]: input_shape = input_ids.size() input_ids = input_ids.view(-1, input_shape[-1]) batch_size = input_ids.shape[0] device = input_ids.device past_length = 0 past_key_values = tuple([None] * len(self.h)) position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device) position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1]) # GPT2Attention mask. attention_mask = attention_mask.view(batch_size, -1) attention_mask = attention_mask[:, None, None, :] attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility attention_mask = (1.0 - attention_mask) * -10000.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # head_mask has shape n_layer x batch x n_heads x N x N head_mask = self.get_head_mask(head_mask, self.config.n_layer) inputs_embeds = self.wte(input_ids) position_embeds = self.wpe(position_ids) hidden_states = inputs_embeds + position_embeds output_shape = input_shape + (hidden_states.size(-1),) for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)): outputs = block(hidden_states, attention_mask=attention_mask, head_mask=head_mask[i]) hidden_states = outputs hidden_states = self.ln_f(hidden_states) hidden_states = hidden_states.view(output_shape) return hidden_states class GPT2LMHeadModel(GPT2PreTrainedModel): def __init__(self, config): super().__init__(config) self.transformer = GPT2Model(config) self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) # Initialize weights and apply final processing self.post_init() def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, ): transformer_outputs = self.transformer( input_ids=input_ids, attention_mask=attention_mask, ) lm_logits = self.lm_head(transformer_outputs) return lm_logits class GPTLMLoss(nn.Module): def __init__(self): super().__init__() self.loss_fn = nn.CrossEntropyLoss() def forward(self, logits, labels): shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens return self.loss_fn(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/experiments/pipeline_parallel/model_zoo.py
examples/language/gpt/experiments/pipeline_parallel/model_zoo.py
from torch import nn from transformers import GPT2Config, GPT2LMHeadModel ## Define the Model and Loss Based on Huggingface transformers GPT2LMHeadModel class GPTLMModel(nn.Module): def __init__( self, hidden_size=768, num_layers=12, num_attention_heads=12, max_seq_len=1024, vocab_size=50257, checkpoint=False, ): super().__init__() self.checkpoint = checkpoint self.config = GPT2Config( n_embd=hidden_size, n_layer=num_layers, n_head=num_attention_heads, n_positions=max_seq_len, n_ctx=max_seq_len, vocab_size=vocab_size, ) self.model = GPT2LMHeadModel(self.config) if checkpoint: self.model.gradient_checkpointing_enable() def forward(self, input_ids, attention_mask): # Only return lm_logits return self.model(input_ids=input_ids, attention_mask=attention_mask, use_cache=not self.checkpoint)[0] def gpt2_medium(checkpoint=False): return GPTLMModel(hidden_size=1024, num_layers=24, num_attention_heads=16, checkpoint=checkpoint) def gpt2_xl(checkpoint=True): return GPTLMModel(hidden_size=1600, num_layers=48, num_attention_heads=32, checkpoint=checkpoint) def gpt2_10b(checkpoint=True): return GPTLMModel(hidden_size=4096, num_layers=50, num_attention_heads=16, checkpoint=checkpoint) def gpt2_14b(checkpoint=True): return GPTLMModel(hidden_size=4096, num_layers=70, num_attention_heads=16, checkpoint=checkpoint) def gpt2_20b(checkpoint=True): return GPTLMModel(hidden_size=8192, num_layers=25, num_attention_heads=16, checkpoint=checkpoint) def gpt2_24b(checkpoint=True): return GPTLMModel(hidden_size=8192, num_layers=30, num_attention_heads=16, checkpoint=checkpoint) def model_builder(model_size: str) -> callable: if model_size == "gpt2_medium": return gpt2_medium elif model_size == "gpt2_xl": return gpt2_xl elif model_size == "gpt2_10b": return gpt2_10b elif model_size == "gpt2_14b": return gpt2_14b elif model_size == "gpt2_20b": return gpt2_20b elif model_size == "gpt2_24b": return gpt2_24b else: raise TypeError(f"model_builder {model_size}") __all__ = ["model_builder"]
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/experiments/pipeline_parallel/train_gpt_pp.py
examples/language/gpt/experiments/pipeline_parallel/train_gpt_pp.py
import argparse import time from functools import partial import torch from model_zoo import model_builder from torch import nn from colossalai.fx import ColoTracer from colossalai.fx.passes.adding_split_node_pass import gpipe_dp_split_pass, split_with_split_nodes_pass from colossalai.fx.passes.meta_info_prop import MetaInfoProp from colossalai.legacy.pipeline.middleware.adaptor import get_fx_topology from colossalai.legacy.pipeline.rpc._pipeline_schedule import FillDrainPipelineEngine from colossalai.legacy.pipeline.rpc.utils import rpc_run from colossalai.logging import disable_existing_loggers, get_dist_logger def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--model_type", type=str, default="gpt2_medium") parser.add_argument("--world_size", type=int, default=2) parser.add_argument("--batch_size", type=int, default=16) parser.add_argument("--dp_degree", type=int, default=1) parser.add_argument("--tp_degree", type=int, default=1) parser.add_argument("--num_microbatches", type=int, default=2) parser.add_argument("--device", type=str, choices=["cpu", "cuda"], default="cuda") parser.add_argument("--master_addr", type=str, default="localhost") parser.add_argument("--master_port", type=str, default="29011") parser.add_argument("--num_worker_threads", type=int, default=128) return parser.parse_args() class GPTLMLoss(nn.Module): def __init__(self): super().__init__() self.loss_fn = nn.CrossEntropyLoss() def forward(self, logits, labels): shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens return self.loss_fn(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)) # Randomly Generated Data def get_data(batch_size, seq_len, vocab_size): input_ids = torch.randint(0, vocab_size, (batch_size, seq_len), device=torch.cuda.current_device()) attention_mask = torch.ones_like(input_ids) return input_ids, attention_mask def get_tflops(model_numel, batch_size, seq_len, step_time): return model_numel * batch_size * seq_len * 8 / 1e12 / (step_time + 1e-12) # Create annotated model which is noted where to be splitted. def get_annotated_model(model, data_kwargs, num_stages, num_microbatches): tracer = ColoTracer() meta_args = {k: v.to("meta") for k, v in data_kwargs.items()} graph = tracer.trace(root=model, meta_args=meta_args) gm = torch.fx.GraphModule(model, graph, model.__class__.__name__) interp_meta_args = tuple([v.to("meta") for k, v in data_kwargs.items()]) interp = MetaInfoProp(gm) interp.run(*interp_meta_args) # annotated_model = avgnode_split_pass(gm, num_stages) annotated_model = gpipe_dp_split_pass(gm, num_stages, num_microbatches, mode="block", block_limit=0.01) return annotated_model def create_partition_module(pp_rank: int, num_stages: int, model, data_kwargs, num_microbatches): annotated_model = get_annotated_model(model, data_kwargs, num_stages, num_microbatches) top_module, split_submodules = split_with_split_nodes_pass(annotated_model, merge_output=True) topo = get_fx_topology(top_module) for submodule in split_submodules: if isinstance(submodule, torch.fx.GraphModule): setattr(submodule, "_topo", topo) return split_submodules[pp_rank + 1] def partition(model, data_kwargs, num_microbatches, pp_rank: int, chunk: int, stage_num: int): module = create_partition_module(pp_rank, stage_num, model, data_kwargs, num_microbatches) return module def run_master(args): batch_size = args.batch_size device = args.device world_size = args.world_size stage_num = world_size num_microbatches = args.num_microbatches model_type = args.model_type # batch size per DP degree SEQ_LEN = 1024 VOCAB_SIZE = 50257 NUM_STEPS = 10 WARMUP_STEPS = 1 disable_existing_loggers() logger = get_dist_logger() logger.info( f"{args.model_type}, batch size {batch_size}, num stage {stage_num}, num microbatch {num_microbatches}", ranks=[0], ) torch.manual_seed(123) # build criterion criterion = GPTLMLoss() # warm up pipeline fx partition input_ids, attn_mask = get_data(batch_size, SEQ_LEN, VOCAB_SIZE) warmup_data_kwargs = {"input_ids": input_ids, "attention_mask": attn_mask} # create model logger.info(f"start model_builder") model = model_builder(model_type)(checkpoint=False) logger.info(f"end model_builder") # set 1f1b pipeline engine pp_engine = FillDrainPipelineEngine( partition_fn=partial(partition, model, warmup_data_kwargs, num_microbatches), stage_num=stage_num, num_microbatches=num_microbatches, device=device, chunk=1, criterion=criterion, metric=None, checkpoint=False, ) partition_numels = pp_engine.remote_numels() for rank, numel in partition_numels.items(): logger.info(f"{rank=} numel in the partition:{numel}") # build optim pp_engine.initialize_optimizer(torch.optim.Adam, lr=1e-3) ranks_tflops = {} for n in range(NUM_STEPS): # we just use randomly generated data here input_ids, attn_mask = get_data(batch_size, SEQ_LEN, VOCAB_SIZE) batch = {"input_ids": input_ids, "attention_mask": attn_mask} start = time.time() outputs = pp_engine.forward_backward(batch=batch, labels=input_ids, forward_only=False) step_time = time.time() - start for rank, numel in partition_numels.items(): if rank not in ranks_tflops: ranks_tflops[rank] = [] step_tflops = get_tflops(numel, batch_size, SEQ_LEN, step_time) logger.info( f"Rank{rank} , [{n + 1}/{NUM_STEPS}] , Step time: {step_time:.3f}s, TFLOPS: {get_tflops(numel, batch_size, SEQ_LEN, step_time):.3f}", ranks=[0], ) if n >= WARMUP_STEPS: ranks_tflops[rank].append(step_tflops) median_index = ((NUM_STEPS - WARMUP_STEPS) >> 1) + WARMUP_STEPS gpu_tflops = [] for rank, tflops_list in ranks_tflops.items(): tflops_list.sort() gpu_tflops.append(tflops_list[median_index]) logger.info(f"GPU{rank} Median TFLOPS is {tflops_list[median_index]:.3f}") logger.info(f"Total TFLOPS is {sum(gpu_tflops):.3f}") logger.info(f"Avg TFLOPS per GPU is {sum(gpu_tflops) / world_size:.3f}") if __name__ == "__main__": args = parse_args() rpc_run(args, run_master)
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/titans/train_gpt.py
examples/language/gpt/titans/train_gpt.py
import argparse import contextlib import os import torch import torch.nn as nn from dataset.webtext import WebtextDataset from titans.model.gpt import GPTLMLoss import colossalai import colossalai.utils as utils from colossalai.legacy.context.parallel_mode import ParallelMode from colossalai.legacy.core import global_context as gpc from colossalai.legacy.trainer import Trainer, hooks from colossalai.legacy.zero.init_ctx import ZeroInitContext from colossalai.logging import disable_existing_loggers, get_dist_logger from colossalai.nn import LinearWarmupLR from colossalai.utils import is_using_pp from colossalai.utils.timer import MultiTimer def calc_local_model_size(model: torch.nn.Module): numel_per_device = 0 for p in model.parameters(): numel_per_device += p.numel() return numel_per_device VOCAB_SIZE = 50257 def main(): parser = argparse.ArgumentParser() parser.add_argument("--from_torch", default=False, action="store_true") parser.add_argument("--use_dummy_dataset", default=False, action="store_true") args = parser.parse_args() disable_existing_loggers() if args.from_torch: colossalai.launch_from_torch() else: colossalai.launch_from_slurm(host=args.host, port=29500, seed=42) logger = get_dist_logger() data_path = None if args.use_dummy_dataset else os.environ["DATA"] logger.info(f"Build data loader from path {data_path}", ranks=[0]) train_ds = WebtextDataset(path=data_path, seq_len=gpc.config.SEQ_LEN) train_dataloader = utils.get_dataloader( train_ds, seed=42, batch_size=gpc.config.BATCH_SIZE, pin_memory=True, shuffle=True, drop_last=True ) logger.info("Build model", ranks=[0]) use_pipeline = is_using_pp() use_interleaved = hasattr(gpc.config.model, "num_chunks") use_zero3 = hasattr(gpc.config, "zero") ctx = contextlib.nullcontext() if use_zero3: ctx = ZeroInitContext( target_device=torch.cuda.current_device(), shard_strategy=gpc.config.zero.model_config.shard_strategy, shard_param=True, ) with ctx: model = gpc.config.model.pop("type")(**gpc.config.model) if use_pipeline and use_interleaved and not isinstance(model, nn.ModuleList): model = nn.ModuleList([model]) if use_zero3: numel = ctx.model_numel_tensor.item() else: numel = calc_local_model_size(model) tflop = ( numel * gpc.config.BATCH_SIZE * gpc.config.SEQ_LEN * gpc.get_world_size(ParallelMode.MODEL) * gpc.get_world_size(ParallelMode.DATA) * 8 / (1024**4) ) criterion = getattr(gpc.config, "loss_fn", None) if criterion is not None: criterion = criterion.type() else: criterion = GPTLMLoss() logger.info("Build optimizer", ranks=[0]) optimizer = gpc.config.optimizer.pop("type")(model.parameters(), **gpc.config.optimizer) lr_scheduler = LinearWarmupLR(optimizer, total_steps=gpc.config.NUM_EPOCHS, warmup_steps=5) engine, train_dataloader, _, lr_scheduler = colossalai.initialize( model, optimizer, criterion, train_dataloader=train_dataloader, lr_scheduler=lr_scheduler ) global_batch_size = ( gpc.config.BATCH_SIZE * gpc.get_world_size(ParallelMode.DATA) * getattr(gpc.config, "gradient_accumulation", 1) ) logger.info(f"Init done, global batch size = {global_batch_size}", ranks=[0]) timier = MultiTimer() trainer = Trainer(engine=engine, logger=logger, timer=timier) hook_list = [ hooks.LossHook(), hooks.LRSchedulerHook(lr_scheduler=lr_scheduler, by_epoch=True), hooks.LogMetricByEpochHook(logger), hooks.ThroughputHook(ignored_steps=10, tflop_per_step=tflop), hooks.LogMetricByStepHook(), hooks.LogMemoryByEpochHook(logger), # hooks.LogMemoryByEpochHook(logger), # hooks.LogTimingByEpochHook(timer, logger), ] trainer.fit( train_dataloader=train_dataloader, epochs=gpc.config.NUM_EPOCHS, test_interval=1, hooks=hook_list, display_progress=True, return_output_label=False, ) if __name__ == "__main__": main()
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/titans/model/pipeline_gpt1d.py
examples/language/gpt/titans/model/pipeline_gpt1d.py
import inspect # import model_zoo.gpt.gpt as col_gpt import titans.model.gpt.gpt as col_gpt import torch import torch.nn as nn from colossalai import kernel from colossalai import nn as col_nn from colossalai.legacy.context.parallel_mode import ParallelMode from colossalai.legacy.core import global_context as gpc from colossalai.legacy.nn.layer.wrapper import PipelineSharedModuleWrapper from colossalai.legacy.pipeline.utils import partition_uniform from colossalai.logging import get_dist_logger from .embed import HiddenParallelEmbedding, HiddenParallelGPTLMHead1D, VocabParallelEmbedding, VocabParallelGPTLMHead1D from .gpt1d import FusedGPTTransformerLayer1D, GPTTransformerLayer1D __all__ = [ "GPT2_small_pipeline_1D", "GPT2_exlarge_pipeline_1D", "GPT3_pipeline_1D", "GPT2_exlarge_pipeline_hybrid", "GPT2_small_pipeline_hybrid", "GPT3_pipeline_hybrid", ] class GenericPipelineGPT(nn.Module): def __init__(self, embedding=None, blocks=None, norm=None, head=None) -> None: super().__init__() self.embedding = embedding self.blocks = blocks self.norm = norm self.head = head assert blocks is not None if norm is not None or head is not None: assert norm is not None and head is not None def forward(self, hidden_states=None, input_ids=None, attention_mask=None): if self.embedding is not None: hidden_states = self.embedding(input_ids=input_ids) batch_size = hidden_states.shape[0] attention_mask = attention_mask.view(batch_size, -1) attention_mask = attention_mask[:, None, None, :] attention_mask = attention_mask.to(dtype=hidden_states.dtype) # fp16 compatibility attention_mask = (1.0 - attention_mask) * -10000.0 for block in self.blocks: hidden_states, attention_mask = block(hidden_states, attention_mask) if self.norm is not None: hidden_states = self.head(self.norm(hidden_states)) return hidden_states class PipelineGPT1D(GenericPipelineGPT): def __init__( self, num_layers: int = 12, hidden_size: int = 768, num_attention_heads: int = 12, vocab_size: int = 50304, embed_drop_rate: float = 0.0, act_func: str = "gelu", mlp_ratio: int = 4.0, attn_drop_rate: float = 0.0, drop_rate: float = 0.0, dtype: torch.dtype = torch.float, checkpoint: bool = False, max_position_embeddings: int = 1024, layer_norm_epsilon: float = 1e-5, apply_post_layer_norm: bool = False, first: bool = False, last: bool = False, embed_split_hidden=False, ): embedding = None norm = None head = None embed_cls = VocabParallelEmbedding head_cls = VocabParallelGPTLMHead1D if embed_split_hidden: embed_cls = HiddenParallelEmbedding head_cls = HiddenParallelGPTLMHead1D if first: embedding = embed_cls(hidden_size, vocab_size, max_position_embeddings, embed_drop_rate, dtype=dtype) blocks = nn.ModuleList( [ GPTTransformerLayer1D( hidden_size, num_attention_heads, act_func=act_func, mlp_ratio=mlp_ratio, attention_dropout_prob=attn_drop_rate, hidden_dropout_prob=drop_rate, dtype=dtype, checkpoint=checkpoint, max_position_embeddings=max_position_embeddings, layer_norm_epsilon=layer_norm_epsilon, apply_post_layer_norm=apply_post_layer_norm, ) for _ in range(num_layers) ] ) if last: norm = nn.LayerNorm(hidden_size, eps=layer_norm_epsilon) head = head_cls(vocab_size=vocab_size, embed_dim=hidden_size, dtype=dtype) super().__init__(embedding=embedding, blocks=blocks, norm=norm, head=head) class FusedPipelineGPT1D(GenericPipelineGPT): def __init__( self, num_layers: int = 12, hidden_size: int = 768, num_attention_heads: int = 12, vocab_size: int = 50304, embed_drop_rate: float = 0.0, act_func: str = "gelu", mlp_ratio: int = 4.0, attn_drop_rate: float = 0.0, drop_rate: float = 0.0, dtype: torch.dtype = torch.float, checkpoint: bool = False, max_position_embeddings: int = 1024, layer_norm_epsilon: float = 1e-5, apply_post_layer_norm: bool = False, first: bool = False, last: bool = False, embed_split_hidden=False, ): embedding = None norm = None head = None embed_cls = VocabParallelEmbedding head_cls = VocabParallelGPTLMHead1D if embed_split_hidden: embed_cls = HiddenParallelEmbedding head_cls = HiddenParallelGPTLMHead1D if first: embedding = embed_cls(hidden_size, vocab_size, max_position_embeddings, embed_drop_rate, dtype=dtype) blocks = nn.ModuleList( [ FusedGPTTransformerLayer1D( hidden_size, num_attention_heads, act_func=act_func, mlp_ratio=mlp_ratio, attention_dropout_prob=attn_drop_rate, hidden_dropout_prob=drop_rate, dtype=dtype, checkpoint=checkpoint, max_position_embeddings=max_position_embeddings, layer_norm_epsilon=layer_norm_epsilon, apply_post_layer_norm=apply_post_layer_norm, ) for _ in range(num_layers) ] ) if last: norm = kernel.LayerNorm(hidden_size, eps=layer_norm_epsilon) head = head_cls(vocab_size=vocab_size, embed_dim=hidden_size, dtype=dtype) super().__init__(embedding=embedding, blocks=blocks, norm=norm, head=head) def forward(self, hidden_states=None, input_ids=None, attention_mask=None): if self.embedding is not None: hidden_states = self.embedding(input_ids=input_ids) attention_mask = attention_mask.to(dtype=hidden_states.dtype) # fp16 compatibility for block in self.blocks: hidden_states, attention_mask = block(hidden_states, attention_mask) if self.norm is not None: hidden_states = self.head(self.norm(hidden_states)) return hidden_states class PipelineGPTHybrid(GenericPipelineGPT): def __init__( self, num_layers: int = 12, hidden_size: int = 768, num_attention_heads: int = 12, vocab_size: int = 50304, embed_drop_rate: float = 0.0, act_func: str = "gelu", mlp_ratio: int = 4, attn_drop_rate: float = 0.0, drop_rate: float = 0.0, dtype: torch.dtype = torch.float, checkpoint: bool = False, max_position_embeddings: int = 1024, layer_norm_epsilon: float = 1e-5, apply_post_layer_norm: bool = False, first: bool = False, last: bool = False, embed_split_hidden=False, ): embedding = None norm = None head = None if first: embedding = col_gpt.GPTEmbedding( hidden_size, vocab_size, max_position_embeddings, dropout=embed_drop_rate, dtype=dtype ) blocks = nn.ModuleList( [ col_gpt.GPTBlock( hidden_size, num_attention_heads, mlp_ratio=mlp_ratio, attention_dropout=attn_drop_rate, dropout=drop_rate, dtype=dtype, checkpoint=checkpoint, activation=nn.functional.gelu, ) for _ in range(num_layers) ] ) if last: norm = col_nn.LayerNorm(hidden_size, eps=layer_norm_epsilon) # head = col_gpt.GPTLMHead(vocab_size=vocab_size, # hidden_size=hidden_size, # dtype=dtype, # bias=False) head = col_nn.Classifier(hidden_size, vocab_size, dtype=dtype, bias=False) super().__init__(embedding=embedding, blocks=blocks, norm=norm, head=head) def _filter_kwargs(func, kwargs): sig = inspect.signature(func) return {k: v for k, v in kwargs.items() if k in sig.parameters} def _build_generic_gpt_pipeline_1d(module_cls, num_layers, num_chunks, device=torch.device("cuda"), **kwargs): logger = get_dist_logger() if gpc.is_initialized(ParallelMode.PIPELINE): pipeline_size = gpc.get_world_size(ParallelMode.PIPELINE) pipeline_rank = gpc.get_local_rank(ParallelMode.PIPELINE) else: pipeline_size = 1 pipeline_rank = 0 rank = gpc.get_global_rank() if pipeline_size > 1: wrapper = PipelineSharedModuleWrapper([0, pipeline_size - 1]) else: wrapper = None parts = partition_uniform(num_layers, pipeline_size, num_chunks)[pipeline_rank] models = [] for start, end in parts: kwargs["num_layers"] = end - start kwargs["first"] = start == 0 kwargs["last"] = end == num_layers logger.info(f"Rank{rank} build layer {start}-{end}, {end-start}/{num_layers} layers") chunk = module_cls(**_filter_kwargs(module_cls.__init__, kwargs)).to(device) if wrapper is not None: if start == 0: wrapper.register_module(chunk.embedding.word_embeddings) elif end == num_layers: wrapper.register_module(chunk.head) models.append(chunk) if len(models) == 1: model = models[0] else: model = nn.ModuleList(models) numel = 0 for _, param in model.named_parameters(recurse=True): numel += param.numel() logger.info(f"Rank{rank}/{pipeline_rank} model size = {numel * 2 / 1e9} GB") return model def _build_gpt_pipeline_1d(num_layers, num_chunks, device=torch.device("cuda"), fused=False, **kwargs): model = FusedPipelineGPT1D if fused else PipelineGPT1D return _build_generic_gpt_pipeline_1d(model, num_layers, num_chunks, device, **kwargs) def _build_gpt_pipeline_hybrid(num_layers, num_chunks, device=torch.device("cuda"), **kwargs): return _build_generic_gpt_pipeline_1d(PipelineGPTHybrid, num_layers, num_chunks, device, **kwargs) def GPT2_small_pipeline_1D(num_chunks=1, checkpoint=False, dtype=torch.float, embed_split_hidden=False, fused=False): cfg = dict( hidden_size=768, num_attention_heads=12, checkpoint=checkpoint, dtype=dtype, embed_split_hidden=embed_split_hidden, ) return _build_gpt_pipeline_1d(12, num_chunks, fused=fused, **cfg) def GPT2_exlarge_pipeline_1D(num_chunks=1, checkpoint=False, dtype=torch.float, embed_split_hidden=False, fused=False): cfg = dict( hidden_size=1600, num_attention_heads=32, checkpoint=checkpoint, dtype=dtype, embed_split_hidden=embed_split_hidden, ) return _build_gpt_pipeline_1d(48, num_chunks, fused=fused, **cfg) def GPT3_pipeline_1D(num_chunks=1, checkpoint=False, dtype=torch.float, embed_split_hidden=False, fused=False): cfg = dict( hidden_size=12288, num_attention_heads=96, checkpoint=checkpoint, max_position_embeddings=2048, dtype=dtype, embed_split_hidden=embed_split_hidden, ) return _build_gpt_pipeline_1d(96, num_chunks, fused=fused, **cfg) def GPT2_exlarge_pipeline_hybrid(num_chunks=1, checkpoint=False, dtype=torch.float, embed_split_hidden=False): cfg = dict( hidden_size=1600, num_attention_heads=32, checkpoint=checkpoint, dtype=dtype, embed_split_hidden=embed_split_hidden, ) return _build_gpt_pipeline_hybrid(48, num_chunks, **cfg) def GPT2_small_pipeline_hybrid(num_chunks=1, checkpoint=False, dtype=torch.float, embed_split_hidden=False): cfg = dict( hidden_size=768, num_attention_heads=12, checkpoint=checkpoint, dtype=dtype, embed_split_hidden=embed_split_hidden, ) return _build_gpt_pipeline_hybrid(12, num_chunks, **cfg) def GPT3_pipeline_hybrid(num_chunks=1, checkpoint=False, dtype=torch.float, embed_split_hidden=False): cfg = dict( hidden_size=12288, num_attention_heads=96, checkpoint=checkpoint, max_position_embeddings=2048, dtype=dtype, embed_split_hidden=embed_split_hidden, ) return _build_gpt_pipeline_hybrid(96, num_chunks, **cfg)
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/titans/model/embed.py
examples/language/gpt/titans/model/embed.py
import torch import torch.nn.init as init from torch import Tensor from torch import nn as nn from torch.nn import functional as F from torch.nn.parameter import Parameter from colossalai.accelerator import get_accelerator from colossalai.legacy.context import ParallelMode, seed from colossalai.legacy.core import global_context as gpc from colossalai.legacy.nn.layer.base_layer import ParallelLayer from colossalai.legacy.nn.layer.parallel_1d._utils import gather_forward_split_backward, reduce_grad, reduce_input from colossalai.legacy.nn.layer.parallel_1d.layers import Linear1D_Row from colossalai.legacy.nn.layer.utils import divide from colossalai.legacy.registry import LAYERS, LOSSES class VocabParallelEmbedding(torch.nn.Module): """Language model embeddings. Arguments: hidden_size: hidden size vocab_size: vocabulary size max_sequence_length: maximum size of sequence. This is used for positional embedding embedding_dropout_prob: dropout probability for embeddings init_method: weight initialization method num_tokentypes: size of the token-type embeddings. 0 value will ignore this embedding """ def __init__( self, hidden_size, vocab_size, max_sequence_length, embedding_dropout_prob, num_tokentypes=0, dtype=torch.float ): super(VocabParallelEmbedding, self).__init__() self.hidden_size = hidden_size self.num_tokentypes = num_tokentypes # Word embeddings (parallel). self.word_embeddings = VocabParallelEmbedding1D(vocab_size, self.hidden_size, dtype=dtype) self._word_embeddings_key = "word_embeddings" # Position embedding (serial). self.position_embeddings = torch.nn.Embedding(max_sequence_length, self.hidden_size, dtype=dtype) self._position_embeddings_key = "position_embeddings" # Initialize the position embeddings. # self.init_method(self.position_embeddings.weight) # Token type embedding. # Add this as an optional field that can be added through # method call so we can load a pretrain model without # token types and add them as needed. self._tokentype_embeddings_key = "tokentype_embeddings" if self.num_tokentypes > 0: self.tokentype_embeddings = torch.nn.Embedding(self.num_tokentypes, self.hidden_size, dtype=dtype) # Initialize the token-type embeddings. # self.init_method(self.tokentype_embeddings.weight) else: self.tokentype_embeddings = None # Embeddings dropout self.embedding_dropout = torch.nn.Dropout(embedding_dropout_prob) def zero_parameters(self): """Zero out all parameters in embedding.""" self.word_embeddings.weight.data.fill_(0) self.word_embeddings.weight.shared = True self.position_embeddings.weight.data.fill_(0) self.position_embeddings.weight.shared = True if self.num_tokentypes > 0: self.tokentype_embeddings.weight.data.fill_(0) self.tokentype_embeddings.weight.shared = True def add_tokentype_embeddings(self, num_tokentypes): """Add token-type embedding. This function is provided so we can add token-type embeddings in case the pretrained model does not have it. This allows us to load the model normally and then add this embedding. """ if self.tokentype_embeddings is not None: raise Exception("tokentype embeddings is already initialized") if torch.distributed.get_rank() == 0: print("adding embedding for {} tokentypes".format(num_tokentypes), flush=True) self.num_tokentypes = num_tokentypes self.tokentype_embeddings = torch.nn.Embedding(num_tokentypes, self.hidden_size) # Initialize the token-type embeddings. # self.init_method(self.tokentype_embeddings.weight) def forward(self, input_ids, position_ids=None, tokentype_ids=None): # Embeddings. if input_ids is not None: input_shape = input_ids.size() input_ids = input_ids.view(-1, input_shape[-1]) words_embeddings = self.word_embeddings(input_ids) if position_ids is not None: position_ids = position_ids.view(-1, input_shape[-1]) if position_ids is None: position_ids = torch.arange( 0, input_shape[-1] + 0, dtype=torch.long, device=get_accelerator().get_current_device() ) position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1]) position_embeddings = self.position_embeddings(position_ids) embeddings = words_embeddings + position_embeddings # Dropout. with seed(ParallelMode.TENSOR): embeddings = self.embedding_dropout(embeddings) return embeddings def state_dict_for_save_checkpoint(self, destination=None, prefix="", keep_vars=False): """For easy load.""" state_dict_ = {} state_dict_[self._word_embeddings_key] = self.word_embeddings.state_dict(destination, prefix, keep_vars) state_dict_[self._position_embeddings_key] = self.position_embeddings.state_dict(destination, prefix, keep_vars) if self.num_tokentypes > 0: state_dict_[self._tokentype_embeddings_key] = self.tokentype_embeddings.state_dict( destination, prefix, keep_vars ) return state_dict_ def load_state_dict(self, state_dict, strict=True): """Customized load.""" # Word embedding. if self._word_embeddings_key in state_dict: state_dict_ = state_dict[self._word_embeddings_key] else: # for backward compatibility. state_dict_ = {} for key in state_dict.keys(): if "word_embeddings" in key: state_dict_[key.split("word_embeddings.")[1]] = state_dict[key] self.word_embeddings.load_state_dict(state_dict_, strict=strict) # Position embedding. if self._position_embeddings_key in state_dict: state_dict_ = state_dict[self._position_embeddings_key] else: # for backward compatibility. state_dict_ = {} for key in state_dict.keys(): if "position_embeddings" in key: state_dict_[key.split("position_embeddings.")[1]] = state_dict[key] self.position_embeddings.load_state_dict(state_dict_, strict=strict) # Tokentype embedding. if self.num_tokentypes > 0: state_dict_ = {} if self._tokentype_embeddings_key in state_dict: state_dict_ = state_dict[self._tokentype_embeddings_key] else: # for backward compatibility. for key in state_dict.keys(): if "tokentype_embeddings" in key: state_dict_[key.split("tokentype_embeddings.")[1]] = state_dict[key] if len(state_dict_.keys()) > 0: self.tokentype_embeddings.load_state_dict(state_dict_, strict=strict) else: print( "***WARNING*** expected tokentype embeddings in the " "checkpoint but could not find it", flush=True ) class VocabParallelEmbedding1D(torch.nn.Module): """Embedding parallelized in the vocabulary dimension. This is mainly adapted from torch.nn.Embedding and all the default values are kept. Arguments: num_embeddings: vocabulary size. embedding_dim: size of hidden state. init_method: method to initialize weights. """ def __init__(self, num_embeddings, embedding_dim, dtype=None, init_method=None): super(VocabParallelEmbedding1D, self).__init__() # Keep the input dimensions. self.num_embeddings = num_embeddings self.embedding_dim = embedding_dim # Set the details for compatibility. self.padding_idx = None self.max_norm = None self.norm_type = 2.0 self.scale_grad_by_freq = False self.sparse = False self._weight = None self.tensor_model_parallel_size = gpc.tensor_parallel_size # Divide the weight matrix along the vocabulary dimension. self.vocab_start_index, self.vocab_end_index = VocabUtility.vocab_range_from_global_vocab_size( self.num_embeddings, gpc.get_local_rank(ParallelMode.PARALLEL_1D), self.tensor_model_parallel_size ) self.num_embeddings_per_partition = self.vocab_end_index - self.vocab_start_index # Allocate weights and initialize. factory_kwargs = {"device": get_accelerator().get_current_device(), "dtype": dtype} self.weight = Parameter(torch.empty(self.num_embeddings_per_partition, self.embedding_dim, **factory_kwargs)) init.uniform_(self.weight, -1, 1) def forward(self, input_): if self.tensor_model_parallel_size > 1: # Build the mask. input_mask = (input_ < self.vocab_start_index) | (input_ >= self.vocab_end_index) # Mask the input. masked_input = input_.clone() - self.vocab_start_index masked_input[input_mask] = 0 else: masked_input = input_ # Get the embeddings. output_parallel = F.embedding( masked_input, self.weight, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse, ) # Mask the output embedding. if self.tensor_model_parallel_size > 1: output_parallel[input_mask, :] = 0.0 # Reduce across all the model parallel GPUs. output = output = reduce_input(output_parallel, ParallelMode.PARALLEL_1D) return output @LOSSES.register_module class vocab_parallel_cross_entropy(nn.Module): def __init__(self): super().__init__() def forward(self, vocab_parallel_logits, target): """Helper function for the cross entropy.""" vocab_parallel_logits = vocab_parallel_logits[..., :-1, :].contiguous() target = target[..., 1:].contiguous() return _VocabParallelCrossEntropy.apply( vocab_parallel_logits.view(-1, vocab_parallel_logits.size(-1)), target.view(-1) ) class _VocabParallelCrossEntropy(torch.autograd.Function): @staticmethod def forward(ctx, vocab_parallel_logits, target): # Maximum value along vocab dimension across all GPUs. logits_max = torch.max(vocab_parallel_logits, dim=-1)[0] torch.distributed.all_reduce( logits_max, op=torch.distributed.ReduceOp.MAX, group=gpc.get_group(ParallelMode.PARALLEL_1D) ) # Subtract the maximum value. vocab_parallel_logits.sub_(logits_max.unsqueeze(dim=-1)) # Get the partition's vocab indices get_vocab_range = VocabUtility.vocab_range_from_per_partition_vocab_size partition_vocab_size = vocab_parallel_logits.size()[-1] rank = gpc.get_local_rank(ParallelMode.PARALLEL_1D) world_size = gpc.tensor_parallel_size vocab_start_index, vocab_end_index = get_vocab_range(partition_vocab_size, rank, world_size) # Create a mask of valid vocab ids (1 means it needs to be masked). target_mask = (target < vocab_start_index) | (target >= vocab_end_index) masked_target = target.clone() - vocab_start_index masked_target[target_mask] = 0 # Get predicted-logits = logits[target]. # For Simplicity, we convert logits to a 2-D tensor with size # [*, partition-vocab-size] and target to a 1-D tensor of size [*]. logits_2d = vocab_parallel_logits.view(-1, partition_vocab_size) masked_target_1d = masked_target.view(-1) arange_1d = torch.arange(start=0, end=logits_2d.size()[0], device=logits_2d.device) predicted_logits_1d = logits_2d[arange_1d, masked_target_1d] predicted_logits_1d = predicted_logits_1d.clone().contiguous() predicted_logits = predicted_logits_1d.view_as(target) predicted_logits[target_mask] = 0.0 # All reduce is needed to get the chunks from other GPUs. torch.distributed.all_reduce( predicted_logits, op=torch.distributed.ReduceOp.SUM, group=gpc.get_group(ParallelMode.PARALLEL_1D) ) # Sum of exponential of logits along vocab dimension across all GPUs. exp_logits = vocab_parallel_logits torch.exp(vocab_parallel_logits, out=exp_logits) sum_exp_logits = exp_logits.sum(dim=-1) torch.distributed.all_reduce( sum_exp_logits, op=torch.distributed.ReduceOp.SUM, group=gpc.get_group(ParallelMode.PARALLEL_1D) ) # Loss = log(sum(exp(logits))) - predicted-logit. loss = torch.log(sum_exp_logits) - predicted_logits loss = loss.mean() # Store softmax, target-mask and masked-target for backward pass. exp_logits.div_(sum_exp_logits.unsqueeze(dim=-1)) ctx.save_for_backward(exp_logits, target_mask, masked_target_1d) return loss @staticmethod def backward(ctx, grad_output): # Retrieve tensors from the forward path. softmax, target_mask, masked_target_1d = ctx.saved_tensors # All the inputs have softmax as their gradient. grad_input = softmax # For simplicity, work with the 2D gradient. partition_vocab_size = softmax.size()[-1] grad_2d = grad_input.view(-1, partition_vocab_size) # Add the gradient from matching classes. arange_1d = torch.arange(start=0, end=grad_2d.size()[0], device=grad_2d.device) grad_2d[arange_1d, masked_target_1d] -= 1.0 - target_mask.view(-1).float() # Finally elementwise multiplication with the output gradients. grad_input.mul_(grad_output.unsqueeze(dim=-1)) return grad_input, None class VocabUtility: """Split the vocabulary into `world_size` chunks amd return the first and last index of the vocabulary belonging to the `rank` partition: Note that indices in [fist, last)""" @staticmethod def vocab_range_from_per_partition_vocab_size(per_partition_vocab_size, rank, world_size): index_f = rank * per_partition_vocab_size index_l = index_f + per_partition_vocab_size return index_f, index_l @staticmethod def vocab_range_from_global_vocab_size(global_vocab_size, rank, world_size): per_partition_vocab_size = divide(global_vocab_size, world_size) return VocabUtility.vocab_range_from_per_partition_vocab_size(per_partition_vocab_size, rank, world_size) class VocabParallelGPTLMHead1D(ParallelLayer): """ Language model head that shares the same parameters with the embedding matrix. """ def __init__(self, embed=None, vocab_size=None, dtype=None, embed_dim=None): super().__init__() if embed is not None: self.head = embed else: self.head = VocabParallelEmbedding1D(vocab_size, embed_dim, dtype=dtype) def forward(self, x: Tensor) -> Tensor: x = reduce_grad(x, ParallelMode.PARALLEL_1D) x = F.linear(x, self.head.weight) return x ################################### class HiddenParallelEmbedding(torch.nn.Module): """Language model embeddings. Arguments: hidden_size: hidden size vocab_size: vocabulary size max_sequence_length: maximum size of sequence. This is used for positional embedding embedding_dropout_prob: dropout probability for embeddings init_method: weight initialization method num_tokentypes: size of the token-type embeddings. 0 value will ignore this embedding """ def __init__( self, hidden_size, vocab_size, max_sequence_length, embedding_dropout_prob, dtype=torch.float, padding_idx: int = 0, num_tokentypes=0, ): super(HiddenParallelEmbedding, self).__init__() self.hidden_size = hidden_size self.num_tokentypes = num_tokentypes # Word embeddings (parallel). self.word_embeddings = HiddenParallelEmbedding1D(vocab_size, hidden_size, dtype, padding_idx) self._word_embeddings_key = "word_embeddings" # Position embedding (serial). self.position_embeddings = torch.nn.Embedding(max_sequence_length, self.hidden_size) self._position_embeddings_key = "position_embeddings" # Initialize the position embeddings. # self.init_method(self.position_embeddings.weight) # Token type embedding. # Add this as an optional field that can be added through # method call so we can load a pretrain model without # token types and add them as needed. self._tokentype_embeddings_key = "tokentype_embeddings" if self.num_tokentypes > 0: self.tokentype_embeddings = torch.nn.Embedding(self.num_tokentypes, self.hidden_size) # Initialize the token-type embeddings. # self.init_method(self.tokentype_embeddings.weight) else: self.tokentype_embeddings = None # Embeddings dropout self.embedding_dropout = torch.nn.Dropout(embedding_dropout_prob) def zero_parameters(self): """Zero out all parameters in embedding.""" self.word_embeddings.weight.data.fill_(0) self.word_embeddings.weight.shared = True self.position_embeddings.weight.data.fill_(0) self.position_embeddings.weight.shared = True if self.num_tokentypes > 0: self.tokentype_embeddings.weight.data.fill_(0) self.tokentype_embeddings.weight.shared = True def add_tokentype_embeddings(self, num_tokentypes): """Add token-type embedding. This function is provided so we can add token-type embeddings in case the pretrained model does not have it. This allows us to load the model normally and then add this embedding. """ if self.tokentype_embeddings is not None: raise Exception("tokentype embeddings is already initialized") if torch.distributed.get_rank() == 0: print("adding embedding for {} tokentypes".format(num_tokentypes), flush=True) self.num_tokentypes = num_tokentypes self.tokentype_embeddings = torch.nn.Embedding(num_tokentypes, self.hidden_size) # Initialize the token-type embeddings. # self.init_method(self.tokentype_embeddings.weight) def forward(self, input_ids, position_ids=None, tokentype_ids=None): if input_ids is not None: input_shape = input_ids.size() input_ids = input_ids.view(-1, input_shape[-1]) words_embeddings = self.word_embeddings(input_ids) if position_ids is not None: position_ids = position_ids.view(-1, input_shape[-1]) if position_ids is None: position_ids = torch.arange( 0, input_shape[-1] + 0, dtype=torch.long, device=get_accelerator().get_current_device() ) position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1]) position_embeddings = self.position_embeddings(position_ids) embeddings = words_embeddings + position_embeddings # Dropout. with seed(ParallelMode.TENSOR): embeddings = self.embedding_dropout(embeddings) return embeddings def state_dict_for_save_checkpoint(self, destination=None, prefix="", keep_vars=False): """For easy load.""" state_dict_ = {} state_dict_[self._word_embeddings_key] = self.word_embeddings.state_dict(destination, prefix, keep_vars) state_dict_[self._position_embeddings_key] = self.position_embeddings.state_dict(destination, prefix, keep_vars) if self.num_tokentypes > 0: state_dict_[self._tokentype_embeddings_key] = self.tokentype_embeddings.state_dict( destination, prefix, keep_vars ) return state_dict_ def load_state_dict(self, state_dict, strict=True): """Customized load.""" # Word embedding. if self._word_embeddings_key in state_dict: state_dict_ = state_dict[self._word_embeddings_key] else: # for backward compatibility. state_dict_ = {} for key in state_dict.keys(): if "word_embeddings" in key: state_dict_[key.split("word_embeddings.")[1]] = state_dict[key] self.word_embeddings.load_state_dict(state_dict_, strict=strict) # Position embedding. if self._position_embeddings_key in state_dict: state_dict_ = state_dict[self._position_embeddings_key] else: # for backward compatibility. state_dict_ = {} for key in state_dict.keys(): if "position_embeddings" in key: state_dict_[key.split("position_embeddings.")[1]] = state_dict[key] self.position_embeddings.load_state_dict(state_dict_, strict=strict) # Tokentype embedding. if self.num_tokentypes > 0: state_dict_ = {} if self._tokentype_embeddings_key in state_dict: state_dict_ = state_dict[self._tokentype_embeddings_key] else: # for backward compatibility. for key in state_dict.keys(): if "tokentype_embeddings" in key: state_dict_[key.split("tokentype_embeddings.")[1]] = state_dict[key] if len(state_dict_.keys()) > 0: self.tokentype_embeddings.load_state_dict(state_dict_, strict=strict) else: print( "***WARNING*** expected tokentype embeddings in the " "checkpoint but could not find it", flush=True ) class HiddenParallelEmbedding1D(torch.nn.Module): """Embedding parallelized in the vocabulary dimension. This is mainly adapted from torch.nn.Embedding and all the default values are kept. Arguments: num_embeddings: vocabulary size. embedding_dim: size of hidden state. init_method: method to initialize weights. """ def __init__(self, num_embeddings, embedding_dim, dtype=torch.float, padding_idx: int = None, init_method=None): super(HiddenParallelEmbedding1D, self).__init__() # Keep the input dimensions. self.num_embeddings = num_embeddings self.embedding_dim = embedding_dim embed_dim_per_partition = divide(embedding_dim, gpc.tensor_parallel_size) # Set the details for compatibility. self.padding_idx = padding_idx self.max_norm = None self.norm_type = 2.0 self.scale_grad_by_freq = False self.sparse = False self._weight = None # Allocate weights and initialize. factory_kwargs = {"device": get_accelerator().get_current_device(), "dtype": dtype} self.weight = Parameter(torch.empty(num_embeddings, embed_dim_per_partition, **factory_kwargs)) init.uniform_(self.weight, -1, 1) def forward(self, input_): # Get the embeddings. output_parallel = F.embedding( input_, self.weight, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse ) # Reduce across all the model parallel GPUs. output = gather_forward_split_backward(output_parallel, ParallelMode.PARALLEL_1D, dim=-1) return output @LAYERS.register_module class HiddenParallelGPTLMHead1D(ParallelLayer): """ Language model head that shares the same parameters with the embedding matrix. """ def __init__( self, embed=None, embed_dim=None, vocab_size=None, dtype=None, ): super().__init__() if embed is not None: self.head = embed self.synced_embed = True else: # self.embedding = HiddenParallelEmbedding1D(vocab_size, hidden_size, dtype, padding_idx) # (hidden_size/q, vocab_size) self.synced_embed = False self.head = Linear1D_Row( in_features=embed_dim, out_features=vocab_size, bias=False, dtype=dtype, parallel_input=False ) def forward(self, x: Tensor) -> Tensor: if self.synced_embed: x = F.linear(x, self.head.weight) else: x = self.head(x) return x
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/titans/model/gpt1d.py
examples/language/gpt/titans/model/gpt1d.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- import math import torch from torch import Tensor from torch import nn as nn from colossalai import kernel from colossalai import nn as col_nn from colossalai.kernel.cuda_native.scaled_softmax import AttnMaskType from colossalai.legacy.core import global_context as gpc from colossalai.legacy.nn.layer import Linear1D_Col, Linear1D_Row from colossalai.legacy.nn.layer.base_layer import ParallelLayer from colossalai.legacy.nn.layer.utils import ACT2FN, divide from colossalai.legacy.utils.activation_checkpoint import checkpoint from colossalai.utils import checkpoint __all__ = [ "GPTMLP1D", "GPTSelfAttention1D", "GPTTransformerLayer1D", "FusedGPTSelfAttention1D", "FusedGPTTransformerLayer1D", ] class GPTMLP1D(ParallelLayer): def __init__( self, in_features: int, mlp_ratio: int, act_func: str = "gelu", dropout_prob: float = 0.0, dtype=None, checkpoint: bool = False, skip_bias_add: bool = False, ): super().__init__() self.in_features = in_features self.mlp_ratio = mlp_ratio self.checkpoint = checkpoint self.skip_bias_add = skip_bias_add self.act = ACT2FN[act_func] skip_dense_1_add_bias = False # Project to mlp_ratio * h. self.dense_1 = Linear1D_Col( self.in_features, int(self.mlp_ratio * self.in_features), dtype=dtype, gather_output=False, skip_bias_add=skip_dense_1_add_bias, ) # Project back to h. self.dense_2 = Linear1D_Row( int(self.mlp_ratio * self.in_features), self.in_features, dtype=dtype, parallel_input=True, ) self.dropout = col_nn.Dropout(dropout_prob) def _forward(self, hidden_states: Tensor) -> Tensor: intermediate_output = self.dense_1(hidden_states) intermediate_output = self.act(intermediate_output) output = self.dense_2(intermediate_output) output = self.dropout(output) return output def _checkpoint_forward(self, hidden_states: Tensor) -> Tensor: return checkpoint(self._forward, False, hidden_states) def forward(self, hidden_states: Tensor) -> Tensor: if self.checkpoint: return self._checkpoint_forward(hidden_states) else: return self._forward(hidden_states) class GenericGPTSelfAttention1D(ParallelLayer): def __init__( self, hidden_size: int, num_attention_heads: int, attention_dropout_prob: float, hidden_dropout_prob: float, dtype=None, checkpoint: bool = False, max_position_embeddings=1024, ): super().__init__() self.hidden_size = hidden_size self.attention_head_size = divide(hidden_size, num_attention_heads) self.num_attention_heads_per_partition = divide(num_attention_heads, gpc.tensor_parallel_size) self.hidden_size_per_partition = divide(hidden_size, gpc.tensor_parallel_size) self.checkpoint = checkpoint self.query_key_value = Linear1D_Col( hidden_size, 3 * hidden_size, dtype=dtype, ) self.attention_dropout = col_nn.Dropout(attention_dropout_prob) self.dense = Linear1D_Row( hidden_size, hidden_size, dtype=dtype, parallel_input=True, ) self.dropout = col_nn.Dropout(hidden_dropout_prob) def softmax_forward(self, attention_scores, attention_mask, query_layer, key_layer): raise NotImplementedError def _forward(self, hidden_states: Tensor, attention_mask=None) -> Tensor: query_key_value = self.query_key_value(hidden_states) new_qkv_shape = query_key_value.shape[:-1] + ( self.num_attention_heads_per_partition, 3 * self.attention_head_size, ) query_key_value = query_key_value.view(new_qkv_shape) query_key_value = query_key_value.permute((0, 2, 1, 3)) query_layer, key_layer, value_layer = torch.chunk(query_key_value, 3, dim=-1) attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = self.softmax_forward(attention_scores, attention_mask, query_layer, key_layer) attention_scores = attention_scores.type(value_layer.dtype) attention_probs = self.attention_dropout(attention_scores) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.transpose(1, 2) new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,) context_layer = context_layer.reshape(new_context_layer_shape) output = self.dense(context_layer) output = self.dropout(output) return output def _checkpoint_forward(self, hidden_states: Tensor, attention_mask=None) -> Tensor: return checkpoint(self._forward, False, hidden_states, attention_mask) def forward(self, hidden_states: Tensor, attention_mask=None) -> Tensor: if self.checkpoint: return self._checkpoint_forward(hidden_states, attention_mask) else: return self._forward(hidden_states, attention_mask) class GPTSelfAttention1D(GenericGPTSelfAttention1D): def __init__( self, hidden_size: int, num_attention_heads: int, attention_dropout_prob: float, hidden_dropout_prob: float, dtype=None, checkpoint: bool = False, max_position_embeddings=1024, ): super().__init__( hidden_size, num_attention_heads, attention_dropout_prob, hidden_dropout_prob, dtype=dtype, checkpoint=checkpoint, max_position_embeddings=max_position_embeddings, ) self.softmax = nn.Softmax(dim=-1) max_positions = max_position_embeddings self.register_buffer( "bias", torch.tril(torch.ones((max_positions, max_positions), dtype=torch.uint8)).view( 1, 1, max_positions, max_positions ), ) self.register_buffer("masked_bias", torch.tensor(-1e4)) def softmax_forward(self, attention_scores, attention_mask, query_layer, key_layer): attention_scores = attention_scores / math.sqrt(self.attention_head_size) # causal mask query_length, key_length = query_layer.size(-2), key_layer.size(-2) causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length].bool() attention_scores = torch.where(causal_mask, attention_scores, self.masked_bias.to(attention_scores)) if attention_mask is not None: # Apply the attention mask attention_scores = attention_scores + attention_mask attention_scores = self.softmax(attention_scores) return attention_scores class FusedGPTSelfAttention1D(GenericGPTSelfAttention1D): def __init__( self, hidden_size: int, num_attention_heads: int, attention_dropout_prob: float, hidden_dropout_prob: float, dtype=None, checkpoint: bool = False, max_position_embeddings=1024, ): super().__init__( hidden_size, num_attention_heads, attention_dropout_prob, hidden_dropout_prob, dtype=dtype, checkpoint=checkpoint, max_position_embeddings=max_position_embeddings, ) self.softmax = kernel.FusedScaleMaskSoftmax( input_in_fp16=True, input_in_bf16=False, attn_mask_type=AttnMaskType.causal, scaled_masked_softmax_fusion=True, mask_func=None, softmax_in_fp32=True, scale=math.sqrt(self.attention_head_size), ) def softmax_forward(self, attention_scores, attention_mask, query_layer, key_layer): return self.softmax(attention_scores, attention_mask) class GenericGPTTransformerLayer1D(ParallelLayer): def __init__( self, hidden_size: int, num_attention_heads: int, act_func: str = "gelu", mlp_ratio: float = 4.0, attention_dropout_prob: float = 0.0, hidden_dropout_prob: float = 0.0, dtype=None, checkpoint: bool = False, max_position_embeddings: int = 1024, layer_norm_epsilon: float = 1e-5, apply_post_layer_norm: bool = False, attention=None, layer_norm=None, ): super().__init__() self.checkpoint = checkpoint self.dtype = dtype self.norm1 = layer_norm(hidden_size, eps=layer_norm_epsilon) self.apply_post_layer_norm = apply_post_layer_norm self.attention = attention( hidden_size=hidden_size, num_attention_heads=num_attention_heads, attention_dropout_prob=attention_dropout_prob, hidden_dropout_prob=hidden_dropout_prob, dtype=dtype, max_position_embeddings=max_position_embeddings, checkpoint=False, ) self.norm2 = layer_norm(hidden_size, eps=layer_norm_epsilon) self.mlp = GPTMLP1D( in_features=hidden_size, dropout_prob=hidden_dropout_prob, act_func=act_func, mlp_ratio=mlp_ratio, dtype=dtype, checkpoint=False, ) def _forward(self, hidden_states, attention_mask) -> Tensor: if not self.apply_post_layer_norm: residual = hidden_states hidden_states = self.norm1(hidden_states) if self.apply_post_layer_norm: residual = hidden_states attention_output = self.attention(hidden_states, attention_mask) hidden_states = residual + attention_output if not self.apply_post_layer_norm: residual = hidden_states hidden_states = self.norm2(hidden_states) if self.apply_post_layer_norm: residual = hidden_states feed_forward_hidden_states = self.mlp(hidden_states) hidden_states = residual + feed_forward_hidden_states output = (hidden_states, attention_mask) return output def forward(self, hidden_states, attention_mask): if self.checkpoint: return checkpoint(self._forward, False, hidden_states, attention_mask) else: return self._forward(hidden_states, attention_mask) class GPTTransformerLayer1D(GenericGPTTransformerLayer1D): def __init__( self, hidden_size: int, num_attention_heads: int, act_func: str = "gelu", mlp_ratio: float = 4, attention_dropout_prob: float = 0, hidden_dropout_prob: float = 0, dtype=None, checkpoint: bool = False, max_position_embeddings: int = 1024, layer_norm_epsilon: float = 0.00001, apply_post_layer_norm: bool = False, ): attention = GPTSelfAttention1D layer_norm = nn.LayerNorm super().__init__( hidden_size, num_attention_heads, act_func=act_func, mlp_ratio=mlp_ratio, attention_dropout_prob=attention_dropout_prob, hidden_dropout_prob=hidden_dropout_prob, dtype=dtype, checkpoint=checkpoint, max_position_embeddings=max_position_embeddings, layer_norm_epsilon=layer_norm_epsilon, apply_post_layer_norm=apply_post_layer_norm, attention=attention, layer_norm=layer_norm, ) class FusedGPTTransformerLayer1D(GenericGPTTransformerLayer1D): def __init__( self, hidden_size: int, num_attention_heads: int, act_func: str = "gelu", mlp_ratio: float = 4, attention_dropout_prob: float = 0, hidden_dropout_prob: float = 0, dtype=None, checkpoint: bool = False, max_position_embeddings: int = 1024, layer_norm_epsilon: float = 0.00001, apply_post_layer_norm: bool = False, ): attention = FusedGPTSelfAttention1D layer_norm = kernel.LayerNorm super().__init__( hidden_size, num_attention_heads, act_func=act_func, mlp_ratio=mlp_ratio, attention_dropout_prob=attention_dropout_prob, hidden_dropout_prob=hidden_dropout_prob, dtype=dtype, checkpoint=checkpoint, max_position_embeddings=max_position_embeddings, layer_norm_epsilon=layer_norm_epsilon, apply_post_layer_norm=apply_post_layer_norm, attention=attention, layer_norm=layer_norm, )
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/titans/model/__init__.py
examples/language/gpt/titans/model/__init__.py
from .embed import vocab_parallel_cross_entropy from .gpt1d import * from .pipeline_gpt1d import *
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/titans/dataset/webtext.py
examples/language/gpt/titans/dataset/webtext.py
import json import os from typing import Optional import torch from torch.utils.data import Dataset from transformers import GPT2Tokenizer from colossalai.legacy.registry import DATASETS @DATASETS.register_module class WebtextDataset(Dataset): def __init__(self, path: Optional[str] = None, seq_len=1024) -> None: super().__init__() if path is not None: root = os.path.dirname(path) encoded_data_cache_path = os.path.join(root, f"gpt_webtext_{seq_len}.pt") if os.path.isfile(encoded_data_cache_path): seq_len_, data, attention_mask = torch.load(encoded_data_cache_path) if seq_len_ == seq_len: self.data = data self.attention_mask = attention_mask return raw_data = [] with open(path) as f: for line in f.readlines(): raw_data.append(json.loads(line)["text"]) tokenizer = GPT2Tokenizer.from_pretrained("gpt2") tokenizer.pad_token = tokenizer.unk_token encoded_data = tokenizer(raw_data, padding=True, truncation=True, max_length=seq_len, return_tensors="pt") self.data = encoded_data["input_ids"] self.attention_mask = encoded_data["attention_mask"] else: self.data = torch.randint(0, 50257, (10240, seq_len)) self.attention_mask = torch.ones_like(self.data) def __len__(self): return len(self.data) def __getitem__(self, index): return {"input_ids": self.data[index], "attention_mask": self.attention_mask[index]}, self.data[index]
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/titans/configs/gpt3_zero3_pp1d.py
examples/language/gpt/titans/configs/gpt3_zero3_pp1d.py
from model import GPT3_pipeline_hybrid from colossalai.nn.optimizer import HybridAdam from colossalai.zero.shard_utils import TensorShardStrategy BATCH_SIZE = 192 NUM_EPOCHS = 60 SEQ_LEN = 2048 NUM_MICRO_BATCHES = 192 HIDDEN_SIZE = 12288 TENSOR_SHAPE = (BATCH_SIZE // NUM_MICRO_BATCHES, SEQ_LEN, HIDDEN_SIZE) # if you do no want zero, just comment out this dictionary zero = dict( model_config=dict(tensor_placement_policy="cuda", shard_strategy=TensorShardStrategy()), optimizer_config=dict(initial_scale=2**16), ) optimizer = dict( type=HybridAdam, lr=0.00015, weight_decay=1e-2, ) model = dict(type=GPT3_pipeline_hybrid, checkpoint=True, num_chunks=1) # pipeline parallel: modify integer value for the number of pipeline stages # tensor parallel: modify size to set the tensor parallel size, usually the number of GPUs per node # for the current model implementation, mode can only be 1D or None parallel = dict( pipeline=1, tensor=dict(size=2, mode="1d"), # for the current model implementation, mode can only be 1D or None )
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/titans/configs/gpt2_small_zero3_pp1d.py
examples/language/gpt/titans/configs/gpt2_small_zero3_pp1d.py
from model import GPT2_small_pipeline_hybrid from colossalai.nn.optimizer import HybridAdam from colossalai.zero.shard_utils import TensorShardStrategy BATCH_SIZE = 8 NUM_EPOCHS = 10 SEQ_LEN = 1024 NUM_MICRO_BATCHES = 4 HIDDEN_SIZE = 768 TENSOR_SHAPE = (BATCH_SIZE // NUM_MICRO_BATCHES, SEQ_LEN, HIDDEN_SIZE) # if you do no want zero, just comment out this dictionary zero = dict( model_config=dict(tensor_placement_policy="cuda", shard_strategy=TensorShardStrategy()), optimizer_config=dict(initial_scale=2**5), ) optimizer = dict( type=HybridAdam, lr=0.000015, weight_decay=1e-2, ) model = dict(type=GPT2_small_pipeline_hybrid, checkpoint=True, num_chunks=1) # pipeline parallel: modify integer value for the number of pipeline stages # tensor parallel: modify size to set the tensor parallel size, usually the number of GPUs per node # for the current model implementation, mode can only be 1D or None parallel = dict( pipeline=1, tensor=dict(size=2, mode="1d"), )
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/hybridparallelism/finetune.py
examples/language/gpt/hybridparallelism/finetune.py
import argparse from contextlib import nullcontext from typing import Callable, List, Union import evaluate import torch import torch.distributed as dist import torch.nn as nn from data import GLUEDataBuilder from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler as LRScheduler from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoConfig, GPT2ForSequenceClassification, get_linear_schedule_with_warmup import colossalai from colossalai.accelerator import get_accelerator from colossalai.booster import Booster from colossalai.booster.plugin import GeminiPlugin, HybridParallelPlugin, LowLevelZeroPlugin, TorchDDPPlugin from colossalai.cluster import DistCoordinator from colossalai.lazy import LazyInitContext from colossalai.nn.optimizer import HybridAdam # ============================== # Prepare Hyperparameters # ============================== NUM_EPOCHS = 3 BATCH_SIZE = 32 LEARNING_RATE = 2.4e-5 WEIGHT_DECAY = 0.01 WARMUP_FRACTION = 0.1 output_transform_fn = lambda x: x criterion = lambda x: x.loss def move_to_cuda(batch): return {k: v.cuda() for k, v in batch.items()} @torch.no_grad() def evaluate_model( model: nn.Module, criterion, test_dataloader: Union[DataLoader, List[DataLoader]], num_labels: int, task_name: str, eval_splits: List[str], booster: Booster, coordinator: DistCoordinator, ): metric = evaluate.load("glue", task_name, process_id=coordinator.rank, num_process=coordinator.world_size) model.eval() def evaluate_subset(dataloader: DataLoader): use_pipeline = isinstance(booster.plugin, HybridParallelPlugin) and booster.plugin.pp_size > 1 is_pp_last_stage = use_pipeline and booster.plugin.stage_manager.is_last_stage() accum_loss = torch.zeros(1, device=get_accelerator().get_current_device()) for batch in dataloader: batch = move_to_cuda(batch) labels = batch["labels"] if use_pipeline: pg_mesh = booster.plugin.pg_mesh pp_group = booster.plugin.pp_group current_pp_group_ranks = pg_mesh.get_ranks_in_group(pp_group) current_rank = dist.get_rank() batch = iter([batch]) outputs = booster.execute_pipeline(batch, model, criterion, return_loss=True, return_outputs=True) if is_pp_last_stage: logits = outputs["outputs"]["logits"] val_loss = outputs["loss"] accum_loss.add_(val_loss) if num_labels > 1: preds = torch.argmax(logits, axis=1) elif num_labels == 1: preds = logits.squeeze() dist.broadcast_object_list([preds, val_loss], src=current_pp_group_ranks[-1], group=pp_group) metric.add_batch(predictions=preds, references=labels) elif current_rank in current_pp_group_ranks: object_list = [None, None] dist.broadcast_object_list(object_list, src=current_pp_group_ranks[-1], group=pp_group) metric.add_batch( predictions=object_list[0].to(get_accelerator().get_current_device()), references=labels ) accum_loss.add_(object_list[1].to(get_accelerator().get_current_device())) else: batch = move_to_cuda(batch) outputs = model(**batch) val_loss, logits = outputs[:2] accum_loss.add_(val_loss) if num_labels > 1: preds = torch.argmax(logits, axis=1) elif num_labels == 1: preds = logits.squeeze() metric.add_batch(predictions=preds, references=labels) results = metric.compute() dist.all_reduce(accum_loss.div_(len(dataloader))) if coordinator.is_master() and results is not None: results["loss"] = accum_loss.item() / coordinator.world_size return results if isinstance(test_dataloader, DataLoader): return evaluate_subset(test_dataloader) else: assert len(test_dataloader) == len(eval_splits) final_results = {} for split, sub_loader in zip(eval_splits, test_dataloader): results = evaluate_subset(sub_loader) final_results.update({f"{k}_{split}": v for k, v in results.items()}) return final_results def train_epoch( epoch: int, model: nn.Module, optimizer: Optimizer, _criterion: Callable, lr_scheduler: LRScheduler, train_dataloader: DataLoader, booster: Booster, coordinator: DistCoordinator, ): use_pipeline = isinstance(booster.plugin, HybridParallelPlugin) and booster.plugin.pp_size > 1 is_pp_last_stage = use_pipeline and booster.plugin.stage_manager.is_last_stage() total_step = len(train_dataloader) model.train() optimizer.zero_grad() train_dataloader_iter = iter(train_dataloader) with tqdm( range(total_step), desc=f"Epoch [{epoch + 1}/{NUM_EPOCHS}]", disable=not (coordinator.is_master() or is_pp_last_stage), ) as pbar: # Forward pass for _ in pbar: if use_pipeline: outputs = booster.execute_pipeline( train_dataloader_iter, model, _criterion, optimizer, return_loss=True ) # Backward and optimize if is_pp_last_stage: loss = outputs["loss"] pbar.set_postfix({"loss": loss.item()}) else: data = next(train_dataloader_iter) data = move_to_cuda(data) outputs = model(**data) loss = _criterion(outputs, None) # Backward booster.backward(loss, optimizer) pbar.set_postfix({"loss": loss.item()}) optimizer.step() optimizer.zero_grad() lr_scheduler.step() def main(): # ============================== # Parse Arguments # ============================== parser = argparse.ArgumentParser() parser.add_argument("-t", "--task", default="mrpc", help="GLUE task to run") parser.add_argument( "-p", "--plugin", type=str, default="torch_ddp", choices=["torch_ddp", "torch_ddp_fp16", "gemini", "low_level_zero", "hybrid_parallel"], help="plugin to use", ) parser.add_argument( "--model_type", type=str, default="gpt2", help="only gpt2 now", ) parser.add_argument("--target_f1", type=float, default=None, help="target f1 score. Raise exception if not reached") parser.add_argument("--use_lazy_init", type=bool, default=False, help="for initiating lazy init context") parser.add_argument("--use_fp8_comm", type=bool, default=False, help="for using fp8 during communication") args = parser.parse_args() if args.model_type == "gpt2": model_name = "gpt2" else: raise RuntimeError # ============================== # Launch Distributed Environment # ============================== colossalai.launch_from_torch(seed=42) coordinator = DistCoordinator() # local_batch_size = BATCH_SIZE // coordinator.world_size lr = LEARNING_RATE * coordinator.world_size # ============================== # Instantiate Plugin and Booster # ============================== booster_kwargs = {} if args.plugin == "torch_ddp_fp16": booster_kwargs["mixed_precision"] = "fp16" if args.plugin.startswith("torch_ddp"): plugin = TorchDDPPlugin(fp8_communication=args.use_fp8_comm) elif args.plugin == "gemini": plugin = GeminiPlugin(initial_scale=2**5) elif args.plugin == "low_level_zero": plugin = LowLevelZeroPlugin(initial_scale=2**5) elif args.plugin == "hybrid_parallel": # modify the param accordingly for finetuning test cases plugin = HybridParallelPlugin( tp_size=1, pp_size=2, num_microbatches=None, microbatch_size=1, enable_all_optimization=True, zero_stage=1, precision="fp16", initial_scale=1, fp8_communication=args.use_fp8_comm, ) booster = Booster(plugin=plugin, **booster_kwargs) # ============================== # Prepare Dataloader # ============================== data_builder = GLUEDataBuilder( model_name, plugin, args.task, train_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE ) train_dataloader = data_builder.train_dataloader() test_dataloader = data_builder.test_dataloader() # ==================================== # Prepare model, optimizer # ==================================== # gpt2 pretrained model cfg = AutoConfig.from_pretrained( model_name, num_labels=data_builder.num_labels, pad_token=data_builder.tokenizer.pad_token, pad_token_id=data_builder.tokenizer.pad_token_id, ) init_ctx = ( LazyInitContext(default_device=get_accelerator().get_current_device()) if isinstance(plugin, (GeminiPlugin)) else nullcontext() ) with init_ctx: if model_name == "gpt2": model = GPT2ForSequenceClassification.from_pretrained(model_name, config=cfg).cuda() else: raise RuntimeError # optimizer no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": WEIGHT_DECAY, }, { "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0, }, ] optimizer = HybridAdam(optimizer_grouped_parameters, lr=lr, eps=1e-8) # lr scheduler total_steps = len(train_dataloader) * NUM_EPOCHS num_warmup_steps = int(WARMUP_FRACTION * total_steps) lr_scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=total_steps, ) def _criterion(outputs, inputs): outputs = output_transform_fn(outputs) loss = criterion(outputs) return loss # ============================== # Boost with ColossalAI # ============================== model, optimizer, _criterion, _, lr_scheduler = booster.boost( model, optimizer, criterion=_criterion, lr_scheduler=lr_scheduler ) # ============================== # Train model # ============================== for epoch in range(NUM_EPOCHS): train_epoch(epoch, model, optimizer, _criterion, lr_scheduler, train_dataloader, booster, coordinator) results = evaluate_model( model, _criterion, test_dataloader, data_builder.num_labels, args.task, data_builder.eval_splits, booster, coordinator, ) if coordinator.is_master(): print(results) if args.target_f1 is not None and "f1" in results: assert results["f1"] >= args.target_f1, f'f1 score {results["f1"]} is lower than target {args.target_f1}' if __name__ == "__main__": main()
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/hybridparallelism/benchmark.py
examples/language/gpt/hybridparallelism/benchmark.py
import argparse import resource from contextlib import nullcontext import torch from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload, MixedPrecision from torch.optim import Adam from tqdm import tqdm from transformers.models.gpt2.configuration_gpt2 import GPT2Config from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel import colossalai # import colossalai.utils.device as device_utils from colossalai.booster import Booster from colossalai.booster.plugin import GeminiPlugin, HybridParallelPlugin, TorchFSDPPlugin from colossalai.cluster import DistCoordinator from colossalai.lazy import LazyInitContext from colossalai.utils import get_current_device from examples.language.data_utils import RandomDataset from examples.language.model_utils import format_numel_str, get_model_numel from examples.language.performance_evaluator import PerformanceEvaluator # ============================== # Constants # ============================== MODEL_CONFIGS = { "118M": GPT2Config(activation_function="gelu"), "338M": GPT2Config(n_embd=1024, n_head=16, n_layer=24, activation_function="gelu"), "738M": GPT2Config(n_embd=1280, n_head=20, n_layer=36, activation_function="gelu"), "6.21B": GPT2Config(n_embd=4096, n_head=32, n_layer=32, n_positions=32768, activation_function="gelu"), } def main(): # ============================== # Parse Arguments # ============================== parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", type=str, default="6.21B", help="Model configuration") parser.add_argument( "-p", "--plugin", choices=["gemini", "gemini_auto", "fsdp", "fsdp_cpu", "3d", "3d_cpu"], default="gemini", help="Choose which plugin to use", ) parser.add_argument("-b", "--batch_size", type=int, default=2, help="Batch size") parser.add_argument("-s", "--num_steps", type=int, default=200, help="Number of steps to run") parser.add_argument("-i", "--ignore_steps", type=int, default=3, help="Number of steps to ignore") parser.add_argument("-g", "--grad_checkpoint", action="store_true", help="Use gradient checkpointing") parser.add_argument("-l", "--max_length", type=int, default=4096, help="Max sequence length") parser.add_argument( "-w", "--warmup_ratio", type=float, default=0.8, help="warm up ratio of non-model data. Only for gemini-auto" ) parser.add_argument("-m", "--memory_limit", type=int, help="Gemini memory limit in mb") parser.add_argument("--shard_param_frac", type=float, default=1.0, help="Shard param fraction. Only for gemini") parser.add_argument("--offload_optim_frac", type=float, default=0.0, help="Offload optim fraction. Only for gemini") parser.add_argument("--offload_param_frac", type=float, default=0.0, help="Offload param fraction. Only for gemini") parser.add_argument("--tp", type=int, default=1, help="Tensor parallel size") parser.add_argument("--extra_dp", type=int, default=1, help="Extra data parallel size, used for Gemini") parser.add_argument("--pp", type=int, default=1, help="Pipeline parallel size") parser.add_argument("--sp", type=int, default=1, help="Sequence parallel size") parser.add_argument("--sp_mode", type=str, default="ring_attn", help="Sequence parallel mode") parser.add_argument("--mbs", type=int, default=1) parser.add_argument("--zero", type=int, default=0) parser.add_argument("--pp_style", type=str, default="1f1b") parser.add_argument("--num_model_chunks", type=int, default=2) parser.add_argument("--cpu_offload", action="store_true", help="Use gradient checkpointing") args = parser.parse_args() colossalai.launch_from_torch() coordinator = DistCoordinator() def empty_init(): pass # ============================== # Initialize Booster # ============================== use_empty_init = True if args.plugin == "gemini": plugin = GeminiPlugin( precision="bf16", shard_param_frac=args.shard_param_frac, offload_optim_frac=args.offload_optim_frac, offload_param_frac=args.offload_param_frac, tp_size=args.tp, extra_dp_size=args.extra_dp, ) elif args.plugin == "gemini_auto": plugin = GeminiPlugin( placement_policy="auto", precision="bf16", warmup_non_model_data_ratio=args.warmup_ratio, tp_size=args.tp, extra_dp_size=args.extra_dp, ) elif args.plugin == "fsdp": if use_empty_init: plugin = TorchFSDPPlugin( mixed_precision=MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16 ), param_init_fn=empty_init(), ) else: plugin = TorchFSDPPlugin( mixed_precision=MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16 ) ) elif args.plugin == "fsdp_cpu": if use_empty_init: plugin = TorchFSDPPlugin( mixed_precision=MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16 ), cpu_offload=CPUOffload(offload_params=True), param_init_fn=empty_init(), ) else: plugin = TorchFSDPPlugin( mixed_precision=MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16 ), cpu_offload=CPUOffload(offload_params=True), ) elif args.plugin == "3d": plugin = HybridParallelPlugin( tp_size=args.tp, pp_size=args.pp, pp_style=args.pp_style, sp_size=args.sp, sequence_parallelism_mode=args.sp_mode, enable_sequence_parallelism=True, zero_stage=args.zero, num_model_chunks=args.num_model_chunks, enable_all_optimization=True, num_microbatches=args.mbs, cpu_offload=args.cpu_offload, precision="bf16", ) elif args.plugin == "3d_cpu": plugin = HybridParallelPlugin( tp_size=args.tp, pp_size=args.pp, zero_stage=args.zero, cpu_offload=True, enable_fused_normalization=torch.cuda.is_available(), num_microbatches=args.mbs, initial_scale=2**8, precision="bf16", ) else: raise ValueError(f"Unknown plugin {args.plugin}") booster = Booster(plugin=plugin) # ============================== # Initialize Dataset and Dataloader # ============================== dp_size = plugin.dp_size if isinstance(plugin, HybridParallelPlugin) else coordinator.world_size config = MODEL_CONFIGS[args.config] dataset = RandomDataset( num_samples=args.batch_size * args.num_steps * dp_size, max_length=args.max_length, vocab_size=config.vocab_size ) dataloader = plugin.prepare_dataloader(dataset, batch_size=args.batch_size, shuffle=True, drop_last=True) # ============================== # Initialize Model and Optimizer # ============================== init_ctx = ( LazyInitContext(default_device=get_current_device()) if isinstance(plugin, (GeminiPlugin, HybridParallelPlugin)) else nullcontext() ) with init_ctx: model = GPT2LMHeadModel(config) if args.grad_checkpoint: model.gradient_checkpointing_enable() model_numel = get_model_numel(model) coordinator.print_on_master(f"Model params: {format_numel_str(model_numel)}") performance_evaluator = PerformanceEvaluator( model_numel, model.config.n_layer, model.config.n_embd, model.config.vocab_size, args.grad_checkpoint, args.ignore_steps, dp_world_size=dp_size, ) optimizer = Adam(model.parameters()) torch.set_default_dtype(torch.bfloat16) model, optimizer, _, dataloader, _ = booster.boost(model, optimizer, dataloader=dataloader) torch.set_default_dtype(torch.float) coordinator.print_on_master(f"Booster init max CUDA memory: {torch.cuda.max_memory_allocated()/1024**2:.2f} MB") coordinator.print_on_master( f"Booster init max CPU memory: {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024:.2f} MB" ) if isinstance(plugin, HybridParallelPlugin) and args.pp > 1: data_iter = iter(dataloader) for step in tqdm(range(len(dataloader)), desc="Step", disable=not coordinator.is_master()): performance_evaluator.on_step_start(step) booster.execute_pipeline( data_iter, model, criterion=lambda outputs, inputs: outputs[0], optimizer=optimizer, return_loss=False ) optimizer.step() optimizer.zero_grad() performance_evaluator.on_step_end(input_ids=torch.empty(args.batch_size, args.max_length)) else: for step, batch in enumerate(tqdm(dataloader, desc="Step", disable=not coordinator.is_master())): performance_evaluator.on_step_start(step) outputs = model(**batch) loss = outputs[0] del outputs booster.backward(loss, optimizer) optimizer.step() optimizer.zero_grad() performance_evaluator.on_step_end(**batch) coordinator.print_on_master(f"Max CUDA memory usage: {torch.cuda.max_memory_allocated()/1024**2:.2f} MB") performance_evaluator.on_fit_end() coordinator.print_on_master(f"Max CUDA memory usage: {torch.cuda.max_memory_allocated()/1024**2:.2f} MB") if __name__ == "__main__": main()
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/hybridparallelism/data.py
examples/language/gpt/hybridparallelism/data.py
import datasets from transformers import AutoTokenizer, PreTrainedTokenizer from colossalai.booster.plugin.dp_plugin_base import DPPluginBase class GLUEDataBuilder: task_text_field_map = { "cola": ["sentence"], "sst2": ["sentence"], "mrpc": ["sentence1", "sentence2"], "qqp": ["question1", "question2"], "stsb": ["sentence1", "sentence2"], "mnli": ["premise", "hypothesis"], "qnli": ["question", "sentence"], "rte": ["sentence1", "sentence2"], "wnli": ["sentence1", "sentence2"], "ax": ["premise", "hypothesis"], } glue_task_num_labels = { "cola": 2, "sst2": 2, "mrpc": 2, "qqp": 2, "stsb": 1, "mnli": 3, "qnli": 2, "rte": 2, "wnli": 2, "ax": 3, } loader_columns = [ "datasets_idx", "input_ids", "token_type_ids", "attention_mask", "start_positions", "end_positions", "labels", ] def __init__( self, model_name_or_path: str, plugin: DPPluginBase, task_name: str = "mrpc", max_seq_length: int = 128, train_batch_size: int = 32, eval_batch_size: int = 32, **kwargs, ): super().__init__() self.model_name_or_path = model_name_or_path self.task_name = task_name self.max_seq_length = max_seq_length self.train_batch_size = train_batch_size self.eval_batch_size = eval_batch_size self.plugin = plugin self.text_fields = self.task_text_field_map[task_name] self.num_labels = self.glue_task_num_labels[task_name] self.tokenizer: PreTrainedTokenizer = AutoTokenizer.from_pretrained(self.model_name_or_path, use_fast=True) if not getattr(self.tokenizer, "pad_token", None): self.tokenizer.pad_token = self.tokenizer._eos_token self.setup() def setup(self): self.dataset = datasets.load_dataset("glue", self.task_name) for split in self.dataset.keys(): self.dataset[split] = self.dataset[split].map( self.convert_to_features, batched=True, remove_columns=["label"], ) self.columns = [c for c in self.dataset[split].column_names if c in self.loader_columns] self.dataset[split].set_format(type="torch", columns=self.columns) self.eval_splits = [x for x in self.dataset.keys() if "validation" in x] def prepare_data(self): datasets.load_dataset("glue", self.task_name) AutoTokenizer.from_pretrained(self.model_name_or_path, use_fast=True) def train_dataloader(self): return self.plugin.prepare_dataloader( self.dataset["train"], batch_size=self.train_batch_size, shuffle=True, drop_last=True ) def val_dataloader(self): if len(self.eval_splits) == 1: return self.plugin.prepare_dataloader(self.dataset["validation"], batch_size=self.eval_batch_size) elif len(self.eval_splits) > 1: return [ self.plugin.prepare_dataloader(self.dataset[x], batch_size=self.eval_batch_size) for x in self.eval_splits ] def test_dataloader(self): if len(self.eval_splits) == 1: return self.plugin.prepare_dataloader(self.dataset["test"], batch_size=self.eval_batch_size) elif len(self.eval_splits) > 1: return [ self.plugin.prepare_dataloader(self.dataset[x], batch_size=self.eval_batch_size) for x in self.eval_splits ] def convert_to_features(self, example_batch): # Either encode single sentence or sentence pairs if len(self.text_fields) > 1: texts_or_text_pairs = list(zip(example_batch[self.text_fields[0]], example_batch[self.text_fields[1]])) else: texts_or_text_pairs = example_batch[self.text_fields[0]] # Tokenize the text/text pairs features = self.tokenizer.batch_encode_plus( texts_or_text_pairs, max_length=self.max_seq_length, padding="max_length", truncation=True ) # Rename label to labels to make it easier to pass to model forward features["labels"] = example_batch["label"] return features
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/gemini/train_gpt_demo.py
examples/language/gpt/gemini/train_gpt_demo.py
import argparse import os from contextlib import nullcontext from functools import partial from time import time import psutil import torch import torch.nn as nn from commons.model_zoo import model_builder from commons.performance_evaluator import get_profile_context from commons.utils import get_data, get_tflops, get_time_stamp from packaging import version import colossalai from colossalai.accelerator import get_accelerator from colossalai.booster import Booster from colossalai.booster.plugin import GeminiPlugin, LowLevelZeroPlugin, TorchDDPPlugin from colossalai.lazy import LazyInitContext from colossalai.logging import disable_existing_loggers, get_dist_logger from colossalai.nn.optimizer import HybridAdam CAI_VERSION = colossalai.__version__ def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--distplan", type=str, default="CAI_Gemini", help="The distributed plan [colossalai, zero1, zero2, torch_ddp, torch_zero].", ) parser.add_argument( "--batch_size", type=int, default=8, help="batch size per DP group of training.", ) parser.add_argument( "--model_type", type=str, default="gpt2_medium", help="model model scale", ) parser.add_argument( "--train_step", type=int, default=10, help="training iterations for test", ) args = parser.parse_args() return args class GPTLMLoss(nn.Module): def __init__(self): super().__init__() self.loss_fn = nn.CrossEntropyLoss() def forward(self, logits, labels): shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens return self.loss_fn(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)) def get_cpu_mem(): return psutil.Process().memory_info().rss / 1024**2 def get_gpu_mem(): return torch.cuda.memory_allocated() / 1024**2 def get_mem_info(prefix=""): return f"{prefix}GPU memory usage: {get_gpu_mem():.2f} MB, CPU memory usage: {get_cpu_mem():.2f} MB" def get_model_size(model: nn.Module): total_numel = 0 for module in model.modules(): for p in module.parameters(recurse=False): total_numel += p.numel() return total_numel def model_size_formatter(numel: int) -> str: GB_SIZE = 10**9 MB_SIZE = 10**6 KB_SIZE = 10**3 if numel >= GB_SIZE: return f"{numel / GB_SIZE:.1f}B" elif numel >= MB_SIZE: return f"{numel / MB_SIZE:.1f}M" elif numel >= KB_SIZE: return f"{numel / KB_SIZE:.1f}K" else: return str(numel) def set_cpu_maximum_parallelism(): conf_str = torch.__config__.parallel_info() inter_str = conf_str.split("hardware_concurrency() : ")[1] max_concurrency = inter_str.split("\n")[0] os.environ["OMP_NUM_THREADS"] = max_concurrency print(f"environmental variable OMP_NUM_THREADS is set to {max_concurrency}.") def main(): # version check # this example is supposed to work for versions greater than 0.2.0 assert version.parse(CAI_VERSION) >= version.parse("0.2.0") set_cpu_maximum_parallelism() args = parse_args() # if args.distplan not in ["colossalai", "torch_ddp", "torch_zero", "zero1", "zero2"]: if args.distplan not in ["CAI_ZeRO1", "CAI_ZeRO2", "CAI_Gemini", "Pytorch_DDP", "Pytorch_ZeRO"]: raise TypeError(f"{args.distplan} is error") # batch size per DP degree BATCH_SIZE = args.batch_size SEQ_LEN = 1024 VOCAB_SIZE = 50257 NUM_STEPS = args.train_step WARMUP_STEPS = 1 assert WARMUP_STEPS < NUM_STEPS, "warmup steps should smaller than the total steps" assert (NUM_STEPS - WARMUP_STEPS) % 2 == 1, "the number of valid steps should be odd to take the median" PROF_FLAG = False # The flag of profiling, False by default disable_existing_loggers() colossalai.launch_from_torch() logger = get_dist_logger() logger.info(f"{args.model_type}, {args.distplan}, batch size {BATCH_SIZE}", ranks=[0]) # build criterion criterion = GPTLMLoss() torch.manual_seed(123) if args.distplan.startswith("CAI"): ctx = ( LazyInitContext(default_device=get_accelerator().get_current_device()) if args.distplan == "CAI_Gemini" else nullcontext() ) # build GPT model with ctx: model = model_builder(args.model_type)(checkpoint=True) # assign running configurations if args.distplan == "CAI_ZeRO1": zero_stage = 1 elif args.distplan == "CAI_ZeRO2": zero_stage = 2 elif args.distplan == "CAI_Gemini": zero_stage = 3 else: raise RuntimeError plugin = None if args.distplan.startswith("CAI_ZeRO"): plugin = LowLevelZeroPlugin( stage=zero_stage, reduce_bucket_size_in_m=12, overlap_communication=True, verbose=True ) elif args.distplan == "CAI_Gemini": plugin = GeminiPlugin(search_range_m=128, hidden_dim=model.config.n_embd) else: raise RuntimeError # build a highly optimized gpu/cpu optimizer optimizer = HybridAdam(model.parameters(), lr=1e-3) logger.info(get_mem_info(prefix="After init optim, "), ranks=[0]) elif args.distplan.startswith("Pytorch"): assert args.tp_degree == 1, "The degree of TP should be 1 for DDP examples." model = model_builder(args.model_type)(checkpoint=True).cuda() plugin = TorchDDPPlugin() if args.distplan.endswith("DDP"): optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) elif args.distplan.endswith("ZeRO"): from torch.distributed.optim import ZeroRedundancyOptimizer optimizer = ZeroRedundancyOptimizer(model.parameters(), optimizer_class=torch.optim.Adam, lr=1e-3) else: raise RuntimeError # wrap your model and optimizer booster = Booster(plugin=plugin) model, optimizer, criterion, _, _ = booster.boost(model, optimizer, criterion) # model is shared after TP numel = get_model_size(model) logger.info(f"the size of testing model size is {model_size_formatter(numel)}.") logger.info(get_mem_info(prefix="After init model, "), ranks=[0]) # Tflops_per_GPU = global_batch * global_numel * seq_len * 8 / #gpu # = (batch_per_DP_group * dp_degree) * (numel * tp_degree) * seq_len * 8 / (tp_degree * dp_degree) # = batch_per_DP_group * numel * seq_len * 8 get_tflops_func = partial(get_tflops, numel, BATCH_SIZE, SEQ_LEN) torch.cuda.synchronize() model.train() tflops_list = [] def train_step(): # we just use randomly generated data here input_ids, attn_mask = get_data(BATCH_SIZE, SEQ_LEN, VOCAB_SIZE) optimizer.zero_grad() start = time() outputs = model(input_ids, attn_mask) loss = criterion(outputs, input_ids) torch.cuda.synchronize() fwd_end = time() fwd_time = fwd_end - start logger.info(get_mem_info(prefix=f"[{n + 1}/{NUM_STEPS}] Forward "), ranks=[0]) booster.backward(loss, optimizer) torch.cuda.synchronize() bwd_end = time() bwd_time = bwd_end - fwd_end logger.info(get_mem_info(prefix=f"[{n + 1}/{NUM_STEPS}] Backward "), ranks=[0]) optimizer.step() torch.cuda.synchronize() optim_time = time() - bwd_end step_time = time() - start logger.info(get_mem_info(prefix=f"[{n + 1}/{NUM_STEPS}] Optimizer step "), ranks=[0]) step_tflops = get_tflops_func(step_time) logger.info( f"[{n + 1}/{NUM_STEPS}] Loss:{loss.item():.3f}, Step time: {step_time:.3f}s, TFLOPS: {get_tflops_func(step_time):.3f}, FWD time: {fwd_time:.3f}s, BWD time: {bwd_time:.3f}s, OPTIM time: {optim_time:.3f}s", ranks=[0], ) if n >= WARMUP_STEPS: tflops_list.append(step_tflops) demo_profiler = get_profile_context( PROF_FLAG, WARMUP_STEPS, NUM_STEPS - WARMUP_STEPS, save_dir=f"profile/{get_time_stamp()}-demo" ) with demo_profiler as prof: for n in range(NUM_STEPS): train_step() prof.step() tflops_list.sort() median_index = ((NUM_STEPS - WARMUP_STEPS) >> 1) + WARMUP_STEPS logger.info(f"Median TFLOPS is {tflops_list[median_index]:.3f}") torch.cuda.synchronize() if __name__ == "__main__": main()
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/gemini/commons/model_zoo.py
examples/language/gpt/gemini/commons/model_zoo.py
from torch import nn from transformers import GPT2Config, GPT2LMHeadModel ## Define the Model and Loss Based on Huggingface transformers GPT2LMHeadModel class GPTLMModel(nn.Module): def __init__( self, hidden_size=768, num_layers=12, num_attention_heads=12, max_seq_len=1024, vocab_size=50257, checkpoint=False, ): super().__init__() self.checkpoint = checkpoint self.config = GPT2Config( n_embd=hidden_size, n_layer=num_layers, n_head=num_attention_heads, n_positions=max_seq_len, n_ctx=max_seq_len, vocab_size=vocab_size, ) self.model = GPT2LMHeadModel(self.config) if checkpoint: self.model.gradient_checkpointing_enable() def forward(self, input_ids, attention_mask): # Only return lm_logits return self.model(input_ids=input_ids, attention_mask=attention_mask, use_cache=not self.checkpoint)[0] def gpt2_medium(checkpoint=False): return GPTLMModel(hidden_size=1024, num_layers=24, num_attention_heads=16, checkpoint=checkpoint) def gpt2_xl(checkpoint=True): return GPTLMModel(hidden_size=1600, num_layers=48, num_attention_heads=32, checkpoint=checkpoint) def gpt2_10b(checkpoint=True): return GPTLMModel(hidden_size=4096, num_layers=50, num_attention_heads=16, checkpoint=checkpoint) def gpt2_14b(checkpoint=True): return GPTLMModel(hidden_size=4096, num_layers=70, num_attention_heads=16, checkpoint=checkpoint) def gpt2_20b(checkpoint=True): return GPTLMModel(hidden_size=8192, num_layers=25, num_attention_heads=16, checkpoint=checkpoint) def gpt2_24b(checkpoint=True): return GPTLMModel(hidden_size=8192, num_layers=30, num_attention_heads=16, checkpoint=checkpoint) def gpt2_30b(checkpoint=True): return GPTLMModel(hidden_size=8192, num_layers=37, num_attention_heads=16, checkpoint=checkpoint) def gpt2_40b(checkpoint=True): return GPTLMModel(hidden_size=8192, num_layers=50, num_attention_heads=16, checkpoint=checkpoint) def model_builder(model_size: str) -> callable: if model_size == "gpt2_medium": return gpt2_medium elif model_size == "gpt2_xl": return gpt2_xl elif model_size == "gpt2_10b": return gpt2_10b elif model_size == "gpt2_14b": return gpt2_14b elif model_size == "gpt2_20b": return gpt2_20b elif model_size == "gpt2_24b": return gpt2_24b elif model_size == "gpt2_30b": return gpt2_30b elif model_size == "gpt2_40b": return gpt2_40b else: raise TypeError(f"model_builder {model_size}") __all__ = ["model_builder"]
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/gemini/commons/utils.py
examples/language/gpt/gemini/commons/utils.py
import time import torch class DummyProfiler: def __init__(self): self.step_number = 0 def step(self): self.step_number += 1 # Randomly Generated Data def get_data(batch_size, seq_len, vocab_size): input_ids = torch.randint(0, vocab_size, (batch_size, seq_len), device=torch.cuda.current_device()) attention_mask = torch.ones_like(input_ids) return input_ids, attention_mask def get_tflops(model_numel, batch_size, seq_len, step_time): return model_numel * batch_size * seq_len * 8 / 1e12 / (step_time + 1e-12) def get_time_stamp(): cur_time = time.strftime("%d-%H:%M", time.localtime()) return cur_time
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/gpt/gemini/commons/performance_evaluator.py
examples/language/gpt/gemini/commons/performance_evaluator.py
from time import time from typing import Optional import torch import torch.distributed as dist from torch import Tensor from torch.profiler import ProfilerActivity, profile, schedule, tensorboard_trace_handler from colossalai.cluster import DistCoordinator from colossalai.utils import get_current_device def divide(x: float, y: float) -> float: if y == 0: return float("inf") elif y == float("inf"): return float("nan") return x / y @torch.no_grad() def all_reduce_mean(x: float, world_size: int) -> float: if world_size == 1: return x # BUG: RuntimeError: Invalid scalar type when use dist.all_reduce(tensor, group=gloo_group) # # Use CPU tensor to avoid OOM/weird NCCl error # gloo_group = dist.new_group(backend="gloo") # tensor = torch.tensor([x], device="cpu") # dist.all_reduce(tensor, group=gloo_group) # tensor = tensor / world_size # return tensor.item() tensor = torch.tensor([x], device=get_current_device(), dtype=torch.float) dist.all_reduce(tensor) tensor = tensor / world_size return tensor.item() def get_profile_context(enable_flag, warmup_steps, active_steps, save_dir, nsys=False): class DummyProfiler: def __init__(self): self.step_number = 0 def step(self): self.step_number += 1 def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass class NsysProfiler: def __init__(self, warmup_steps, active_steps): self.step_number = 0 self.warmup_steps = warmup_steps self.active_steps = active_steps def step(self): if self.step_number == self.warmup_steps: torch.cuda.cudart().cudaProfilerStart() elif self.step_number == self.warmup_steps + self.active_steps: torch.cuda.cudart().cudaProfilerStop() self.step_number += 1 def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass if enable_flag: if nsys: return NsysProfiler(warmup_steps, active_steps) return profile( activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], schedule=schedule(wait=0, warmup=warmup_steps, active=active_steps), on_trace_ready=tensorboard_trace_handler(save_dir), record_shapes=True, profile_memory=True, with_stack=True, ) else: return DummyProfiler() class Timer: def __init__(self) -> None: self.start_time: Optional[float] = None self.duration: float = 0.0 def start(self) -> None: self.start_time = time() def end(self) -> None: assert self.start_time is not None self.duration += time() - self.start_time self.start_time = None def reset(self) -> None: self.duration = 0.0 class PerformanceEvaluator: """ Callback for valuate the performance of the model. Args: actor_num_params: The number of parameters of the actor model. critic_num_params: The number of parameters of the critic model. initial_model_num_params: The number of parameters of the initial model. reward_model_num_params: The number of parameters of the reward model. enable_grad_checkpoint: Whether to enable gradient checkpointing. ignore_episodes: The number of episodes to ignore when calculating the performance. """ def __init__( self, model_numel: int, num_layers: int, hidden_size: int, vocab_size: int, enable_grad_checkpoint: bool = False, ignore_steps: int = 0, dp_world_size: Optional[int] = None, ) -> None: self.model_numel = model_numel self.enable_grad_checkpoint = enable_grad_checkpoint self.ignore_steps = ignore_steps self.num_layers = num_layers self.hidden_size = hidden_size self.vocab_size = vocab_size self.coordinator = DistCoordinator() self.dp_world_size = dp_world_size or self.coordinator.world_size self.disable: bool = False self.timer = Timer() self.num_samples: int = 0 self.flop_megatron = 0 self.flop: int = 0 def on_step_start(self, step: int) -> None: self.disable = self.ignore_steps > 0 and step < self.ignore_steps if self.disable: return # get_accelerator().synchronize() self.timer.start() def on_step_end(self, input_ids: Tensor, **kwargs) -> None: if self.disable: return # get_accelerator().synchronize() self.timer.end() batch_size, seq_len = input_ids.shape self.num_samples += batch_size checkpoint_activations_factor = 3 + int(self.enable_grad_checkpoint) self.flop_megatron += ( 24 * checkpoint_activations_factor * batch_size * seq_len * self.num_layers * (self.hidden_size**2) ) * ( 1.0 + (seq_len / (6.0 * self.hidden_size)) + (self.vocab_size / (16.0 * self.num_layers * self.hidden_size)) ) self.flop += batch_size * seq_len * self.model_numel * 2 * (3 + int(self.enable_grad_checkpoint)) def on_fit_end(self) -> None: avg_duration = all_reduce_mean(self.timer.duration, self.coordinator.world_size) avg_throughput = self.num_samples * self.dp_world_size / (avg_duration + 1e-12) mp_world_size = self.coordinator.world_size // self.dp_world_size avg_tflops_per_gpu_megatron = self.flop_megatron / 1e12 / (avg_duration + 1e-12) / mp_world_size avg_tflops_per_gpu = self.flop / 1e12 / (avg_duration + 1e-12) / mp_world_size self.coordinator.print_on_master( f"num_samples: {self.num_samples}, dp_world_size: {self.dp_world_size}, flop_megatron: {self.flop_megatron}, flop: {self.flop}, avg_duration: {avg_duration}, " f"avg_throughput: {avg_throughput}" ) self.coordinator.print_on_master( f"Throughput: {avg_throughput:.2f} samples/sec, TFLOPS per GPU by Megatron: {avg_tflops_per_gpu_megatron:.2f}, TFLOPS per GPU: {avg_tflops_per_gpu:.2f}" )
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/deepseek/data_utils.py
examples/language/deepseek/data_utils.py
import json import random from typing import Iterator, Optional import numpy as np import torch from torch.distributed import ProcessGroup from torch.distributed.distributed_c10d import _get_default_group from torch.utils.data import DataLoader, Dataset, DistributedSampler from colossalai.accelerator import get_accelerator class StatefulDistributedSampler(DistributedSampler): def __init__( self, dataset: Dataset, num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed: int = 0, drop_last: bool = False, ) -> None: super().__init__(dataset, num_replicas, rank, shuffle, seed, drop_last) self.start_index: int = 0 def __iter__(self) -> Iterator: iterator = super().__iter__() indices = list(iterator) indices = indices[self.start_index :] return iter(indices) def __len__(self) -> int: return self.num_samples - self.start_index def set_start_index(self, start_index: int) -> None: self.start_index = start_index def prepare_dataloader( dataset, batch_size, shuffle=False, seed=1024, drop_last=False, pin_memory=False, num_workers=0, process_group: Optional[ProcessGroup] = None, **kwargs, ): r""" Prepare a dataloader for distributed training. The dataloader will be wrapped by `torch.utils.data.DataLoader` and `StatefulDistributedSampler`. Args: dataset (`torch.utils.data.Dataset`): The dataset to be loaded. shuffle (bool, optional): Whether to shuffle the dataset. Defaults to False. seed (int, optional): Random worker seed for sampling, defaults to 1024. add_sampler: Whether to add ``DistributedDataParallelSampler`` to the dataset. Defaults to True. drop_last (bool, optional): Set to True to drop the last incomplete batch, if the dataset size is not divisible by the batch size. If False and the size of dataset is not divisible by the batch size, then the last batch will be smaller, defaults to False. pin_memory (bool, optional): Whether to pin memory address in CPU memory. Defaults to False. num_workers (int, optional): Number of worker threads for this dataloader. Defaults to 0. kwargs (dict): optional parameters for ``torch.utils.data.DataLoader``, more details could be found in `DataLoader <https://pytorch.org/docs/stable/_modules/torch/utils/data/dataloader.html#DataLoader>`_. Returns: :class:`torch.utils.data.DataLoader`: A DataLoader used for training or testing. """ _kwargs = kwargs.copy() process_group = process_group or _get_default_group() sampler = StatefulDistributedSampler( dataset, num_replicas=process_group.size(), rank=process_group.rank(), shuffle=shuffle ) # Deterministic dataloader def seed_worker(worker_id): worker_seed = seed np.random.seed(worker_seed) torch.manual_seed(worker_seed) random.seed(worker_seed) return DataLoader( dataset, batch_size=batch_size, sampler=sampler, worker_init_fn=seed_worker, drop_last=drop_last, pin_memory=pin_memory, num_workers=num_workers, **_kwargs, ) def load_json(file_path: str): with open(file_path, "r") as f: return json.load(f) def save_json(data, file_path: str): with open(file_path, "w") as f: json.dump(data, f, indent=4) class RandomDataset(Dataset): def __init__(self, num_samples: int = 1000, max_length: int = 2048, vocab_size: int = 32000): self.num_samples = num_samples self.max_length = max_length self.input_ids = torch.randint( 0, vocab_size, (num_samples, max_length), device=get_accelerator().get_current_device() ) self.attention_mask = torch.ones_like(self.input_ids) def __len__(self): return self.num_samples def __getitem__(self, idx): return { "input_ids": self.input_ids[idx], "attention_mask": self.attention_mask[idx], "labels": self.input_ids[idx], }
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/deepseek/model_utils.py
examples/language/deepseek/model_utils.py
from contextlib import contextmanager import torch import torch.nn as nn @contextmanager def low_precision_init(target_dtype: torch.dtype = torch.float16): dtype = torch.get_default_dtype() try: torch.set_default_dtype(target_dtype) yield finally: torch.set_default_dtype(dtype) def get_model_numel(model: nn.Module) -> int: return sum(p.numel() for p in model.parameters()) def format_numel_str(numel: int) -> str: B = 1024**3 M = 1024**2 K = 1024 if numel >= B: return f"{numel / B:.2f} B" elif numel >= M: return f"{numel / M:.2f} M" elif numel >= K: return f"{numel / K:.2f} K" else: return f"{numel}"
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/deepseek/benchmark.py
examples/language/deepseek/benchmark.py
# modified from mixtral benchmark import argparse import resource import time import warnings from contextlib import nullcontext from types import MethodType import torch import torch.distributed as dist from data_utils import RandomDataset from model_utils import format_numel_str, get_model_numel from peft import LoraConfig from performance_evaluator import PerformanceEvaluator, get_profile_context from tqdm import tqdm from transformers import AutoConfig, AutoModelForCausalLM import colossalai from colossalai.accelerator import get_accelerator from colossalai.booster import Booster from colossalai.booster.plugin import MoeHybridParallelPlugin from colossalai.cluster import DistCoordinator from colossalai.lazy import LazyInitContext from colossalai.nn.optimizer import HybridAdam from colossalai.shardformer import PipelineGradientCheckpointConfig warnings.filterwarnings("ignore") # ============================== # Constants # ============================== # We have lots of llamas for your choice! MODEL_CONFIGS = { "100m": AutoConfig.from_pretrained( "deepseek-ai/deepseek-moe-16b-base", max_position_embeddings=4096, num_hidden_layers=1, num_attention_heads=32, intermediate_size=512, moe_intermediate_size=128, hidden_size=512, n_routed_experts=8, n_shared_experts=4, num_experts_per_tok=2, first_k_dense_replace=0, attn_implementation="flash_attention_2", trust_remote_code=True, ), "7b": AutoConfig.from_pretrained( "deepseek-ai/deepseek-moe-16b-base", max_position_embeddings=4096, num_hidden_layers=13, attn_implementation="flash_attention_2", trust_remote_code=True, ), "14b": AutoConfig.from_pretrained( "deepseek-ai/deepseek-moe-16b-base", max_position_embeddings=4096, num_hidden_layers=26, attn_implementation="flash_attention_2", trust_remote_code=True, ), "v3-7b": AutoConfig.from_pretrained( "deepseek-ai/DeepSeek-V3", num_hidden_layers=6, first_k_dense_replace=2, n_routed_experts=32, vocab_size=8192, attn_implementation="flash_attention_2", trust_remote_code=True, ), } def main(): # ============================== # Parse Arguments # ============================== parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", type=str, default="100m", help="Model configuration") parser.add_argument( "-p", "--plugin", choices=["3d"], default="3d", help="Choose which plugin to use", ) parser.add_argument("-b", "--batch_size", type=int, default=1, help="Batch size") parser.add_argument("-s", "--num_steps", type=int, default=5, help="Number of steps to run") parser.add_argument("-i", "--ignore_steps", type=int, default=2, help="Number of steps to ignore") parser.add_argument("-g", "--grad_checkpoint", action="store_true", help="Use gradient checkpointing") parser.add_argument("-l", "--max_length", type=int, default=4096, help="Max sequence length") parser.add_argument( "-w", "--warmup_ratio", type=float, default=0.8, help="warm up ratio of non-model data. Only for gemini-auto" ) parser.add_argument("-m", "--memory_limit", type=int, help="Gemini memory limit in mb") parser.add_argument("-x", "--xformers", action="store_true", help="Use xformers") parser.add_argument("--shard_param_frac", type=float, default=1.0, help="Shard param fraction. Only for gemini") parser.add_argument("--offload_optim_frac", type=float, default=0.0, help="Offload optim fraction. Only for gemini") parser.add_argument("--offload_param_frac", type=float, default=0.0, help="Offload param fraction. Only for gemini") parser.add_argument("--tp", type=int, default=1, help="Tensor parallel size") parser.add_argument("--ep", type=int, default=1, help="Expert parallel size") parser.add_argument("--sp", type=int, default=1, help="Sequence parallel size") parser.add_argument("--extra_dp", type=int, default=1, help="Extra data parallel size, used for Gemini") parser.add_argument("--pp", type=int, default=1, help="Pipeline parallel size") parser.add_argument("--mbs", type=int, default=1, help="Micro batch size of pipeline parallel") parser.add_argument("--zero", type=int, default=1, help="Zero Stage when hybrid plugin is enabled") parser.add_argument("--custom-ckpt", action="store_true", help="Customize checkpoint", default=False) parser.add_argument("--pp_style", default="1f1b", choices=["1f1b", "interleaved"]) parser.add_argument("--n_chunks", default=1, help="number of model chunks", type=eval) parser.add_argument("--profile", action="store_true", help="Profile the code") parser.add_argument( "--nsys", action="store_true", help="Use nsys for profiling. \ You should put something like this before colossalai launch: \ nsys profile -w true -t cuda,cudnn,cublas -s cpu --capture-range=cudaProfilerApi --capture-range-end=stop --cudabacktrace=true -x true --python-backtrace=cuda -o prof_out", ) parser.add_argument("--disable-async-reduce", action="store_true", help="Disable the asynchronous reduce operation") parser.add_argument("--prefetch_num", type=int, default=0, help="chunk prefetch max number") parser.add_argument("--no_cache", action="store_true") parser.add_argument("--use_fp8_comm", action="store_true", default=False, help="for using fp8 during communication") parser.add_argument("--use_fp8", action="store_true", default=False, help="for using fp8 linear") parser.add_argument("--overlap_allgather", action="store_true") parser.add_argument( "--sp_mode", default="all_to_all", choices=["all_to_all"], help="Sequence parallelism mode", ) parser.add_argument("--debug", action="store_true", help="Enable debug mode") parser.add_argument("--enable_lora", action="store_true", help="Enable LoRA") args = parser.parse_args() colossalai.launch_from_torch() coordinator = DistCoordinator() # ckpt config for LLaMA3-70B on 64 H100 GPUs hybrid_kwargs = ( { "gradient_checkpoint_config": PipelineGradientCheckpointConfig( num_ckpt_layers_per_stage=[19, 19, 19, 13], ), "num_layers_per_stage": [19, 20, 20, 21], "pp_style": "interleaved", } if args.custom_ckpt else {} ) # ============================== # Initialize Booster # ============================== if args.plugin == "3d": plugin = MoeHybridParallelPlugin( ep_size=args.ep, tp_size=args.tp, pp_size=args.pp, pp_style=args.pp_style, num_model_chunks=args.n_chunks, zero_stage=args.zero, sp_size=args.sp, sequence_parallelism_mode=args.sp_mode, enable_sequence_parallelism=args.sp > 1, enable_fused_normalization=get_accelerator().is_available(), enable_flash_attention=args.xformers, microbatch_size=args.mbs, precision="bf16", enable_metadata_cache=not args.no_cache, overlap_allgather=args.overlap_allgather, use_fp8=args.use_fp8, fp8_communication=args.use_fp8_comm, **hybrid_kwargs, ) else: raise ValueError(f"Unknown plugin {args.plugin}") booster = Booster(plugin=plugin) # ============================== # Initialize Dataset and Dataloader # ============================== dp_size = getattr(plugin, "dp_size", coordinator.world_size) if args.config in MODEL_CONFIGS: config = MODEL_CONFIGS[args.config] else: config = AutoConfig.from_pretrained(args.config, trust_remote_code=True) torch.cuda.manual_seed(42) dataset = RandomDataset( num_samples=args.batch_size * args.num_steps * dp_size, max_length=args.max_length, vocab_size=config.vocab_size ) dataloader = plugin.prepare_dataloader(dataset, batch_size=args.batch_size, shuffle=True, drop_last=True, seed=42) # ============================== # Initialize Model and Optimizer # ============================== init_ctx = ( LazyInitContext(default_device=get_accelerator().get_current_device()) if isinstance(plugin, MoeHybridParallelPlugin) else nullcontext() ) attn_impl = "eager" if get_accelerator().name == "npu" else "flash_attention_2" with init_ctx: model = AutoModelForCausalLM.from_config( config, trust_remote_code=True, attn_implementation=attn_impl, torch_dtype=torch.bfloat16 ).to(torch.bfloat16) if args.enable_lora: model = booster.enable_lora( model, lora_config=LoraConfig(task_type="CAUSAL_LM", target_modules=["gate_proj", "up_proj", "down_proj"]), ) if args.grad_checkpoint: model.gradient_checkpointing_enable() if config.__class__.__name__.startswith("DeepseekV3"): model.config.use_cache = False model.eval() # enable grad for moe layers for m in model.modules(): if m.__class__.__name__ == "DeepseekV3MoE": m.moe_infer = MethodType(m.moe_infer.__wrapped__, m) model_numel = get_model_numel(model) coordinator.print_on_master(f"Model params: {format_numel_str(model_numel)}") performance_evaluator = PerformanceEvaluator( model_numel, model.config.num_hidden_layers, model.config.hidden_size, model.config.vocab_size, args.grad_checkpoint, args.ignore_steps, dp_world_size=dp_size, ) optimizer = HybridAdam(model.parameters()) torch.set_default_dtype(torch.bfloat16) model, optimizer, _, dataloader, _ = booster.boost(model, optimizer, dataloader=dataloader) torch.set_default_dtype(torch.float) coordinator.print_on_master( f"Booster init max CUDA memory: {get_accelerator().max_memory_allocated()/1024**2:.2f} MB" ) coordinator.print_on_master( f"Booster init max CPU memory: {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024:.2f} MB" ) with get_profile_context( args.profile, args.ignore_steps, 1, # avoid creating massive log files save_dir=f"profile/{time.strftime('%H:%M', time.localtime())}-{args.plugin}-llama-{args.config}", nsys=args.nsys, ) as prof: # , distributed_debug_mode(10, enable=True): if isinstance(plugin, MoeHybridParallelPlugin) and args.pp > 1: data_iter = iter(dataloader) with tqdm( range(len(dataloader)), desc="Step", disable=dist.get_rank() != dist.get_world_size() - 1 ) as pbar: for step in pbar: performance_evaluator.on_step_start(step) outputs = booster.execute_pipeline( data_iter, model, criterion=lambda outputs, inputs: outputs[0], optimizer=optimizer, return_loss=True, ) loss = outputs["loss"] loss_scalar = loss.item() if loss is not None else None pbar.set_postfix({"loss": loss_scalar}) optimizer.step() optimizer.zero_grad() performance_evaluator.on_step_end(input_ids=torch.empty(args.batch_size, args.max_length)) prof.step() else: with tqdm(dataloader, desc="Step", disable=not coordinator.is_master()) as pbar: for step, batch in enumerate(pbar): performance_evaluator.on_step_start(step) outputs = model(**batch) loss = outputs[0] del outputs # free memory pbar.set_postfix({"loss": loss.item()}) booster.backward(loss, optimizer) optimizer.step() optimizer.zero_grad() performance_evaluator.on_step_end(**batch) prof.step() performance_evaluator.on_fit_end() coordinator.print_on_master(f"Max CUDA memory usage: {get_accelerator().max_memory_allocated()/1024**2:.2f} MB") if __name__ == "__main__": main()
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/deepseek/performance_evaluator.py
examples/language/deepseek/performance_evaluator.py
from time import time from typing import Optional import torch import torch.distributed as dist from torch import Tensor from torch.profiler import ProfilerActivity, profile, schedule, tensorboard_trace_handler from colossalai.cluster import DistCoordinator from colossalai.utils import get_current_device def divide(x: float, y: float) -> float: if y == 0: return float("inf") elif y == float("inf"): return float("nan") return x / y @torch.no_grad() def all_reduce_mean(x: float, world_size: int) -> float: if world_size == 1: return x # BUG: RuntimeError: Invalid scalar type when use dist.all_reduce(tensor, group=gloo_group) # # Use CPU tensor to avoid OOM/weird NCCl error # gloo_group = dist.new_group(backend="gloo") # tensor = torch.tensor([x], device="cpu") # dist.all_reduce(tensor, group=gloo_group) # tensor = tensor / world_size # return tensor.item() tensor = torch.tensor([x], device=get_current_device(), dtype=torch.float) dist.all_reduce(tensor) tensor = tensor / world_size return tensor.item() def get_profile_context(enable_flag, warmup_steps, active_steps, save_dir, nsys=False): class DummyProfiler: def __init__(self): self.step_number = 0 def step(self): self.step_number += 1 def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass class NsysProfiler: def __init__(self, warmup_steps, active_steps): self.step_number = 0 self.warmup_steps = warmup_steps self.active_steps = active_steps def step(self): if self.step_number == self.warmup_steps: torch.cuda.cudart().cudaProfilerStart() elif self.step_number == self.warmup_steps + self.active_steps: torch.cuda.cudart().cudaProfilerStop() self.step_number += 1 def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass if enable_flag: if nsys: return NsysProfiler(warmup_steps, active_steps) return profile( activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], schedule=schedule(wait=0, warmup=warmup_steps, active=active_steps), on_trace_ready=tensorboard_trace_handler(save_dir), record_shapes=True, profile_memory=True, with_stack=True, ) else: return DummyProfiler() class Timer: def __init__(self) -> None: self.start_time: Optional[float] = None self.duration: float = 0.0 def start(self) -> None: self.start_time = time() def end(self) -> None: assert self.start_time is not None self.duration += time() - self.start_time self.start_time = None def reset(self) -> None: self.duration = 0.0 class PerformanceEvaluator: """ Callback for valuate the performance of the model. Args: actor_num_params: The number of parameters of the actor model. critic_num_params: The number of parameters of the critic model. initial_model_num_params: The number of parameters of the initial model. reward_model_num_params: The number of parameters of the reward model. enable_grad_checkpoint: Whether to enable gradient checkpointing. ignore_episodes: The number of episodes to ignore when calculating the performance. """ def __init__( self, model_numel: int, num_layers: int, hidden_size: int, vocab_size: int, enable_grad_checkpoint: bool = False, ignore_steps: int = 0, dp_world_size: Optional[int] = None, ) -> None: self.model_numel = model_numel self.enable_grad_checkpoint = enable_grad_checkpoint self.ignore_steps = ignore_steps self.num_layers = num_layers self.hidden_size = hidden_size self.vocab_size = vocab_size self.coordinator = DistCoordinator() self.dp_world_size = dp_world_size or self.coordinator.world_size self.disable: bool = False self.timer = Timer() self.num_samples: int = 0 self.flop_megatron = 0 self.flop: int = 0 def on_step_start(self, step: int) -> None: self.disable = self.ignore_steps > 0 and step < self.ignore_steps if self.disable: return # get_accelerator().synchronize() self.timer.start() def on_step_end(self, input_ids: Tensor, **kwargs) -> None: if self.disable: return # get_accelerator().synchronize() self.timer.end() batch_size, seq_len = input_ids.shape self.num_samples += batch_size checkpoint_activations_factor = 3 + int(self.enable_grad_checkpoint) self.flop_megatron += ( 24 * checkpoint_activations_factor * batch_size * seq_len * self.num_layers * (self.hidden_size**2) ) * ( 1.0 + (seq_len / (6.0 * self.hidden_size)) + (self.vocab_size / (16.0 * self.num_layers * self.hidden_size)) ) self.flop += batch_size * seq_len * self.model_numel * 2 * (3 + int(self.enable_grad_checkpoint)) def on_fit_end(self) -> None: avg_duration = all_reduce_mean(self.timer.duration, self.coordinator.world_size) avg_throughput = self.num_samples * self.dp_world_size / (avg_duration + 1e-12) mp_world_size = self.coordinator.world_size // self.dp_world_size avg_tflops_per_gpu_megatron = self.flop_megatron / 1e12 / (avg_duration + 1e-12) / mp_world_size avg_tflops_per_gpu = self.flop / 1e12 / (avg_duration + 1e-12) / mp_world_size self.coordinator.print_on_master( f"num_samples: {self.num_samples}, dp_world_size: {self.dp_world_size}, flop_megatron: {self.flop_megatron}, flop: {self.flop}, avg_duration: {avg_duration}, " f"avg_throughput: {avg_throughput}" ) self.coordinator.print_on_master( f"Throughput: {avg_throughput:.2f} samples/sec, TFLOPS per GPU by Megatron: {avg_tflops_per_gpu_megatron:.2f}, TFLOPS per GPU: {avg_tflops_per_gpu:.2f}" )
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/llama/data_utils.py
examples/language/llama/data_utils.py
import json import random from typing import Iterator, Optional import numpy as np import torch from torch.distributed import ProcessGroup from torch.distributed.distributed_c10d import _get_default_group from torch.utils.data import DataLoader, Dataset, DistributedSampler from colossalai.accelerator import get_accelerator class StatefulDistributedSampler(DistributedSampler): def __init__( self, dataset: Dataset, num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed: int = 0, drop_last: bool = False, ) -> None: super().__init__(dataset, num_replicas, rank, shuffle, seed, drop_last) self.start_index: int = 0 def __iter__(self) -> Iterator: iterator = super().__iter__() indices = list(iterator) indices = indices[self.start_index :] return iter(indices) def __len__(self) -> int: return self.num_samples - self.start_index def set_start_index(self, start_index: int) -> None: self.start_index = start_index def prepare_dataloader( dataset, batch_size, shuffle=False, seed=1024, drop_last=False, pin_memory=False, num_workers=0, process_group: Optional[ProcessGroup] = None, **kwargs, ): r""" Prepare a dataloader for distributed training. The dataloader will be wrapped by `torch.utils.data.DataLoader` and `StatefulDistributedSampler`. Args: dataset (`torch.utils.data.Dataset`): The dataset to be loaded. shuffle (bool, optional): Whether to shuffle the dataset. Defaults to False. seed (int, optional): Random worker seed for sampling, defaults to 1024. add_sampler: Whether to add ``DistributedDataParallelSampler`` to the dataset. Defaults to True. drop_last (bool, optional): Set to True to drop the last incomplete batch, if the dataset size is not divisible by the batch size. If False and the size of dataset is not divisible by the batch size, then the last batch will be smaller, defaults to False. pin_memory (bool, optional): Whether to pin memory address in CPU memory. Defaults to False. num_workers (int, optional): Number of worker threads for this dataloader. Defaults to 0. kwargs (dict): optional parameters for ``torch.utils.data.DataLoader``, more details could be found in `DataLoader <https://pytorch.org/docs/stable/_modules/torch/utils/data/dataloader.html#DataLoader>`_. Returns: :class:`torch.utils.data.DataLoader`: A DataLoader used for training or testing. """ _kwargs = kwargs.copy() process_group = process_group or _get_default_group() sampler = StatefulDistributedSampler( dataset, num_replicas=process_group.size(), rank=process_group.rank(), shuffle=shuffle ) # Deterministic dataloader def seed_worker(worker_id): worker_seed = seed np.random.seed(worker_seed) torch.manual_seed(worker_seed) random.seed(worker_seed) return DataLoader( dataset, batch_size=batch_size, sampler=sampler, worker_init_fn=seed_worker, drop_last=drop_last, pin_memory=pin_memory, num_workers=num_workers, **_kwargs, ) def load_json(file_path: str): with open(file_path, "r") as f: return json.load(f) def save_json(data, file_path: str): with open(file_path, "w") as f: json.dump(data, f, indent=4) class RandomDataset(Dataset): def __init__(self, num_samples: int = 1000, max_length: int = 2048, vocab_size: int = 32000): self.num_samples = num_samples self.max_length = max_length self.input_ids = torch.randint( 0, vocab_size, (num_samples, max_length), device=get_accelerator().get_current_device() ) self.attention_mask = torch.ones_like(self.input_ids) def __len__(self): return self.num_samples def __getitem__(self, idx): return { "input_ids": self.input_ids[idx], "attention_mask": self.attention_mask[idx], "labels": self.input_ids[idx], }
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/llama/model_utils.py
examples/language/llama/model_utils.py
from contextlib import contextmanager import torch import torch.nn as nn @contextmanager def low_precision_init(target_dtype: torch.dtype = torch.float16): dtype = torch.get_default_dtype() try: torch.set_default_dtype(target_dtype) yield finally: torch.set_default_dtype(dtype) def get_model_numel(model: nn.Module) -> int: return sum(p.numel() for p in model.parameters()) def format_numel_str(numel: int) -> str: B = 1024**3 M = 1024**2 K = 1024 if numel >= B: return f"{numel / B:.2f} B" elif numel >= M: return f"{numel / M:.2f} M" elif numel >= K: return f"{numel / K:.2f} K" else: return f"{numel}"
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/llama/benchmark.py
examples/language/llama/benchmark.py
import argparse import resource import time import warnings from contextlib import nullcontext import torch import torch.distributed as dist from data_utils import RandomDataset from model_utils import format_numel_str, get_model_numel from performance_evaluator import PerformanceEvaluator, get_profile_context from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload, MixedPrecision from tqdm import tqdm from transformers import AutoConfig, AutoModelForCausalLM from transformers.models.llama.configuration_llama import LlamaConfig import colossalai from colossalai.accelerator import get_accelerator from colossalai.booster import Booster from colossalai.booster.plugin import GeminiPlugin, HybridParallelPlugin, TorchFSDPPlugin from colossalai.cluster import DistCoordinator from colossalai.lazy import LazyInitContext from colossalai.nn.optimizer import HybridAdam from colossalai.pipeline.schedule.v_schedule import PipelineGraph from colossalai.shardformer import PipelineGradientCheckpointConfig warnings.filterwarnings("ignore") # ============================== # Constants # ============================== # We have lots of llamas for your choice! MODEL_CONFIGS = { "100m": LlamaConfig( max_position_embeddings=4096, num_hidden_layers=4, num_attention_heads=32, intermediate_size=2048, hidden_size=1024, ), "5b": LlamaConfig(max_position_embeddings=4096, num_key_value_heads=8), "7b": LlamaConfig(max_position_embeddings=4096), # "7b": LlamaConfig(num_hidden_layers=4, max_position_embeddings=4096), "13b": LlamaConfig( hidden_size=5120, intermediate_size=13824, num_hidden_layers=40, num_attention_heads=40, max_position_embeddings=4096, ), "70b": LlamaConfig( hidden_size=8192, intermediate_size=28672, num_hidden_layers=80, num_attention_heads=64, max_position_embeddings=4096, num_key_value_heads=8, ), } def main(): # ============================== # Parse Arguments # ============================== parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", type=str, default="7b", help="Model configuration") parser.add_argument( "-p", "--plugin", choices=["gemini", "gemini_auto", "fsdp", "fsdp_cpu", "3d", "3d_cpu"], default="gemini", help="Choose which plugin to use", ) parser.add_argument("-b", "--batch_size", type=int, default=2, help="Batch size") parser.add_argument("-s", "--num_steps", type=int, default=5, help="Number of steps to run") parser.add_argument("-i", "--ignore_steps", type=int, default=2, help="Number of steps to ignore") parser.add_argument("-g", "--grad_checkpoint", action="store_true", help="Use gradient checkpointing") parser.add_argument("-l", "--max_length", type=int, default=4096, help="Max sequence length") parser.add_argument( "-w", "--warmup_ratio", type=float, default=0.8, help="warm up ratio of non-model data. Only for gemini-auto" ) parser.add_argument("-m", "--memory_limit", type=int, help="Gemini memory limit in mb") parser.add_argument("-x", "--xformers", action="store_true", help="Use xformers") parser.add_argument("--shard_param_frac", type=float, default=1.0, help="Shard param fraction. Only for gemini") parser.add_argument("--offload_optim_frac", type=float, default=0.0, help="Offload optim fraction. Only for gemini") parser.add_argument("--offload_param_frac", type=float, default=0.0, help="Offload param fraction. Only for gemini") parser.add_argument("--tp", type=int, default=1, help="Tensor parallel size") parser.add_argument("--sp", type=int, default=1, help="Sequence parallel size") parser.add_argument("--extra_dp", type=int, default=1, help="Extra data parallel size, used for Gemini") parser.add_argument("--pp", type=int, default=1, help="Pipeline parallel size") parser.add_argument("--mbs", type=int, default=1, help="Micro batch size of pipeline parallel") parser.add_argument("--zero", type=int, default=0, help="Zero Stage when hybrid plugin is enabled") parser.add_argument("--custom-ckpt", action="store_true", help="Customize checkpoint", default=False) parser.add_argument("--pp_style", default="1f1b", choices=["1f1b", "interleaved", "zbv"]) parser.add_argument("--n_chunks", default=1, help="number of model chunks", type=eval) parser.add_argument("--profile", action="store_true", help="Profile the code") parser.add_argument( "--nsys", action="store_true", help="Use nsys for profiling. \ You should put something like this before colossalai launch: \ nsys profile -w true -t cuda,cudnn,cublas -s cpu --capture-range=cudaProfilerApi --capture-range-end=stop --cudabacktrace=true -x true --python-backtrace=cuda -o prof_out", ) parser.add_argument("--disable-async-reduce", action="store_true", help="Disable the asynchronous reduce operation") parser.add_argument("--prefetch_num", type=int, default=0, help="chunk prefetch max number") parser.add_argument("--no_cache", action="store_true") parser.add_argument("--use_fp8_comm", action="store_true", default=False, help="for using fp8 during communication") parser.add_argument("--use_fp8", action="store_true", default=False, help="for using fp8 linear") parser.add_argument("--overlap_p2p", action="store_true", default=True, help="for using overlap p2p") parser.add_argument("--overlap_allgather", action="store_true") parser.add_argument( "--sp_mode", default="all_to_all", choices=["all_to_all", "ring_attn", "ring", "split_gather"], help="Sequence parallelism mode", ) args = parser.parse_args() colossalai.launch_from_torch() coordinator = DistCoordinator() def empty_init(): pass # ckpt config for LLaMA3-70B on 64 H100 GPUs hybrid_kwargs = ( { "gradient_checkpoint_config": PipelineGradientCheckpointConfig( num_ckpt_layers_per_stage=[19, 19, 19, 13], ), "num_layers_per_stage": [19, 20, 20, 21], "pp_style": "interleaved", } if args.custom_ckpt else {} ) # ============================== # Initialize Booster # ============================== if args.config in MODEL_CONFIGS: config = MODEL_CONFIGS[args.config] else: config = AutoConfig.from_pretrained(args.config, trust_remote_code=True) use_empty_init = True if args.plugin == "gemini": plugin = GeminiPlugin( precision="bf16", shard_param_frac=args.shard_param_frac, offload_optim_frac=args.offload_optim_frac, offload_param_frac=args.offload_param_frac, tp_size=args.tp, extra_dp_size=args.extra_dp, enable_fused_normalization=get_accelerator().is_available(), enable_flash_attention=args.xformers, max_prefetch=args.prefetch_num, enable_async_reduce=not args.disable_async_reduce, use_fp8=args.use_fp8, fp8_communication=args.use_fp8_comm, ) elif args.plugin == "gemini_auto": plugin = GeminiPlugin( placement_policy="auto", precision="bf16", warmup_non_model_data_ratio=args.warmup_ratio, tp_size=args.tp, extra_dp_size=args.extra_dp, enable_fused_normalization=get_accelerator().is_available(), max_prefetch=args.prefetch_num, enable_async_reduce=not args.disable_async_reduce, enable_flash_attention=args.xformers, use_fp8=args.use_fp8, fp8_communication=args.use_fp8_comm, ) elif args.plugin == "fsdp": if use_empty_init: plugin = TorchFSDPPlugin( mixed_precision=MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16, ), param_init_fn=empty_init(), fp8_communication=args.use_fp8_comm, ) else: plugin = TorchFSDPPlugin( mixed_precision=MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16, ), fp8_communication=args.use_fp8_comm, ) elif args.plugin == "fsdp_cpu": if use_empty_init: plugin = TorchFSDPPlugin( mixed_precision=MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16, ), cpu_offload=CPUOffload(offload_params=True), param_init_fn=empty_init(), fp8_communication=args.use_fp8_comm, ) else: plugin = TorchFSDPPlugin( mixed_precision=MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16, ), cpu_offload=CPUOffload(offload_params=True), fp8_communication=args.use_fp8_comm, ) elif args.plugin == "3d": if args.pp_style == "zbv": mem_f = 34 * config.hidden_size + 5 * config.num_attention_heads * args.max_length mem_w = -32 * config.hidden_size mem_b = -mem_w - mem_f scheduler_nodes = PipelineGraph( n_stage=args.pp, n_micro=args.batch_size // args.mbs, f_cost=1000, b_cost=1000, w_cost=1000, c_cost=1, f_mem=mem_f * 1.5, b_mem=mem_b * 1.5, w_mem=mem_w * 1.5, ).get_v_schedule() else: scheduler_nodes = None plugin = HybridParallelPlugin( tp_size=args.tp, pp_size=args.pp, pp_style=args.pp_style, num_model_chunks=args.n_chunks, zero_stage=args.zero, sp_size=args.sp, sequence_parallelism_mode=args.sp_mode, enable_sequence_parallelism=args.sp > 1, enable_fused_normalization=get_accelerator().is_available(), enable_flash_attention=args.xformers, microbatch_size=args.mbs, precision="bf16", enable_metadata_cache=not args.no_cache, overlap_allgather=args.overlap_allgather, use_fp8=args.use_fp8, fp8_communication=args.use_fp8_comm, scheduler_nodes=scheduler_nodes, **hybrid_kwargs, ) elif args.plugin == "3d_cpu": plugin = HybridParallelPlugin( tp_size=args.tp, pp_size=args.pp, pp_style=args.pp_style, num_model_chunks=args.n_chunks, zero_stage=args.zero, cpu_offload=True, enable_fused_normalization=get_accelerator().is_available(), enable_flash_attention=args.xformers, microbatch_size=args.mbs, initial_scale=2**8, precision="bf16", overlap_p2p=args.overlap_p2p, use_fp8=args.use_fp8, fp8_communication=args.use_fp8_comm, ) else: raise ValueError(f"Unknown plugin {args.plugin}") booster = Booster(plugin=plugin) # ============================== # Initialize Dataset and Dataloader # ============================== dp_size = getattr(plugin, "dp_size", coordinator.world_size) if args.config in MODEL_CONFIGS: config = MODEL_CONFIGS[args.config] else: config = AutoConfig.from_pretrained(args.config, trust_remote_code=True) get_accelerator().manual_seed(42) dataset = RandomDataset( num_samples=args.batch_size * args.num_steps * dp_size, max_length=args.max_length, vocab_size=config.vocab_size ) dataloader = plugin.prepare_dataloader(dataset, batch_size=args.batch_size, shuffle=True, drop_last=True, seed=42) # ============================== # Initialize Model and Optimizer # ============================== init_ctx = ( LazyInitContext(default_device=get_accelerator().get_current_device()) if isinstance(plugin, (GeminiPlugin, HybridParallelPlugin)) else nullcontext() ) init_kwargs = {} if config.model_type == "chatglm": init_kwargs["empty_init"] = False with init_ctx: model = AutoModelForCausalLM.from_config( config, trust_remote_code=True, **init_kwargs, torch_dtype=torch.bfloat16, ) if args.grad_checkpoint: model.gradient_checkpointing_enable() if config.model_type == "chatglm": model.transformer.encoder.gradient_checkpointing = True model_numel = get_model_numel(model) coordinator.print_on_master(f"Model params: {format_numel_str(model_numel)}") if config.model_type == "chatglm": num_layers = model.config.num_layers else: num_layers = model.config.num_hidden_layers performance_evaluator = PerformanceEvaluator( model_numel, num_layers, model.config.hidden_size, model.config.vocab_size, args.grad_checkpoint, args.ignore_steps, dp_world_size=dp_size, ) optimizer = HybridAdam(model.parameters()) torch.set_default_dtype(torch.bfloat16) model, optimizer, _, dataloader, _ = booster.boost(model, optimizer, dataloader=dataloader) torch.set_default_dtype(torch.float) coordinator.print_on_master( f"Booster init max device memory: {get_accelerator().max_memory_allocated()/1024**2:.2f} MB" ) coordinator.print_on_master( f"Booster init max CPU memory: {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024:.2f} MB" ) with get_profile_context( args.profile, args.ignore_steps, 1, # avoid creating massive log files save_dir=f"./profile/{time.strftime('%H:%M', time.localtime())}-{args.plugin}-llama-{args.config}", nsys=args.nsys, ) as prof: if isinstance(plugin, HybridParallelPlugin) and args.pp > 1: data_iter = iter(dataloader) for step in tqdm(range(len(dataloader)), desc="Step", disable=not coordinator.is_master()): performance_evaluator.on_step_start(step) outputs = booster.execute_pipeline( data_iter, model, criterion=lambda outputs, inputs: outputs[0], optimizer=optimizer, return_loss=True, ) loss = outputs["loss"] if args.pp_style == "zbv": if coordinator.is_master(): print(f"Step {step} loss: {loss}") else: if coordinator.is_last_process(): print(f"Step {step} loss: {loss}") optimizer.step() optimizer.zero_grad() performance_evaluator.on_step_end(input_ids=torch.empty(args.batch_size, args.max_length)) prof.step() else: for step, batch in enumerate(tqdm(dataloader, desc="Step", disable=not coordinator.is_master())): performance_evaluator.on_step_start(step) outputs = model(**batch) loss = outputs[0] del outputs # free memory if dist.get_rank() == dist.get_world_size() - 1: print(f"Step {step} loss: {loss}") booster.backward(loss, optimizer) optimizer.step() optimizer.zero_grad() performance_evaluator.on_step_end(**batch) prof.step() performance_evaluator.on_fit_end() coordinator.print_on_master(f"Max device memory usage: {get_accelerator().max_memory_allocated()/1024**2:.2f} MB") if __name__ == "__main__": main()
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
hpcaitech/ColossalAI
https://github.com/hpcaitech/ColossalAI/blob/b1915d2889543949eb5b610241f1515c73df5059/examples/language/llama/performance_evaluator.py
examples/language/llama/performance_evaluator.py
from time import time from typing import Optional import torch import torch.distributed as dist from torch import Tensor from torch.profiler import ProfilerActivity, profile, schedule, tensorboard_trace_handler from colossalai.cluster import DistCoordinator from colossalai.utils import get_current_device def divide(x: float, y: float) -> float: if y == 0: return float("inf") elif y == float("inf"): return float("nan") return x / y @torch.no_grad() def all_reduce_mean(x: float, world_size: int) -> float: if world_size == 1: return x # BUG: RuntimeError: Invalid scalar type when use dist.all_reduce(tensor, group=gloo_group) # # Use CPU tensor to avoid OOM/weird NCCl error # gloo_group = dist.new_group(backend="gloo") # tensor = torch.tensor([x], device="cpu") # dist.all_reduce(tensor, group=gloo_group) # tensor = tensor / world_size # return tensor.item() tensor = torch.tensor([x], device=get_current_device(), dtype=torch.float) dist.all_reduce(tensor) tensor = tensor / world_size return tensor.item() def get_profile_context(enable_flag, warmup_steps, active_steps, save_dir, nsys=False): class DummyProfiler: def __init__(self): self.step_number = 0 def step(self): self.step_number += 1 def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass class NsysProfiler: def __init__(self, warmup_steps, active_steps): self.step_number = 0 self.warmup_steps = warmup_steps self.active_steps = active_steps def step(self): if self.step_number == self.warmup_steps: torch.cuda.cudart().cudaProfilerStart() elif self.step_number == self.warmup_steps + self.active_steps: torch.cuda.cudart().cudaProfilerStop() self.step_number += 1 def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass if enable_flag: if nsys: return NsysProfiler(warmup_steps, active_steps) return profile( activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], schedule=schedule(wait=0, warmup=warmup_steps, active=active_steps), on_trace_ready=tensorboard_trace_handler(save_dir), record_shapes=True, profile_memory=True, with_stack=True, ) else: return DummyProfiler() class Timer: def __init__(self) -> None: self.start_time: Optional[float] = None self.duration: float = 0.0 def start(self) -> None: self.start_time = time() def end(self) -> None: assert self.start_time is not None self.duration += time() - self.start_time self.start_time = None def reset(self) -> None: self.duration = 0.0 class PerformanceEvaluator: """ Callback for valuate the performance of the model. Args: actor_num_params: The number of parameters of the actor model. critic_num_params: The number of parameters of the critic model. initial_model_num_params: The number of parameters of the initial model. reward_model_num_params: The number of parameters of the reward model. enable_grad_checkpoint: Whether to enable gradient checkpointing. ignore_episodes: The number of episodes to ignore when calculating the performance. """ def __init__( self, model_numel: int, num_layers: int, hidden_size: int, vocab_size: int, enable_grad_checkpoint: bool = False, ignore_steps: int = 0, dp_world_size: Optional[int] = None, ) -> None: self.model_numel = model_numel self.enable_grad_checkpoint = enable_grad_checkpoint self.ignore_steps = ignore_steps self.num_layers = num_layers self.hidden_size = hidden_size self.vocab_size = vocab_size self.coordinator = DistCoordinator() self.dp_world_size = dp_world_size or self.coordinator.world_size self.disable: bool = False self.timer = Timer() self.num_samples: int = 0 self.flop_megatron = 0 self.flop: int = 0 def on_step_start(self, step: int) -> None: self.disable = self.ignore_steps > 0 and step < self.ignore_steps if self.disable: return # get_accelerator().synchronize() self.timer.start() def on_step_end(self, input_ids: Tensor, **kwargs) -> None: if self.disable: return # get_accelerator().synchronize() self.timer.end() batch_size, seq_len = input_ids.shape self.num_samples += batch_size checkpoint_activations_factor = 3 + int(self.enable_grad_checkpoint) self.flop_megatron += ( 24 * checkpoint_activations_factor * batch_size * seq_len * self.num_layers * (self.hidden_size**2) ) * ( 1.0 + (seq_len / (6.0 * self.hidden_size)) + (self.vocab_size / (16.0 * self.num_layers * self.hidden_size)) ) self.flop += batch_size * seq_len * self.model_numel * 2 * (3 + int(self.enable_grad_checkpoint)) def on_fit_end(self) -> None: avg_duration = all_reduce_mean(self.timer.duration, self.coordinator.world_size) avg_throughput = self.num_samples * self.dp_world_size / (avg_duration + 1e-12) mp_world_size = self.coordinator.world_size // self.dp_world_size avg_tflops_per_gpu_megatron = self.flop_megatron / 1e12 / (avg_duration + 1e-12) / mp_world_size avg_tflops_per_gpu = self.flop / 1e12 / (avg_duration + 1e-12) / mp_world_size self.coordinator.print_on_master( f"num_samples: {self.num_samples}, dp_world_size: {self.dp_world_size}, flop_megatron: {self.flop_megatron}, flop: {self.flop}, avg_duration: {avg_duration}, " f"avg_throughput: {avg_throughput}" ) self.coordinator.print_on_master( f"Throughput: {avg_throughput:.2f} samples/sec, TFLOPS per GPU by Megatron: {avg_tflops_per_gpu_megatron:.2f}, TFLOPS per GPU: {avg_tflops_per_gpu:.2f}" )
python
Apache-2.0
b1915d2889543949eb5b610241f1515c73df5059
2026-01-04T14:40:19.002665Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/setup.py
setup.py
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Simple check list from AllenNLP repo: https://github.com/allenai/allennlp/blob/main/setup.py To create the package for pypi. 1. Create the release branch named: v<RELEASE>-release, for example v4.19-release. For a patch release checkout the current release branch. If releasing on a special branch, copy the updated README.md on the main branch for the commit you will make for the post-release and run `make fix-copies` on the main branch as well. 2. Run `make pre-release` (or `make pre-patch` for a patch release) and commit these changes with the message: "Release: <VERSION>" and push. 3. Go back to the main branch and run `make post-release` then `make fix-copies`. Commit these changes with the message "v<NEXT_VERSION>.dev.0" and push to main. # If you were just cutting the branch in preparation for a release, you can stop here for now. 4. Wait for the tests on the release branch to be completed and be green (otherwise revert and fix bugs) 5. On the release branch, add a tag in git to mark the release: "git tag v<VERSION> -m 'Adds tag v<VERSION> for pypi' " Push the tag to git: git push --tags origin v<RELEASE>-release 6. Have a core maintainer review and approve the deployment to pypi. """ import re import shutil from pathlib import Path from setuptools import Command, find_packages, setup # Remove stale transformers.egg-info directory to avoid https://github.com/pypa/pip/issues/5466 stale_egg_info = Path(__file__).parent / "transformers.egg-info" if stale_egg_info.exists(): print( f"Warning: {stale_egg_info} exists.\n\n" "If you recently updated transformers to 3.0 or later, this is expected,\n" "but it may prevent transformers from installing in editable mode.\n\n" "This directory is automatically generated by Python's packaging tools.\n" "I will remove it now.\n\n" "See https://github.com/pypa/pip/issues/5466 for details.\n" ) shutil.rmtree(stale_egg_info) # IMPORTANT: # 1. all dependencies should be listed here with their version requirements if any # 2. once modified, run: `make deps_table_update` to update src/transformers/dependency_versions_table.py _deps = [ "Pillow>=10.0.1,<=15.0", "accelerate>=1.1.0", "av", "beautifulsoup4", "blobfile", "codecarbon>=2.8.1", "cookiecutter==1.7.3", "datasets>=2.15.0", # We need either this pin or pyarrow<21.0.0 "deepspeed>=0.9.3", "diffusers", "dill<0.3.5", "evaluate>=0.4.6", "faiss-cpu", "fastapi", "filelock", "ftfy", "fugashi>=1.0", "GitPython<3.1.19", "hf-doc-builder>=0.3.0", "hf_xet", "huggingface-hub>=1.2.1,<2.0", "importlib_metadata", "ipadic>=1.0.0,<2.0", "jinja2>=3.1.0", "jmespath>=1.0.1", "kenlm", "kernels>=0.10.2,<0.11", "librosa", "natten>=0.14.6,<0.15.0", "nltk<=3.8.1", "num2words", "numpy>=1.17", "openai>=1.98.0", "opencv-python", "optimum-benchmark>=0.3.0", "optuna", "pandas<2.3.0", # `datasets` requires `pandas` while `pandas==2.3.0` has issues with CircleCI on 2025/06/05 "packaging>=20.0", "parameterized>=0.9", # older version of parameterized cause pytest collection to fail on .expand "peft>=0.18.0", "phonemizer", "protobuf", "psutil", "pyyaml>=5.1", "pydantic>=2", "pytest>=7.2.0,<9.0.0", "pytest-asyncio>=1.2.0", "pytest-rerunfailures<16.0", "pytest-timeout", "pytest-xdist", "pytest-order", "python>=3.10.0", "ray[tune]>=2.7.0", "regex!=2019.12.17", "requests", "rhoknp>=1.1.0,<1.3.1", "rjieba", "rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1", "ruff==0.13.1", # `sacrebleu` not used in `transformers`. However, it is needed in several tests, when a test calls # `evaluate.load("sacrebleu")`. This metric is used in the examples that we use to test the `Trainer` with, in the # `Trainer` tests (see references to `run_translation.py`). "sacrebleu>=1.4.12,<2.0.0", "sacremoses", "safetensors>=0.4.3", "sagemaker>=2.31.0", "schedulefree>=1.2.6", "scikit-learn", "scipy", "sentencepiece>=0.1.91,!=0.1.92", "starlette", "sudachipy>=0.6.6", "sudachidict_core>=20220729", "tensorboard", "timeout-decorator", "tiktoken", "timm>=1.0.20", "tokenizers>=0.22.0,<=0.23.0", "torch>=2.2", "torchaudio", "torchvision", "pyctcdecode>=0.4.0", "tqdm>=4.27", "typer-slim", "unidic>=1.0.2", "unidic_lite>=1.0.7", "urllib3<2.0.0", "uvicorn", "pytest-rich", "libcst", "rich", "opentelemetry-api", "mistral-common[opencv]>=1.6.3", ] # this is a lookup table with items like: # # tokenizers: "tokenizers==0.9.4" # packaging: "packaging" # # some of the values are versioned whereas others aren't. deps = {b: a for a, b in (re.findall(r"^(([^!=<>~ ]+)(?:[!=<>~ ].*)?$)", x)[0] for x in _deps)} # since we save this data in src/transformers/dependency_versions_table.py it can be easily accessed from # anywhere. If you need to quickly access the data from this table in a shell, you can do so easily with: # # python -c 'import sys; from transformers.dependency_versions_table import deps; \ # print(" ".join([ deps[x] for x in sys.argv[1:]]))' tokenizers datasets # # Just pass the desired package names to that script as it's shown with 2 packages above. # # If transformers is not yet installed and the work is done from the cloned repo remember to add `PYTHONPATH=src` to the script above # # You can then feed this for example to `pip`: # # pip install -U $(python -c 'import sys; from transformers.dependency_versions_table import deps; \ # print(" ".join([deps[x] for x in sys.argv[1:]]))' tokenizers datasets) # def deps_list(*pkgs): return [deps[pkg] for pkg in pkgs] class DepsTableUpdateCommand(Command): """ A custom distutils command that updates the dependency table. usage: python setup.py deps_table_update """ description = "build runtime dependency table" user_options = [ # format: (long option, short option, description). ("dep-table-update", None, "updates src/transformers/dependency_versions_table.py"), ] def initialize_options(self): pass def finalize_options(self): pass def run(self): entries = "\n".join([f' "{k}": "{v}",' for k, v in deps.items()]) content = [ "# THIS FILE HAS BEEN AUTOGENERATED. To update:", "# 1. modify the `_deps` dict in setup.py", "# 2. run `make deps_table_update``", "deps = {", entries, "}", "", ] target = "src/transformers/dependency_versions_table.py" print(f"updating {target}") with open(target, "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(content)) extras = {} extras["ja"] = deps_list("fugashi", "ipadic", "unidic_lite", "unidic", "sudachipy", "sudachidict_core", "rhoknp") extras["sklearn"] = deps_list("scikit-learn") extras["torch"] = deps_list("torch", "accelerate") extras["accelerate"] = deps_list("accelerate") extras["hf_xet"] = deps_list("hf_xet") extras["retrieval"] = deps_list("faiss-cpu", "datasets") extras["tokenizers"] = deps_list("tokenizers") extras["ftfy"] = deps_list("ftfy") extras["modelcreation"] = deps_list("cookiecutter") extras["sagemaker"] = deps_list("sagemaker") extras["deepspeed"] = deps_list("deepspeed") + extras["accelerate"] extras["optuna"] = deps_list("optuna") extras["ray"] = deps_list("ray[tune]") extras["hub-kernels"] = deps_list("kernels") extras["integrations"] = extras["hub-kernels"] + extras["optuna"] + extras["ray"] extras["serving"] = deps_list("openai", "pydantic", "uvicorn", "fastapi", "starlette", "rich") + extras["torch"] extras["audio"] = deps_list( "librosa", "pyctcdecode", "phonemizer", "kenlm", ) # `pip install ".[speech]"` is deprecated and `pip install ".[torch-speech]"` should be used instead extras["speech"] = deps_list("torchaudio") + extras["audio"] extras["torch-speech"] = deps_list("torchaudio") + extras["audio"] extras["vision"] = deps_list("Pillow") extras["timm"] = deps_list("timm") extras["torch-vision"] = deps_list("torchvision") + extras["vision"] extras["natten"] = deps_list("natten") extras["codecarbon"] = deps_list("codecarbon") extras["video"] = deps_list("av") extras["num2words"] = deps_list("num2words") extras["sentencepiece"] = deps_list("sentencepiece", "protobuf") extras["tiktoken"] = deps_list("tiktoken", "blobfile") extras["mistral-common"] = deps_list("mistral-common[opencv]") extras["chat_template"] = deps_list("jinja2", "jmespath") extras["testing"] = ( deps_list( "pytest", "pytest-asyncio", "pytest-rich", "pytest-xdist", "pytest-order", "pytest-rerunfailures", "timeout-decorator", "parameterized", "psutil", "datasets", "dill", "evaluate", "pytest-timeout", "ruff", "rouge-score", "nltk", "GitPython", "sacremoses", "rjieba", "beautifulsoup4", "tensorboard", "pydantic", "sentencepiece", "sacrebleu", # needed in trainer tests, see references to `run_translation.py` "libcst", ) + extras["retrieval"] + extras["modelcreation"] + extras["mistral-common"] + extras["serving"] ) extras["deepspeed-testing"] = extras["deepspeed"] + extras["testing"] + extras["optuna"] + extras["sentencepiece"] extras["ruff"] = deps_list("ruff") extras["quality"] = deps_list("datasets", "ruff", "GitPython", "urllib3", "libcst", "rich", "pandas") extras["all"] = ( extras["torch"] + extras["sentencepiece"] + extras["tokenizers"] + extras["torch-speech"] + extras["vision"] + extras["integrations"] + extras["timm"] + extras["torch-vision"] + extras["codecarbon"] + extras["accelerate"] + extras["video"] + extras["num2words"] + extras["mistral-common"] + extras["chat_template"] ) extras["dev-torch"] = ( extras["testing"] + extras["torch"] + extras["sentencepiece"] + extras["tokenizers"] + extras["torch-speech"] + extras["vision"] + extras["integrations"] + extras["timm"] + extras["torch-vision"] + extras["codecarbon"] + extras["quality"] + extras["ja"] + extras["sklearn"] + extras["modelcreation"] + extras["num2words"] ) extras["dev"] = ( extras["all"] + extras["testing"] + extras["quality"] + extras["ja"] + extras["sklearn"] + extras["modelcreation"] ) extras["torchhub"] = deps_list( "filelock", "huggingface-hub", "importlib_metadata", "numpy", "packaging", "protobuf", "regex", "requests", "sentencepiece", "torch", "tokenizers", "tqdm", ) extras["benchmark"] = deps_list("optimum-benchmark") # OpenTelemetry dependencies for metrics collection in continuous batching # TODO: refactor this to split API and SDK; SDK and exporter should only be needed to run code that collects metrics whereas API is what people will need to instrument their code and handle exporter themselves extras["open-telemetry"] = deps_list("opentelemetry-api") + ["opentelemetry-exporter-otlp", "opentelemetry-sdk"] # when modifying the following list, make sure to update src/transformers/dependency_versions_check.py install_requires = [ deps["filelock"], # filesystem locks, e.g., to prevent parallel downloads deps["huggingface-hub"], deps["numpy"], deps["packaging"], # utilities from PyPA to e.g., compare versions deps["pyyaml"], # used for the model cards metadata deps["regex"], # for OpenAI GPT deps["requests"], # for downloading models over HTTPS deps["tokenizers"], deps["typer-slim"], # CLI utilities. In practice, already a dependency of huggingface_hub deps["safetensors"], deps["tqdm"], # progress bars in model download and training scripts ] setup( name="transformers", version="5.0.0.dev0", # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots) author="The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)", author_email="transformers@huggingface.co", description="Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.", long_description=open("README.md", "r", encoding="utf-8").read(), long_description_content_type="text/markdown", keywords="machine-learning nlp python pytorch transformer llm vlm deep-learning inference training model-hub pretrained-models llama gemma qwen", license="Apache 2.0 License", url="https://github.com/huggingface/transformers", package_dir={"": "src"}, packages=find_packages("src"), include_package_data=True, package_data={"": ["**/*.cu", "**/*.cpp", "**/*.cuh", "**/*.h", "**/*.pyx", "py.typed"]}, zip_safe=False, extras_require=extras, entry_points={"console_scripts": ["transformers=transformers.cli.transformers:main"]}, python_requires=">=3.10.0", install_requires=list(install_requires), classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Intended Audience :: Education", "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Topic :: Scientific/Engineering :: Artificial Intelligence", ], cmdclass={"deps_table_update": DepsTableUpdateCommand}, ) extras["tests_torch"] = deps_list() extras["tests_hub"] = deps_list() extras["tests_pipelines_torch"] = deps_list() extras["tests_examples_torch"] = deps_list() extras["tests_custom_tokenizers"] = deps_list() extras["tests_exotic_models"] = deps_list() extras["consistency"] = deps_list()
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/conftest.py
conftest.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import os import sys import warnings from os.path import abspath, dirname, join import _pytest import pytest from transformers.testing_utils import ( HfDoctestModule, HfDocTestParser, is_torch_available, patch_testing_methods_to_collect_info, patch_torch_compile_force_graph, ) from transformers.utils import enable_tf32 NOT_DEVICE_TESTS = { "test_tokenization", "test_tokenization_mistral_common", "test_processing", "test_beam_constraints", "test_configuration_utils", "test_data_collator", "test_trainer_callback", "test_trainer_utils", "test_feature_extraction", "test_image_processing", "test_image_processor", "test_image_transforms", "test_optimization", "test_retrieval", "test_config", "test_from_pretrained_no_checkpoint", "test_keep_in_fp32_modules", "test_gradient_checkpointing_backward_compatibility", "test_gradient_checkpointing_enable_disable", "test_torch_save_load", "test_forward_signature", "test_model_get_set_embeddings", "test_model_main_input_name", "test_correct_missing_keys", "test_can_use_safetensors", "test_load_save_without_tied_weights", "test_tied_weights_keys", "test_model_weights_reload_no_missing_tied_weights", "test_can_load_ignoring_mismatched_shapes", "test_model_is_small", "ModelTest::test_pipeline_", # None of the pipeline tests from PipelineTesterMixin (of which XxxModelTest inherits from) are running on device "ModelTester::test_pipeline_", "/repo_utils/", "/utils/", } # allow having multiple repository checkouts and not needing to remember to rerun # `pip install -e '.[dev]'` when switching between checkouts and running tests. git_repo_path = abspath(join(dirname(__file__), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def pytest_configure(config): config.addinivalue_line("markers", "is_pipeline_test: mark test to run only when pipelines are tested") config.addinivalue_line("markers", "is_staging_test: mark test to run only in the staging environment") config.addinivalue_line("markers", "accelerate_tests: mark test that require accelerate") config.addinivalue_line("markers", "not_device_test: mark the tests always running on cpu") config.addinivalue_line("markers", "torch_compile_test: mark test which tests torch compile functionality") config.addinivalue_line("markers", "torch_export_test: mark test which tests torch export functionality") config.addinivalue_line("markers", "flash_attn_test: mark test which tests flash attention functionality") config.addinivalue_line("markers", "flash_attn_3_test: mark test which tests flash attention 3 functionality") config.addinivalue_line("markers", "training_ci: mark test for training CI validation") os.environ["DISABLE_SAFETENSORS_CONVERSION"] = "true" def pytest_collection_modifyitems(items): for item in items: if any(test_name in item.nodeid for test_name in NOT_DEVICE_TESTS): item.add_marker(pytest.mark.not_device_test) def pytest_addoption(parser): from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(parser) def pytest_terminal_summary(terminalreporter): from transformers.testing_utils import pytest_terminal_summary_main make_reports = terminalreporter.config.getoption("--make-reports") if make_reports: pytest_terminal_summary_main(terminalreporter, id=make_reports) def pytest_sessionfinish(session, exitstatus): # If no tests are collected, pytest exists with code 5, which makes the CI fail. if exitstatus == 5: session.exitstatus = 0 # Doctest custom flag to ignore output. IGNORE_RESULT = doctest.register_optionflag("IGNORE_RESULT") OutputChecker = doctest.OutputChecker class CustomOutputChecker(OutputChecker): def check_output(self, want, got, optionflags): if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self, want, got, optionflags) doctest.OutputChecker = CustomOutputChecker _pytest.doctest.DoctestModule = HfDoctestModule doctest.DocTestParser = HfDocTestParser if is_torch_available(): # The flag below controls whether to allow TF32 on cuDNN. This flag defaults to True. # We set it to `False` for CI. See https://github.com/pytorch/pytorch/issues/157274#issuecomment-3090791615 enable_tf32(False) # patch `torch.compile`: if `TORCH_COMPILE_FORCE_FULLGRAPH=1` (or values considered as true, e.g. yes, y, etc.), # the patched version will always run with `fullgraph=True`. patch_torch_compile_force_graph() if os.environ.get("PATCH_TESTING_METHODS_TO_COLLECT_OUTPUTS", "").lower() in ("yes", "true", "on", "y", "1"): patch_testing_methods_to_collect_info()
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/.github/scripts/assign_reviewers.py
.github/scripts/assign_reviewers.py
# coding=utf-8 # Copyright 2025 the HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import re from collections import Counter from pathlib import Path import github from github import Github def pattern_to_regex(pattern): if pattern.startswith("/"): start_anchor = True pattern = re.escape(pattern[1:]) else: start_anchor = False pattern = re.escape(pattern) # Replace `*` with "any number of non-slash characters" pattern = pattern.replace(r"\*", "[^/]*") if start_anchor: pattern = r"^\/?" + pattern # Allow an optional leading slash after the start of the string return pattern def get_file_owners(file_path, codeowners_lines): # Process lines in reverse (last matching pattern takes precedence) for line in reversed(codeowners_lines): # Skip comments and empty lines, strip inline comments line = line.split('#')[0].strip() if not line: continue # Split into pattern and owners parts = line.split() pattern = parts[0] # Can be empty, e.g. for dummy files with explicitly no owner! owners = [owner.removeprefix("@") for owner in parts[1:]] # Check if file matches pattern file_regex = pattern_to_regex(pattern) if re.search(file_regex, file_path) is not None: return owners # Remember, can still be empty! return [] # Should never happen, but just in case def pr_author_is_in_hf(pr_author, codeowners_lines): # Check if the PR author is in the codeowners file for line in codeowners_lines: line = line.split('#')[0].strip() if not line: continue # Split into pattern and owners parts = line.split() owners = [owner.removeprefix("@") for owner in parts[1:]] if pr_author in owners: return True return False def main(): script_dir = Path(__file__).parent.absolute() with open(script_dir / "codeowners_for_review_action") as f: codeowners_lines = f.readlines() g = Github(os.environ['GITHUB_TOKEN']) repo = g.get_repo("huggingface/transformers") with open(os.environ['GITHUB_EVENT_PATH']) as f: event = json.load(f) # The PR number is available in the event payload pr_number = event['pull_request']['number'] pr = repo.get_pull(pr_number) pr_author = pr.user.login if pr_author_is_in_hf(pr_author, codeowners_lines): print(f"PR author {pr_author} is in codeowners, skipping review request.") return existing_reviews = list(pr.get_reviews()) if existing_reviews: print(f"Already has reviews: {[r.user.login for r in existing_reviews]}") return users_requested, teams_requested = pr.get_review_requests() users_requested = list(users_requested) if users_requested: print(f"Reviewers already requested: {users_requested}") return locs_per_owner = Counter() for file in pr.get_files(): owners = get_file_owners(file.filename, codeowners_lines) for owner in owners: locs_per_owner[owner] += file.changes # Assign the top 2 based on locs changed as reviewers, but skip the owner if present locs_per_owner.pop(pr_author, None) top_owners = locs_per_owner.most_common(2) print("Top owners", top_owners) top_owners = [owner[0] for owner in top_owners] try: pr.create_review_request(top_owners) except github.GithubException as e: print(f"Failed to request review for {top_owners}: {e}") if __name__ == "__main__": main()
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/scripts/stale.py
scripts/stale.py
# Copyright 2021 The HuggingFace Team, the AllenNLP library authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Script to close stale issue. Taken in part from the AllenNLP repository. https://github.com/allenai/allennlp. """ import os from datetime import datetime as dt import github.GithubException from github import Github LABELS_TO_EXEMPT = [ "good first issue", "good second issue", "good difficult issue", "feature request", "new model", "wip", ] def main(): g = Github(os.environ["GITHUB_TOKEN"]) repo = g.get_repo("huggingface/transformers") open_issues = repo.get_issues(state="open") for i, issue in enumerate(open_issues): print(i, issue) comments = sorted(issue.get_comments(), key=lambda i: i.created_at, reverse=True) last_comment = comments[0] if len(comments) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at.replace(tzinfo=None)).days > 7 and (dt.utcnow() - issue.created_at.replace(tzinfo=None)).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") try: issue.edit(state="closed") except github.GithubException as e: print("Couldn't close the issue:", repr(e)) elif ( (dt.utcnow() - issue.updated_at.replace(tzinfo=None)).days > 23 and (dt.utcnow() - issue.created_at.replace(tzinfo=None)).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would add stale comment to {issue.number}") try: issue.create_comment( "This issue has been automatically marked as stale because it has not had " "recent activity. If you think this still needs to be addressed " "please comment on this thread.\n\nPlease note that issues that do not follow the " "[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) " "are likely to be ignored." ) except github.GithubException as e: print("Couldn't create comment:", repr(e)) if __name__ == "__main__": main()
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/scripts/check_tokenizers.py
scripts/check_tokenizers.py
from collections import Counter import datasets import transformers from transformers.convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.utils import logging logging.set_verbosity_info() TOKENIZER_CLASSES = { name: (getattr(transformers, name), getattr(transformers, name + "Fast")) for name in SLOW_TO_FAST_CONVERTERS } dataset = datasets.load_dataset("facebook/xnli", split="test+validation") # no-script total = 0 perfect = 0 imperfect = 0 wrong = 0 def check_diff( spm_diff: list[int], tok_diff: list[int], slow: PreTrainedTokenizerBase, fast: PreTrainedTokenizerBase ) -> bool: if spm_diff == list(reversed(tok_diff)): # AAA -> AA+A vs A+AA case. return True elif len(spm_diff) == len(tok_diff) and fast.decode(spm_diff) == fast.decode(tok_diff): # Second order OK # Barrich -> Barr + ich vs Bar + rich return True spm_reencoded = slow.encode(slow.decode(spm_diff)) tok_reencoded = fast.encode(fast.decode(spm_diff)) if spm_reencoded != spm_diff and spm_reencoded == tok_reencoded: # Type 3 error. # Snehagatha -> # Sne, h, aga, th, a # Sne, ha, gat, ha # Encoding the wrong with sp does not even recover what spm gave us # It fits tokenizer however... return True return False def check_LTR_mark(line: str, idx: int, fast: PreTrainedTokenizerBase) -> bool: enc = fast.encode_plus(line)[0] offsets = enc.offsets curr, prev = offsets[idx], offsets[idx - 1] if curr is not None and line[curr[0] : curr[1]] == "\u200f": return True if prev is not None and line[prev[0] : prev[1]] == "\u200f": return True return False def check_details( line: str, spm_ids: list[int], tok_ids: list[int], slow: PreTrainedTokenizerBase, fast: PreTrainedTokenizerBase ) -> bool: # Encoding can be the same with same result AAA -> A + AA vs AA + A # We can check that we use at least exactly the same number of tokens. for i, (spm_id, tok_id) in enumerate(zip(spm_ids, tok_ids)): if spm_id != tok_id: break first = i for i, (spm_id, tok_id) in enumerate(zip(reversed(spm_ids), reversed(tok_ids))): if spm_id != tok_id: break last = len(spm_ids) - i spm_diff = spm_ids[first:last] tok_diff = tok_ids[first:last] if check_diff(spm_diff, tok_diff, slow, fast): return True if check_LTR_mark(line, first, fast): return True if last - first > 5: # We might have twice a single problem, attempt to subdivide the disjointed tokens into smaller problems spms = Counter(spm_ids[first:last]) toks = Counter(tok_ids[first:last]) removable_tokens = {spm_ for (spm_, si) in spms.items() if toks.get(spm_, 0) == si} min_width = 3 for i in range(last - first - min_width): if all(spm_ids[first + i + j] in removable_tokens for j in range(min_width)): possible_matches = [ k for k in range(last - first - min_width) if tok_ids[first + k : first + k + min_width] == spm_ids[first + i : first + i + min_width] ] for j in possible_matches: if check_diff( spm_ids[first : first + i], tok_ids[first : first + j], slow, fast ) and check_details( line, spm_ids[first + i : last], tok_ids[first + j : last], slow, fast, ): return True print(f"Spm: {[fast.decode([spm_ids[i]]) for i in range(first, last)]}") try: print(f"Tok: {[fast.decode([tok_ids[i]]) for i in range(first, last)]}") except Exception: pass fast.decode(spm_ids[:first]) fast.decode(spm_ids[last:]) wrong = fast.decode(spm_ids[first:last]) print() print(wrong) return False def test_string(slow: PreTrainedTokenizerBase, fast: PreTrainedTokenizerBase, text: str) -> None: global perfect global imperfect global wrong global total slow_ids = slow.encode(text) fast_ids = fast.encode(text) skip_assert = False total += 1 if slow_ids != fast_ids: if check_details(text, slow_ids, fast_ids, slow, fast): skip_assert = True imperfect += 1 else: wrong += 1 else: perfect += 1 if total % 10000 == 0: print(f"({perfect} / {imperfect} / {wrong} ----- {perfect + imperfect + wrong})") if skip_assert: return assert slow_ids == fast_ids, ( f"line {text} : \n\n{slow_ids}\n{fast_ids}\n\n{slow.tokenize(text)}\n{fast.tokenize(text)}" ) def test_tokenizer(slow: PreTrainedTokenizerBase, fast: PreTrainedTokenizerBase) -> None: global batch_total for i in range(len(dataset)): # premise, all languages for text in dataset[i]["premise"].values(): test_string(slow, fast, text) # hypothesis, all languages for text in dataset[i]["hypothesis"]["translation"]: test_string(slow, fast, text) if __name__ == "__main__": for name, (slow_class, fast_class) in TOKENIZER_CLASSES.items(): checkpoint_names = list(slow_class.max_model_input_sizes.keys()) for checkpoint in checkpoint_names: imperfect = 0 perfect = 0 wrong = 0 total = 0 print(f"========================== Checking {name}: {checkpoint} ==========================") slow = slow_class.from_pretrained(checkpoint, force_download=True) fast = fast_class.from_pretrained(checkpoint, force_download=True) test_tokenizer(slow, fast) print(f"Accuracy {perfect * 100 / total:.2f}")
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/scripts/distributed/torch-distributed-gpu-test.py
scripts/distributed/torch-distributed-gpu-test.py
#!/usr/bin/env python # # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def printflock(*msgs): """solves multi-process interleaved print problem""" with open(__file__, "r") as fh: fcntl.flock(fh, fcntl.LOCK_EX) try: print(*msgs) finally: fcntl.flock(fh, fcntl.LOCK_UN) local_rank = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(local_rank) device = torch.device("cuda", local_rank) hostname = socket.gethostname() gpu = f"[{hostname}-{local_rank}]" try: # test distributed dist.init_process_group("nccl") dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank rank = dist.get_rank() world_size = dist.get_world_size() printflock(f"{gpu} is OK (global rank: {rank}/{world_size})") dist.barrier() if rank == 0: printflock(f"pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}") except Exception: printflock(f"{gpu} is broken") raise
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/benchmark/benchmarks_entrypoint.py
benchmark/benchmarks_entrypoint.py
# Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import importlib.util import json import logging import os import sys import uuid from datetime import datetime import pandas as pd try: from psycopg2.extensions import register_adapter from psycopg2.extras import Json register_adapter(dict, Json) PSYCOPG2_AVAILABLE = True except ImportError: PSYCOPG2_AVAILABLE = False class ImportModuleException(Exception): pass class MetricsRecorder: def __init__( self, connection, logger: logging.Logger, repository: str, branch: str, commit_id: str, commit_msg: str, collect_csv_data: bool = True, ): self.conn = connection self.use_database = connection is not None if self.use_database: self.conn.autocommit = True self.logger = logger self.repository = repository self.branch = branch self.commit_id = commit_id self.commit_msg = commit_msg self.collect_csv_data = collect_csv_data # For CSV export - store all data in pandas DataFrames (only if CSV collection is enabled) if self.collect_csv_data: # Initialize empty DataFrames with proper schemas self.benchmarks_df = pd.DataFrame( columns=[ "benchmark_id", "repository", "branch", "commit_id", "commit_message", "metadata", "created_at", ] ) self.device_measurements_df = pd.DataFrame( columns=["benchmark_id", "cpu_util", "mem_megabytes", "gpu_util", "gpu_mem_megabytes", "time"] ) self.model_measurements_df = pd.DataFrame( columns=[ "benchmark_id", "time", "model_load_time", "first_eager_forward_pass_time_secs", "second_eager_forward_pass_time_secs", "first_eager_generate_time_secs", "second_eager_generate_time_secs", "time_to_first_token_secs", "time_to_second_token_secs", "time_to_third_token_secs", "time_to_next_token_mean_secs", "first_compile_generate_time_secs", "second_compile_generate_time_secs", "third_compile_generate_time_secs", "fourth_compile_generate_time_secs", ] ) else: self.benchmarks_df = None self.device_measurements_df = None self.model_measurements_df = None def initialise_benchmark(self, metadata: dict[str, str]) -> str: """ Creates a new benchmark, returns the benchmark id (UUID) """ # Generate a unique UUID for this benchmark benchmark_id = str(uuid.uuid4()) if self.use_database: with self.conn.cursor() as cur: cur.execute( "INSERT INTO benchmarks (benchmark_id, repository, branch, commit_id, commit_message, metadata) VALUES (%s, %s, %s, %s, %s, %s)", (benchmark_id, self.repository, self.branch, self.commit_id, self.commit_msg, metadata), ) self.logger.debug(f"initialised benchmark #{benchmark_id}") # Store benchmark data for CSV export (if enabled) if self.collect_csv_data: # Add row to pandas DataFrame new_row = pd.DataFrame( [ { "benchmark_id": benchmark_id, "repository": self.repository, "branch": self.branch, "commit_id": self.commit_id, "commit_message": self.commit_msg, "metadata": json.dumps(metadata), "created_at": datetime.utcnow().isoformat(), } ] ) self.benchmarks_df = pd.concat([self.benchmarks_df, new_row], ignore_index=True) mode_info = [] if self.use_database: mode_info.append("database") if self.collect_csv_data: mode_info.append("CSV") mode_str = " + ".join(mode_info) if mode_info else "no storage" self.logger.debug(f"initialised benchmark #{benchmark_id} ({mode_str} mode)") return benchmark_id def collect_device_measurements(self, benchmark_id: str, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes): """ Collect device metrics, such as CPU & GPU usage. These are "static", as in you cannot pass arbitrary arguments to the function. """ # Store device measurements for CSV export (if enabled) if self.collect_csv_data: # Add row to pandas DataFrame new_row = pd.DataFrame( [ { "benchmark_id": benchmark_id, "cpu_util": cpu_util, "mem_megabytes": mem_megabytes, "gpu_util": gpu_util, "gpu_mem_megabytes": gpu_mem_megabytes, "time": datetime.utcnow().isoformat(), } ] ) self.device_measurements_df = pd.concat([self.device_measurements_df, new_row], ignore_index=True) # Store in database if available if self.use_database: with self.conn.cursor() as cur: cur.execute( "INSERT INTO device_measurements (benchmark_id, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes) VALUES (%s, %s, %s, %s, %s)", (benchmark_id, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes), ) self.logger.debug( f"collected device measurements for benchmark #{benchmark_id} [CPU util: {cpu_util}, mem MBs: {mem_megabytes}, GPU util: {gpu_util}, GPU mem MBs: {gpu_mem_megabytes}]" ) def collect_model_measurements(self, benchmark_id: str, measurements: dict[str, float]): # Store model measurements for CSV export (if enabled) if self.collect_csv_data: # Add row to pandas DataFrame with flattened measurements row_data = {"benchmark_id": benchmark_id, "time": datetime.utcnow().isoformat()} # Flatten the measurements dict into the row row_data.update(measurements) new_row = pd.DataFrame([row_data]) self.model_measurements_df = pd.concat([self.model_measurements_df, new_row], ignore_index=True) # Store in database if available if self.use_database: with self.conn.cursor() as cur: cur.execute( """ INSERT INTO model_measurements ( benchmark_id, measurements ) VALUES (%s, %s) """, ( benchmark_id, measurements, ), ) self.logger.debug(f"collected model measurements for benchmark #{benchmark_id}: {measurements}") def export_to_csv(self, output_dir: str = "benchmark_results"): """ Export all collected data to CSV files using pandas DataFrames """ if not self.collect_csv_data: self.logger.warning("CSV data collection is disabled - no CSV files will be generated") return if not os.path.exists(output_dir): os.makedirs(output_dir) self.logger.info(f"Created output directory: {output_dir}") timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") files_created = [] # Export using pandas DataFrames self._export_pandas_data(output_dir, timestamp, files_created) self.logger.info(f"CSV export complete! Created {len(files_created)} files in {output_dir}") def _export_pandas_data(self, output_dir: str, timestamp: str, files_created: list): """ Export CSV files using pandas DataFrames """ # Export benchmarks benchmarks_file = os.path.join(output_dir, f"benchmarks_{timestamp}.csv") self.benchmarks_df.to_csv(benchmarks_file, index=False) files_created.append(benchmarks_file) self.logger.info(f"Exported {len(self.benchmarks_df)} benchmark records to {benchmarks_file}") # Export device measurements device_file = os.path.join(output_dir, f"device_measurements_{timestamp}.csv") self.device_measurements_df.to_csv(device_file, index=False) files_created.append(device_file) self.logger.info(f"Exported {len(self.device_measurements_df)} device measurement records to {device_file}") # Export model measurements (already flattened) model_file = os.path.join(output_dir, f"model_measurements_{timestamp}.csv") self.model_measurements_df.to_csv(model_file, index=False) files_created.append(model_file) self.logger.info(f"Exported {len(self.model_measurements_df)} model measurement records to {model_file}") # Create comprehensive summary using pandas operations summary_file = os.path.join(output_dir, f"benchmark_summary_{timestamp}.csv") self._create_summary(summary_file) files_created.append(summary_file) def _create_summary(self, summary_file: str): """ Create a comprehensive summary CSV using pandas operations """ if len(self.benchmarks_df) == 0: # Create empty summary file summary_df = pd.DataFrame() summary_df.to_csv(summary_file, index=False) self.logger.info(f"Created empty benchmark summary at {summary_file}") return # Start with benchmarks as the base summary_df = self.benchmarks_df.copy() # Add model measurements (join on benchmark_id) if len(self.model_measurements_df) > 0: # Drop 'time' column from model measurements to avoid conflicts model_df = self.model_measurements_df.drop(columns=["time"], errors="ignore") summary_df = summary_df.merge(model_df, on="benchmark_id", how="left") # Calculate device measurement aggregates using pandas groupby if len(self.device_measurements_df) > 0: device_agg = ( self.device_measurements_df.groupby("benchmark_id") .agg( { "cpu_util": ["mean", "max", "std", "count"], "mem_megabytes": ["mean", "max", "std"], "gpu_util": ["mean", "max", "std"], "gpu_mem_megabytes": ["mean", "max", "std"], } ) .round(3) ) # Flatten column names device_agg.columns = [f"{col[0]}_{col[1]}" for col in device_agg.columns] device_agg = device_agg.reset_index() # Rename count column to be more descriptive if "cpu_util_count" in device_agg.columns: device_agg = device_agg.rename(columns={"cpu_util_count": "device_measurement_count"}) # Merge with summary summary_df = summary_df.merge(device_agg, on="benchmark_id", how="left") # Export the comprehensive summary summary_df.to_csv(summary_file, index=False) self.logger.info(f"Created comprehensive benchmark summary with {len(summary_df)} records at {summary_file}") def close(self): if self.use_database and self.conn: self.conn.close() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.INFO) formatter = logging.Formatter("[%(levelname)s - %(asctime)s] %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) def parse_arguments() -> tuple[str, str, str, str, bool, str]: """ Parse command line arguments for the benchmarking CLI. """ parser = argparse.ArgumentParser(description="CLI for benchmarking the huggingface/transformers.") parser.add_argument( "repository", type=str, help="The repository name on which the benchmarking is performed.", ) parser.add_argument( "branch", type=str, help="The branch name on which the benchmarking is performed.", ) parser.add_argument( "commit_id", type=str, help="The commit hash on which the benchmarking is performed.", ) parser.add_argument( "commit_msg", type=str, help="The commit message associated with the commit, truncated to 70 characters.", ) parser.add_argument("--csv", action="store_true", default=False, help="Enable CSV output files generation.") parser.add_argument( "--csv-output-dir", type=str, default="benchmark_results", help="Directory for CSV output files (default: benchmark_results).", ) args = parser.parse_args() # CSV is disabled by default, only enabled when --csv is used generate_csv = args.csv return args.repository, args.branch, args.commit_id, args.commit_msg, generate_csv, args.csv_output_dir def import_from_path(module_name, file_path): try: spec = importlib.util.spec_from_file_location(module_name, file_path) module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module spec.loader.exec_module(module) return module except Exception as e: raise ImportModuleException(f"failed to load python module: {e}") def create_database_connection(): """ Try to create a database connection. Returns None if connection fails. """ if not PSYCOPG2_AVAILABLE: logger.warning("psycopg2 not available - running in CSV-only mode") return None try: import psycopg2 conn = psycopg2.connect("dbname=metrics") logger.info("Successfully connected to database") return conn except Exception as e: logger.warning(f"Failed to connect to database: {e}. Running in CSV-only mode") return None def create_global_metrics_recorder( repository: str, branch: str, commit_id: str, commit_msg: str, generate_csv: bool = False ) -> MetricsRecorder: """ Create a global metrics recorder that will be used across all benchmarks. """ connection = create_database_connection() recorder = MetricsRecorder(connection, logger, repository, branch, commit_id, commit_msg, generate_csv) # Log the storage mode storage_modes = [] if connection is not None: storage_modes.append("database") if generate_csv: storage_modes.append("CSV") if not storage_modes: logger.warning("Running benchmarks with NO data storage (no database connection, CSV disabled)") logger.warning("Use --csv flag to enable CSV output when database is unavailable") else: logger.info(f"Running benchmarks with: {' + '.join(storage_modes)} storage") return recorder if __name__ == "__main__": benchmarks_folder_path = os.path.dirname(os.path.realpath(__file__)) benches_folder_path = os.path.join(benchmarks_folder_path, "benches") repository, branch, commit_id, commit_msg, generate_csv, csv_output_dir = parse_arguments() # Create a global metrics recorder global_metrics_recorder = create_global_metrics_recorder(repository, branch, commit_id, commit_msg, generate_csv) successful_benchmarks = 0 failed_benchmarks = 0 # Automatically discover all benchmark modules in benches/ folder benchmark_modules = [] if os.path.exists(benches_folder_path): logger.debug(f"Scanning for benchmarks in: {benches_folder_path}") for entry in os.scandir(benches_folder_path): if not entry.name.endswith(".py"): continue if entry.name.startswith("__"): # Skip __init__.py, __pycache__, etc. continue # Check if the file has a run_benchmark function try: logger.debug(f"checking if benches/{entry.name} has run_benchmark function") module = import_from_path(entry.name.split(".")[0], entry.path) if hasattr(module, "run_benchmark"): benchmark_modules.append(entry.name) logger.debug(f"discovered benchmark: {entry.name}") else: logger.debug(f"skipping {entry.name} - no run_benchmark function found") except Exception as e: logger.debug(f"failed to check benches/{entry.name}: {e}") else: logger.warning(f"Benches directory not found: {benches_folder_path}") if benchmark_modules: logger.info(f"Discovered {len(benchmark_modules)} benchmark(s): {benchmark_modules}") else: logger.warning("No benchmark modules found in benches/ directory") for module_name in benchmark_modules: module_path = os.path.join(benches_folder_path, module_name) try: logger.debug(f"loading: {module_name}") module = import_from_path(module_name.split(".")[0], module_path) logger.info(f"running benchmarks in: {module_name}") # Check if the module has an updated run_benchmark function that accepts metrics_recorder try: # Try the new signature first module.run_benchmark(logger, repository, branch, commit_id, commit_msg, global_metrics_recorder) except TypeError: # Fall back to the old signature for backward compatibility logger.warning( f"Module {module_name} using old run_benchmark signature - database connection will be created per module" ) module.run_benchmark(logger, repository, branch, commit_id, commit_msg) successful_benchmarks += 1 except ImportModuleException as e: logger.error(e) failed_benchmarks += 1 except Exception as e: logger.error(f"error running benchmarks for {module_name}: {e}") failed_benchmarks += 1 # Export CSV results at the end (if enabled) try: if generate_csv: global_metrics_recorder.export_to_csv(csv_output_dir) logger.info(f"CSV reports have been generated and saved to the {csv_output_dir} directory") else: logger.info("CSV generation disabled - no CSV files created (use --csv to enable)") logger.info(f"Benchmark run completed. Successful: {successful_benchmarks}, Failed: {failed_benchmarks}") except Exception as e: logger.error(f"Failed to export CSV results: {e}") finally: global_metrics_recorder.close()
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/benchmark/benchmark.py
benchmark/benchmark.py
# Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Run benchmark using the `optimum-benchmark` library with some customization in `transformers`. Assume we are under `transformers` root directory: (make sure the commits are valid commits) ```bash python benchmark/benchmark.py --config-dir benchmark/config --config-name generation --commit=9b9c7f03da625b13643e99205c691fe046461724 --metrics=decode.latency.mean,per_token.latency.mean,per_token.throughput.value backend.model=google/gemma-2b benchmark.input_shapes.sequence_length=5,7 benchmark.input_shapes.batch_size=1,2 --multirun ``` """ import argparse import glob import json import os.path import re import tempfile from contextlib import contextmanager from pathlib import Path from git import Repo from huggingface_hub import HfApi from optimum_benchmark import Benchmark from optimum_benchmark_wrapper import main PATH_TO_REPO = Path(__file__).parent.parent.resolve() @contextmanager def checkout_commit(repo: Repo, commit_id: str): """ Context manager that checks out a given commit when entered, but gets back to the reference it was at on exit. Args: repo (`git.Repo`): A git repository (for instance the Transformers repo). commit_id (`str`): The commit reference to checkout inside the context manager. """ current_head = repo.head.commit if repo.head.is_detached else repo.head.ref try: repo.git.checkout(commit_id) yield finally: repo.git.checkout(current_head) def summarize(run_dir, metrics, expand_metrics=False): """Produce a summary for each optimum-benchmark launched job's output directory found in `run_dir`. Each summary's format is as follows (for `expand_metrics=False`): ``` { "model": "google/gemma-2b", "commit": "3cd6ed22e4d49219f300f5055e71e3929aba20d7", "config": "benchmark.input_shapes.batch_size=1,benchmark.input_shapes.sequence_length=5", "metrics": { "decode.latency.mean": 1.624666809082031, "per_token.latency.mean": 0.012843788806628804, "per_token.throughput.value": 77.85864553330948 } } ``` """ reports = glob.glob(os.path.join(run_dir, "**/benchmark_report.json"), recursive=True) report_dirs = [str(Path(report).parent) for report in reports] summaries = [] for report_dir in report_dirs: commit = re.search(r"/commit=([^/]+)", report_dir).groups()[0] if not os.path.isfile(os.path.join(report_dir, "benchmark.json")): continue benchmark = Benchmark.from_json(os.path.join(report_dir, "benchmark.json")) report = benchmark.report model = benchmark.config.backend["model"] # This looks like `benchmark.input_shapes.batch_size=1,benchmark.input_shapes.sequence_length=5`. # (we rely on the usage of hydra's `${hydra.job.override_dirname}`.) benchmark_name = re.sub(f"backend.model={model},*", "", report_dir) benchmark_name = str(Path(benchmark_name).parts[-1]) if benchmark_name.startswith("commit="): benchmark_name = benchmark.config.name metrics_values = {} # post-processing of report: show a few selected/important metric for metric in metrics: keys = metric.split(".") value = report.to_dict() current = metrics_values for key in keys: # Avoid KeyError when a user's specified metric has typo. # TODO: Give warnings. if key not in value: continue value = value[key] if expand_metrics: if isinstance(value, dict): if key not in current: current[key] = {} current = current[key] else: current[key] = value if not expand_metrics: metrics_values[metric] = value # show some config information print(f"model: {model}") print(f"commit: {commit}") print(f"config: {benchmark_name}") if len(metrics_values) > 0: print("metrics:") if expand_metrics: print(metrics_values) else: for metric, value in metrics_values.items(): print(f" - {metric}: {value}") print("-" * 80) summary = { "model": model, "commit": commit, "config": benchmark_name, "metrics": metrics_values, } summaries.append(summary) with open(os.path.join(report_dir, "summary.json"), "w") as fp: json.dump(summary, fp, indent=4) return summaries def combine_summaries(summaries): """Combine a list of summary obtained from the function `summarize`. The combined summary's format is as follows: ``` "google/gemma-2b": { "benchmark.input_shapes.batch_size=1,benchmark.input_shapes.sequence_length=5": { "3cd6ed22e4d49219f300f5055e71e3929aba20d7": { "metrics": {"decode.latency.mean": 1.624666809082031} }, "c97ee28b117c0abe8e08891f402065e4df6d72aa": { "metrics": {"decode.latency.mean": 1.6278163452148438} } }, "benchmark.input_shapes.batch_size=2,benchmark.input_shapes.sequence_length=5": { "3cd6ed22e4d49219f300f5055e71e3929aba20d7": { "metrics": {"decode.latency.mean": 1.6947791748046876} }, "c97ee28b117c0abe8e08891f402065e4df6d72aa": { "metrics": { "decode.latency.mean": 1.6980519409179688} } } } ``` """ combined = {} for summary in summaries: model = summary["model"] config = summary["config"] commit = summary["commit"] if model not in combined: combined[model] = {} if config not in combined[model]: combined[model][config] = {} if commit not in combined[model][config]: combined[model][config][commit] = {"metrics": summary["metrics"]} with open(os.path.join(exp_run_dir, "summary.json"), "w") as fp: json.dump(combined, fp, indent=4) print(json.dumps(combined, indent=4)) return combined if __name__ == "__main__": def list_str(values): return values.split(",") parser = argparse.ArgumentParser() parser.add_argument("--config-dir", type=str, required=True, help="The path to the config directory.") parser.add_argument("--config-name", type=str, required=True, help="The config name.") # arguments specific to this wrapper for our own customization parser.add_argument("--ensure_empty", type=bool, default=True, help="If to create a temporary directory.") parser.add_argument( "--commit", type=list_str, default="", help="Comma-separated list of branch names and/or commit sha values on which the benchmark will run. If `diff` is specified, it will run on both the current head and the `main` branch.", ) parser.add_argument("--metrics", type=str, help="The metrics to be included in the summary.") parser.add_argument("--repo_id", type=str, default=None, help="The repository to which the file will be uploaded.") parser.add_argument("--path_in_repo", type=str, default=None, help="Relative filepath in the repo.") parser.add_argument("--token", type=str, default=None, help="A valid user access token (string).") args, optimum_benchmark_args = parser.parse_known_args() repo = Repo(PATH_TO_REPO) metrics = [ "prefill.latency.mean", "prefill.throughput.value", "decode.latency.mean", "decode.throughput.value", "per_token.latency.mean", "per_token.throughput.value", ] if args.metrics is not None: metrics = args.metrics.split(",") # Get `backend.model` in a hacky way: We want to control the experiment flow manually. models = [""] for idx, arg in enumerate(optimum_benchmark_args): if arg.startswith("backend.model="): models = arg[len("backend.model=") :] models = models.split(",") break optimum_benchmark_args = [arg for arg in optimum_benchmark_args if not arg.startswith("backend.model=")] # Get the commit(s) current_head = str(repo.head.commit) if repo.head.is_detached else str(repo.head.ref) commits = [x for x in args.commit if x != ""] if len(commits) == 0: commits = [current_head] elif len(commits) == 1 and commits[0] == "diff": # compare to `main` commits = ["main", current_head] # Get the specified run directory run_dir_arg_idx, run_dir = -1, None sweep_dir_arg_idx, sweep_dir = -1, None for idx, arg in enumerate(optimum_benchmark_args): if arg.startswith("hydra.run.dir="): run_dir = arg[len("hydra.run.dir=") :] run_dir_arg_idx = idx elif arg.startswith("hydra.sweep.dir="): sweep_dir = arg[len("hydra.sweep.dir=") :] sweep_dir_arg_idx = idx exp_run_dir, arg_dix, arg_name = ( (sweep_dir, sweep_dir_arg_idx, "hydra.sweep.dir") if "--multirun" in optimum_benchmark_args else (run_dir, run_dir_arg_idx, "hydra.run.dir") ) # TODO: not hardcoded if exp_run_dir is None and args.ensure_empty: exp_run_dir = "_benchmark" if args.ensure_empty: os.makedirs(exp_run_dir, exist_ok=True) exp_run_dir = tempfile.mkdtemp(dir=exp_run_dir) run_summaries = [] for commit in commits: with checkout_commit(repo, commit): commit = str(repo.head.commit) commit_run_dir = exp_run_dir if exp_run_dir is not None: commit_run_dir = os.path.join(exp_run_dir, rf"commit\={commit}") print(f"Run benchmark on commit: {commit}") for model in models: model_arg = [f"backend.model={model}"] if model != "" else [] dir_args = [] if commit_run_dir is not None: if arg_dix > -1: optimum_benchmark_args[arg_dix] = f"{arg_name}={commit_run_dir}" else: dir_args = [ f"hydra.sweep.dir={commit_run_dir}", f"hydra.run.dir={commit_run_dir}/" + "${hydra.job.override_dirname}", ] main(args.config_dir, args.config_name, model_arg + dir_args + optimum_benchmark_args) if commit_run_dir is not None: # Need to remove the `\` character summaries = summarize(commit_run_dir.replace("\\", ""), metrics) run_summaries.extend(summaries) # aggregate the information across the commits if exp_run_dir is not None: with open(os.path.join(exp_run_dir, "summaries.json"), "w") as fp: json.dump(run_summaries, fp, indent=4) combined_summary = combine_summaries(run_summaries) if args.repo_id is not None and args.path_in_repo is not None: # Upload to Hub api = HfApi() api.upload_folder( folder_path=exp_run_dir, path_in_repo=args.path_in_repo, repo_id=args.repo_id, repo_type="dataset", token=args.token, )
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/benchmark/__init__.py
benchmark/__init__.py
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/benchmark/optimum_benchmark_wrapper.py
benchmark/optimum_benchmark_wrapper.py
import argparse import subprocess def main(config_dir, config_name, args): subprocess.run( ["optimum-benchmark", "--config-dir", f"{config_dir}", "--config-name", f"{config_name}"] + ["hydra/job_logging=disabled", "hydra/hydra_logging=disabled"] + args ) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--config-dir", type=str, required=True, help="The path to the config directory.") parser.add_argument("--config-name", type=str, required=True, help="The config name.") args, unknown = parser.parse_known_args() main(args.config_dir, args.config_name, unknown)
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/benchmark/benches/llama.py
benchmark/benches/llama.py
# Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys from logging import Logger from threading import Event, Thread from time import perf_counter, sleep # Add the parent directory to Python path to import benchmarks_entrypoint sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import gpustat import psutil import psycopg2 from benchmarks_entrypoint import MetricsRecorder # Optional heavy ML dependencies - only required when actually running the benchmark try: import torch from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, StaticCache TRANSFORMERS_AVAILABLE = True except ImportError: TRANSFORMERS_AVAILABLE = False torch = None AutoModelForCausalLM = None AutoTokenizer = None GenerationConfig = None StaticCache = None os.environ["HF_XET_HIGH_PERFORMANCE"] = "1" os.environ["TOKENIZERS_PARALLELISM"] = "1" # Only set torch precision if torch is available if TRANSFORMERS_AVAILABLE: torch.set_float32_matmul_precision("high") def collect_metrics(benchmark_id, continue_metric_collection, metrics_recorder): p = psutil.Process(os.getpid()) while not continue_metric_collection.is_set(): with p.oneshot(): cpu_util = p.cpu_percent() mem_megabytes = p.memory_info().rss / (1024 * 1024) gpu_stats = gpustat.GPUStatCollection.new_query() gpu_util = gpu_stats[0]["utilization.gpu"] gpu_mem_megabytes = gpu_stats[0]["memory.used"] metrics_recorder.collect_device_measurements( benchmark_id, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes ) sleep(0.01) def run_benchmark( logger: Logger, repository: str, branch: str, commit_id: str, commit_msg: str, metrics_recorder=None, num_tokens_to_generate=100, ): # Check if required ML dependencies are available if not TRANSFORMERS_AVAILABLE: logger.error("Transformers and torch are required to run the LLaMA benchmark. Please install them with:") logger.error("pip install torch transformers") logger.error("Skipping LLaMA benchmark due to missing dependencies.") return continue_metric_collection = Event() metrics_thread = None model_id = "meta-llama/Llama-2-7b-hf" # If no metrics_recorder is provided, create one for backward compatibility if metrics_recorder is None: try: metrics_recorder = MetricsRecorder( psycopg2.connect("dbname=metrics"), logger, repository, branch, commit_id, commit_msg, True ) should_close_recorder = True except Exception as e: logger.error(f"Failed to create metrics recorder: {e}") return else: should_close_recorder = False try: gpu_stats = gpustat.GPUStatCollection.new_query() gpu_name = gpu_stats[0]["name"] benchmark_id = metrics_recorder.initialise_benchmark({"gpu_name": gpu_name, "model_id": model_id}) logger.info(f"running benchmark #{benchmark_id} on {gpu_name} for {model_id}") metrics_thread = Thread( target=collect_metrics, args=[benchmark_id, continue_metric_collection, metrics_recorder], ) metrics_thread.start() logger.info("started background thread to fetch device metrics") os.environ["TOKENIZERS_PARALLELISM"] = "false" # silence warnings when compiling device = "cuda" logger.info("downloading weights") # This is to avoid counting download in model load time measurement model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.float16) gen_config = GenerationConfig(do_sample=False, top_p=1, temperature=1) logger.info("loading model") start = perf_counter() model = AutoModelForCausalLM.from_pretrained( model_id, dtype=torch.float16, generation_config=gen_config ).eval() model.to(device) torch.cuda.synchronize() end = perf_counter() model_load_time = end - start logger.info(f"loaded model in: {model_load_time}s") tokenizer = AutoTokenizer.from_pretrained(model_id) prompt = "Why dogs are so cute?" inputs = tokenizer(prompt, return_tensors="pt").to(device) # Specify the max length (including both the prompt and the response) # When calling `generate` with `cache_implementation="static" later, this is also used to create a `StaticCache` object # with sequence length = `max_length`. The longer the more you will re-use it seq_length = inputs["input_ids"].shape[1] model.generation_config.max_length = seq_length + num_tokens_to_generate batch_size = inputs["input_ids"].shape[0] # Copied from the gpt-fast repo def multinomial_sample_one_no_sync(probs_sort): # Does multinomial sampling without a cuda synchronization q = torch.empty_like(probs_sort).exponential_(1) return torch.argmax(probs_sort / q, dim=-1, keepdim=True).to(dtype=torch.int) def logits_to_probs(logits, temperature: float = 1.0, top_k: int | None = None): logits = logits / max(temperature, 1e-5) if top_k is not None: v, _ = torch.topk(logits, min(top_k, logits.size(-1))) pivot = v.select(-1, -1).unsqueeze(-1) logits = torch.where(logits < pivot, -float("Inf"), logits) probs = torch.nn.functional.softmax(logits, dim=-1) return probs def sample(logits, temperature: float = 1.0, top_k: int | None = None): probs = logits_to_probs(logits[0, -1], temperature, top_k) idx_next = multinomial_sample_one_no_sync(probs) return idx_next, probs # First eager forward pass logger.info("running first eager forward pass") start = perf_counter() _ = model(**inputs) torch.cuda.synchronize() end = perf_counter() first_eager_fwd_pass_time = end - start logger.info(f"completed first eager forward pass in: {first_eager_fwd_pass_time}s") # Second eager forward pass (should be faster) logger.info("running second eager forward pass") start = perf_counter() _ = model(**inputs) torch.cuda.synchronize() end = perf_counter() second_eager_fwd_pass_time = end - start logger.info(f"completed second eager forward pass in: {second_eager_fwd_pass_time}s") # First eager generation logger.info("running first eager generation") start = perf_counter() output = model.generate(**inputs) torch.cuda.synchronize() end = perf_counter() first_eager_generate_time = end - start logger.info(f"completed first eager generation in: {first_eager_generate_time}s") logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") # Second eager generation (should be faster) logger.info("running second eager generation") start = perf_counter() output = model.generate(**inputs) torch.cuda.synchronize() end = perf_counter() second_eager_generate_time = end - start logger.info(f"completed second eager generation in: {second_eager_generate_time}s") logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") logger.info("running generation timing loop") input_pos = torch.arange(0, seq_length, device=device) inputs = inputs["input_ids"] start = perf_counter() with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH): logits = model(inputs, position_ids=input_pos).logits next_token, probs = sample(logits, temperature=0.6, top_k=5) torch.cuda.synchronize() end = perf_counter() time_to_first_token = end - start input_pos = torch.tensor([seq_length], device=device, dtype=torch.int) next_token = next_token.clone() start = perf_counter() with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH): logits = model(next_token, position_ids=input_pos).logits next_token, probs = sample(logits, temperature=0.6, top_k=5) torch.cuda.synchronize() end = perf_counter() time_to_second_token = end - start input_pos = torch.tensor([seq_length + 1], device=device, dtype=torch.int) next_token = next_token.clone() start = perf_counter() with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH): logits = model(next_token, position_ids=input_pos).logits next_token, probs = sample(logits, temperature=0.6, top_k=5) torch.cuda.synchronize() end = perf_counter() time_to_third_token = end - start logger.info("running longer generation timing loop") total_time = 0 for i in range(20): input_pos = torch.tensor([seq_length + 2 + i], device=device, dtype=torch.int) next_token = next_token.clone() start = perf_counter() with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH): logits = model(next_token, position_ids=input_pos).logits next_token, probs = sample(logits, temperature=0.6, top_k=5) torch.cuda.synchronize() end = perf_counter() total_time += end - start mean_time_to_next_token = total_time / 20 logger.info("running compilation benchmarks") # Now compile the model model = torch.compile(model, mode="max-autotune", fullgraph=True) # StaticCache for generation with torch.device(device): model.setup_caches(max_batch_size=batch_size, max_seq_len=seq_length + num_tokens_to_generate) input_pos = torch.arange(0, seq_length, device=device) inputs = tokenizer(prompt, return_tensors="pt").to(device)["input_ids"] logger.info("compiling model") model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.float16, generation_config=gen_config) model.to(device) model = torch.compile(model, mode="max-autotune", fullgraph=True) past_key_values = StaticCache( model.config, max_batch_size=batch_size, device=device, dtype=torch.float16, max_cache_len=seq_length + 128, ) # 1st call start = perf_counter() output = model.generate(**inputs, past_key_values=past_key_values) end = perf_counter() first_compile_generate_time = end - start logger.info(f"completed first compile generation in: {first_compile_generate_time}s") logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") past_key_values = StaticCache( model.config, max_batch_size=batch_size, device=device, dtype=torch.float16, max_cache_len=seq_length + 128, ) # 2nd call start = perf_counter() output = model.generate(**inputs, past_key_values=past_key_values) end = perf_counter() second_compile_generate_time = end - start logger.info(f"completed second compile generation in: {second_compile_generate_time}s") logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") past_key_values = StaticCache( model.config, max_batch_size=batch_size, device=device, dtype=torch.float16, max_cache_len=seq_length + 128, ) # 3rd call start = perf_counter() output = model.generate(**inputs, past_key_values=past_key_values) end = perf_counter() third_compile_generate_time = end - start logger.info(f"completed third compile generation in: {third_compile_generate_time}s") logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") past_key_values = StaticCache( model.config, max_batch_size=batch_size, device=device, dtype=torch.float16, max_cache_len=seq_length + 128, ) # 4th call start = perf_counter() output = model.generate(**inputs, past_key_values=past_key_values) end = perf_counter() fourth_compile_generate_time = end - start logger.info(f"completed fourth compile generation in: {fourth_compile_generate_time}s") logger.info(f"generated: {tokenizer.batch_decode(output.cpu().tolist())}") metrics_recorder.collect_model_measurements( benchmark_id, { "model_load_time": model_load_time, "first_eager_forward_pass_time_secs": first_eager_fwd_pass_time, "second_eager_forward_pass_time_secs": second_eager_fwd_pass_time, "first_eager_generate_time_secs": first_eager_generate_time, "second_eager_generate_time_secs": second_eager_generate_time, "time_to_first_token_secs": time_to_first_token, "time_to_second_token_secs": time_to_second_token, "time_to_third_token_secs": time_to_third_token, "time_to_next_token_mean_secs": mean_time_to_next_token, "first_compile_generate_time_secs": first_compile_generate_time, "second_compile_generate_time_secs": second_compile_generate_time, "third_compile_generate_time_secs": third_compile_generate_time, "fourth_compile_generate_time_secs": fourth_compile_generate_time, }, ) except Exception as e: logger.error(f"Caught exception: {e}") continue_metric_collection.set() if metrics_thread is not None: metrics_thread.join() # Only close the recorder if we created it locally if should_close_recorder: metrics_recorder.close()
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/masking_utils.py
src/transformers/masking_utils.py
# coding=utf-8 # Copyright 2025 HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import itertools from collections.abc import Callable from typing import Optional, Union import torch import torch.nn.functional as F from .cache_utils import Cache from .configuration_utils import PreTrainedConfig from .utils import is_torch_xpu_available, logging from .utils.generic import GeneralInterface from .utils.import_utils import is_torch_flex_attn_available, is_torch_greater_or_equal, is_tracing if is_torch_flex_attn_available(): from torch.nn.attention.flex_attention import _DEFAULT_SPARSE_BLOCK_SIZE as flex_default_block_size from torch.nn.attention.flex_attention import BlockMask, create_block_mask else: # Register a fake type to avoid crashing for annotations and `isinstance` checks BlockMask = torch.Tensor _is_torch_greater_or_equal_than_2_5 = is_torch_greater_or_equal("2.5", accept_dev=True) _is_torch_greater_or_equal_than_2_6 = is_torch_greater_or_equal("2.6", accept_dev=True) _is_torch_xpu_available = is_torch_xpu_available() if _is_torch_greater_or_equal_than_2_6: from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex logger = logging.get_logger(__name__) def and_masks(*mask_functions: Callable) -> Callable: """Returns a mask function that is the intersection of provided mask functions""" if not all(callable(arg) for arg in mask_functions): raise RuntimeError(f"All inputs should be callable mask_functions: {mask_functions}") def and_mask(batch_idx, head_idx, q_idx, kv_idx): result = q_idx.new_ones((), dtype=torch.bool) for mask in mask_functions: result = result & mask(batch_idx, head_idx, q_idx, kv_idx).to(result.device) return result return and_mask def or_masks(*mask_functions: Callable) -> Callable: """Returns a mask function that is the union of provided mask functions""" if not all(callable(arg) for arg in mask_functions): raise RuntimeError(f"All inputs should be callable mask_functions: {mask_functions}") def or_mask(batch_idx, head_idx, q_idx, kv_idx): result = q_idx.new_zeros((), dtype=torch.bool) for mask in mask_functions: result = result | mask(batch_idx, head_idx, q_idx, kv_idx).to(result.device) return result return or_mask def causal_mask_function(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool: """ This creates a basic lower-diagonal causal mask. """ return kv_idx <= q_idx def bidirectional_mask_function(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool: """ This creates a full bidirectional mask. NOTE: It is important to keep an index-based version for non-vmap expansion. """ return q_idx >= 0 def sliding_window_overlay(sliding_window: int) -> Callable: """ This is an overlay depicting a sliding window pattern. Add it on top of a causal mask for a proper sliding window mask. """ def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool: return kv_idx > q_idx - sliding_window return inner_mask def chunked_overlay(chunk_size: int, left_padding: torch.Tensor) -> Callable: """ This is an overlay depicting a chunked attention pattern. Add it on top of a causal mask for a proper chunked attention mask. """ def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool: return (kv_idx - left_padding[batch_idx]) // chunk_size == (q_idx - left_padding[batch_idx]) // chunk_size return inner_mask def sliding_window_causal_mask_function(sliding_window: int) -> Callable: """ This return the mask_function function to create a sliding window mask. """ return and_masks(sliding_window_overlay(sliding_window), causal_mask_function) def chunked_causal_mask_function(chunk_size: int, left_padding: torch.Tensor) -> Callable: """ This return the mask_function function to create a chunked attention mask. """ return and_masks(chunked_overlay(chunk_size, left_padding), causal_mask_function) def padding_mask_function(padding_mask: torch.Tensor) -> Callable: """ This return the mask_function function corresponding to a 2D padding mask. """ def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool: # Note that here the mask should ALWAYS be at least of the max `kv_index` size in the dimension 1. This is because # we cannot pad it here in the mask_function as we don't know the final size, and we cannot try/except, as it is not # vectorizable on accelerator devices return padding_mask[batch_idx, kv_idx] return inner_mask def packed_sequence_mask_function(packed_sequence_mask: torch.Tensor) -> Callable: """ This return the mask_function function corresponding to a 2D packed sequence mask. """ def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool: return packed_sequence_mask[batch_idx, q_idx] == packed_sequence_mask[batch_idx, kv_idx] return inner_mask def add_offsets_to_mask_function(mask_function: Callable, q_offset: int, kv_offset: int) -> Callable: """ This function adds the correct offsets to the `q_idx` and `kv_idx` as the torch API can only accept lengths, not start and end indices. """ def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool: return mask_function(batch_idx, head_idx, q_idx + q_offset, kv_idx + kv_offset) return inner_mask def prepare_padding_mask( attention_mask: Optional[torch.Tensor], kv_length: int, kv_offset: int ) -> Optional[torch.Tensor]: """ From the 2D attention mask, prepare the correct padding mask to use by potentially padding it. """ local_padding_mask = attention_mask if attention_mask is not None: # Pad it if necessary if (padding_length := kv_length + kv_offset - attention_mask.shape[-1]) > 0: local_padding_mask = torch.nn.functional.pad(attention_mask, (0, padding_length)) return local_padding_mask def _can_skip_causal_mask_xpu( padding_mask: Optional[torch.Tensor], query_length: int, kv_length: int, local_attention_size: Optional[int], ) -> bool: """ XPU-specific logic for determining if we can skip causal mask creation. For XPU devices, we have special handling: - Single query tokens (query_length == 1) use the same logic as CUDA - Multi-query tokens can skip if padding_mask is provided and correctly structured The mask must have all True values in the query window and all False after """ if is_tracing(padding_mask): return False # Check local attention constraint (same as CUDA) if local_attention_size is not None and kv_length >= local_attention_size: return False if padding_mask is None: # Without padding mask, can skip if single query token or full causal attention return query_length == 1 or kv_length == query_length # XPU allows skipping under additional conditions when padding_mask is provided if query_length == 1: # Single query token: skip only if no padding tokens present return padding_mask.all() # XPU-specific: check if query window is all True and rest is all False # This allows XPU to optimize the 1st token in static cache return padding_mask[:, :query_length].all() and not padding_mask[:, query_length:].any() def _ignore_causal_mask_sdpa( padding_mask: Optional[torch.Tensor], query_length: int, kv_length: int, kv_offset: int, local_attention_size: Optional[int] = None, ) -> bool: """ Detects whether the causal mask can be ignored in case PyTorch's SDPA is used, rather relying on SDPA's `is_causal` argument. In case no token is masked in the 2D `padding_mask` argument, if `query_length == 1` or `key_value_length == query_length`, we rather rely on SDPA `is_causal` argument to use causal/non-causal masks, allowing to dispatch to the flash attention kernel (that can otherwise not be used if a custom `attn_mask` is passed). """ if padding_mask is not None and padding_mask.shape[-1] > kv_length: mask_indices = torch.arange(kv_length, device=padding_mask.device) mask_indices += kv_offset padding_mask = padding_mask[:, mask_indices] if _is_torch_xpu_available: # XPU devices have special handling for mask skipping: # - Single query tokens use the same logic as CUDA # - Multi-query tokens can skip if padding_mask is provided and correctly structured # (all True in query window, all False after) return _can_skip_causal_mask_xpu(padding_mask, query_length, kv_length, local_attention_size) # When using `torch.export` or `torch.onnx.dynamo_export`, we must pass an example input, and `is_causal` behavior is # hard-coded to the forward. If a user exports a model with query_length > 1, the exported model will hard-code `is_causal=True` # which is in general wrong (see https://github.com/pytorch/pytorch/issues/108108). Thus, we only set # `ignore_causal_mask = True` if we are not tracing if ( not is_tracing(padding_mask) # only cases when lower and upper diags are the same, see https://github.com/pytorch/pytorch/issues/108108 and (query_length == 1 or kv_length == query_length) # in this case we need to add special patterns to the mask so cannot be skipped otherwise and (local_attention_size is None or kv_length < local_attention_size) # In this case, we need to add padding to the mask, so cannot be skipped otherwise and (padding_mask is None or padding_mask.all()) ): return True return False def _ignore_bidirectional_mask_sdpa(padding_mask: Optional[torch.Tensor]) -> bool: """ Detects whether the bidirectional mask can be ignored in case PyTorch's SDPA is used, i.e. when there is full attention with no padding. """ # When using `torch.export` or `torch.onnx.dynamo_export`, we need to avoid to check the contents of the mask; # otherwise, we will encounter dynamic control flows if not is_tracing(padding_mask) and (padding_mask is None or padding_mask.all()): return True return False def _vmap_expansion_sdpa(mask_function: Callable) -> Callable: """ Used to vmap our mask_functions over the all 4 dimensions (b_idx, h_idx, q_idx, kv_idx) of the inputs. Using vmap here allows us to keep the performance of vectorized ops, while having a single set of primitive functions between attention interfaces (i.e. between flex and sdpa/eager, FA2 being a bit different). """ # We vmap the function over all 4 dimensions, broadcasting [b_idx, h_idx, q_idx, kv_idx] dimensions = [(None, None, None, 0), (None, None, 0, None), (None, 0, None, None), (0, None, None, None)] for dims in dimensions: mask_function = torch.vmap(mask_function, in_dims=dims, out_dims=0) return mask_function def _non_vmap_expansion_sdpa( batch_indices: torch.Tensor, head_indices: torch.Tensor, q_indices: torch.Tensor, kv_indices: torch.Tensor ): """ Used to broadcast our mask_functions over the all 4 dimensions (b_idx, h_idx, q_idx, kv_idx) of the inputs. Allows the usage of any index-based mask function without relying on vmap. NOTE: This is limited to index based functions only and is not guaranteed to work otherwise. Reference: - https://github.com/huggingface/optimum-onnx/blob/c123e8f4fab61b54a8e0e31ce74462bcacca576e/optimum/exporters/onnx/model_patcher.py#L362-L365 """ batch_indices = batch_indices[:, None, None, None] head_indices = head_indices[None, :, None, None] q_indices = q_indices[None, None, :, None] kv_indices = kv_indices[None, None, None, :] return batch_indices, head_indices, q_indices, kv_indices def sdpa_mask( batch_size: int, cache_position: torch.Tensor, kv_length: int, kv_offset: int = 0, mask_function: Callable = causal_mask_function, attention_mask: Optional[torch.Tensor] = None, local_size: Optional[int] = None, allow_is_causal_skip: bool = True, allow_is_bidirectional_skip: bool = False, allow_torch_fix: bool = True, use_vmap: bool = False, **kwargs, ) -> Optional[torch.Tensor]: """ Create a 4D boolean mask of shape `(batch_size, 1, query_length, kv_length)` where a value of True indicates that the element should take part in the attention computation, and False that it should not. This function can only be used with torch>=2.5, as the context manager is otherwise not available. Args: batch_size (`int`): The batch size of the input sequence. cache_position (`torch.Tensor`): A tensor of shape (query_length,) indicating the current indices of the input sequence elements. kv_length (`int`): The size that the key and value states will have during the attention computation. kv_offset (`int`, optional): An optional offset to indicate at which first position the key and values states will refer to. mask_function (`Callable`): The mask factory function describing the mask pattern. attention_mask (`torch.Tensor`, optional): The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length) local_size (`int`, optional): The size of the local attention, if we do not use full attention. This is used only if `allow_is_causal_skip=True` to try to skip mask creation if possible. allow_is_causal_skip (`bool`, optional): Whether to allow to return `None` for the mask under conditions where we can use the `is_causal` argument in `torch.sdpa` instead. Default to `True`. allow_is_bidirectional_skip (`bool`, optional): Whether to allow to return `None` for the mask under conditions where we do not have to add any bias, i.e. full attention without any padding. Default to `False`. allow_torch_fix (`bool`, optional): Whether to update the mask in case a query is not attending to any tokens, to solve a bug in torch's older versions. We need an arg to skip it when using eager. By default `True`. use_vmap (`bool`, optional): Whether to use `vmap` during the mask construction or not. Allows powerful custom patterns that may not be index-based (for the cost of speed performance). By default `False`. ## Creating a simple causal mask: To create the following causal mask: 0 ■ ⬚ ⬚ ⬚ ⬚ 1 ■ ■ ⬚ ⬚ ⬚ 2 ■ ■ ■ ⬚ ⬚ 3 ■ ■ ■ ■ ⬚ 4 ■ ■ ■ ■ ■ You can do ```python >>> sdpa_mask(batch_size=1, cache_position=torch.arange(5), kv_length=5) >>> tensor([[[[ True, False, False, False, False], [ True, True, False, False, False], [ True, True, True, False, False], [ True, True, True, True, False], [ True, True, True, True, True]]]]) ``` ## Creating a sliding window mask: To create the following sliding window mask (`sliding_window=3`): 0 ■ ⬚ ⬚ ⬚ ⬚ 1 ■ ■ ⬚ ⬚ ⬚ 2 ■ ■ ■ ⬚ ⬚ 3 ⬚ ■ ■ ■ ⬚ 4 ⬚ ⬚ ■ ■ ■ You can do ```python >>> sdpa_mask(batch_size=1, cache_position=torch.arange(5), kv_length=5, mask_function=sliding_window_causal_mask_function(3)) >>> tensor([[[[ True, False, False, False, False], [ True, True, False, False, False], [ True, True, True, False, False], [False, True, True, True, False], [False, False, True, True, True]]]]) ``` ## Creating a chunked attention mask To create the following chunked attention mask (`chunk_size=3`): 0 ■ ⬚ ⬚ ⬚ ⬚ 1 ■ ■ ⬚ ⬚ ⬚ 2 ■ ■ ■ ⬚ ⬚ 3 ⬚ ⬚ ⬚ ■ ⬚ 4 ⬚ ⬚ ⬚ ■ ■ You can do ```python >>> sdpa_mask(batch_size=1, cache_position=torch.arange(5), kv_length=5, mask_function=chunked_causal_mask_function(3, torch.zeros(1, dtype=int))) >>> tensor([[[[ True, False, False, False, False], [ True, True, False, False, False], [ True, True, True, False, False], [False, False, False, True, False], [False, False, False, True, True]]]]) ``` """ q_length = cache_position.shape[0] # Potentially pad the 2D mask padding_mask = prepare_padding_mask(attention_mask, kv_length, kv_offset) # Under specific conditions, we can avoid materializing the mask # 1. Causal masks can rely on the `is_causal` argument # 2. Bidirectional do not need any further processing (no bias) if allow_is_causal_skip and _ignore_causal_mask_sdpa(padding_mask, q_length, kv_length, kv_offset, local_size): return None if allow_is_bidirectional_skip and _ignore_bidirectional_mask_sdpa(padding_mask): return None # Potentially add the padding 2D mask if padding_mask is not None: mask_function = and_masks(mask_function, padding_mask_function(padding_mask)) batch_arange = torch.arange(batch_size, device=cache_position.device) head_arange = torch.arange(1, device=cache_position.device) # Similar to `kv_arange = torch.arange(start=kv_offset, end=kv_offset + kv_length, device=cache_position.device)` # but without data-dependent slicing (i.e. torch.compile friendly) kv_arange = torch.arange(kv_length, device=cache_position.device) + kv_offset # Actual mask creation # Option 1: Fast non-vmap mask creation (default) if not use_vmap: # Apply mask function element-wise through broadcasting attention_mask = mask_function(*_non_vmap_expansion_sdpa(batch_arange, head_arange, cache_position, kv_arange)) # Expand the mask to match batch size and query length if they weren't used in the mask function attention_mask = attention_mask.expand(batch_size, -1, q_length, kv_length) # Option 2: Vmap mask creation (torch>=2.6 and custom patterns) elif _is_torch_greater_or_equal_than_2_6: # This creates the 4D mask easily. Note that we need this context manager as vmap cannot handle slicing a tensor from # scalar tensor (it internally calls `.item()` which vmap does not allow, but this context works around it # We don't need to add an offset to the mask_function either, as we vmap directly the correct indices for k and kv indices with TransformGetItemToIndex(): attention_mask = _vmap_expansion_sdpa(mask_function)(batch_arange, head_arange, cache_position, kv_arange) # Option 3: Error out since it indicates that the user did something custom, which they shouldn't have (torch<2.6) else: raise ValueError( "The vmap functionality for mask creation is only supported from torch>=2.6. " "Please update your torch version or use `use_vmap=False` with index-based masks." ) # Due to a bug in versions of torch<2.5, we need to update the mask in case a query is not attending to any # tokens (due to padding). See details in https://github.com/pytorch/pytorch/issues/110213 if not _is_torch_greater_or_equal_than_2_5 and allow_torch_fix: attention_mask = attention_mask | torch.all(~attention_mask, dim=-1, keepdim=True) return attention_mask def eager_mask( batch_size: int, cache_position: torch.Tensor, kv_length: int, kv_offset: int = 0, mask_function: Callable = causal_mask_function, attention_mask: Optional[torch.Tensor] = None, dtype: torch.dtype = torch.float32, allow_is_bidirectional_skip: bool = False, use_vmap: bool = False, **kwargs, ) -> torch.Tensor: """ Create a 4D float mask of shape `(batch_size, 1, query_length, kv_length)` where a value of 0 indicates that the element should take part in the attention computation, and -inf (minimum value for the given `dtype`) that it should not. Args: batch_size (`int`): The batch size of the input sequence. cache_position (`torch.Tensor`): A tensor of shape (query_length,) indicating the current indices of the input sequence elements. kv_length (`int`): The size that the key and value states will have during the attention computation. kv_offset (`int`, optional): An optional offset to indicate at which first position the key and values states will refer to. mask_function (`Callable`): The mask factory function describing the mask pattern. attention_mask (`torch.Tensor`, optional): The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length) dtype (`torch.dtype`, optional): The dtype to use for the mask. By default, `torch.float32`. allow_is_bidirectional_skip (`bool`, optional): Whether to allow to return `None` for the mask under conditions where we do not have to add any bias, i.e. full attention without any padding. Default to `False`. use_vmap (`bool`, optional): Whether to use `vmap` during the mask construction or not. Allows powerful custom patterns that may not be index-based (for the cost of speed performance). By default `False`. """ # The masks for eager attention are simply boolean mask from sdpa, casted to 0 and -inf _ = kwargs.pop("allow_is_causal_skip", None) _ = kwargs.pop("allow_torch_fix", None) mask = sdpa_mask( batch_size=batch_size, cache_position=cache_position, kv_length=kv_length, kv_offset=kv_offset, mask_function=mask_function, attention_mask=attention_mask, allow_is_causal_skip=False, allow_is_bidirectional_skip=allow_is_bidirectional_skip, allow_torch_fix=False, use_vmap=use_vmap, **kwargs, ) # only bidirectional masks can be skipped, otherwise we convert bool -> float if mask is not None: min_dtype = torch.finfo(dtype).min # we need 0s where the tokens should be taken into account, and -inf otherwise (mask is already of boolean type) mask = torch.where(mask, torch.tensor(0.0, device=mask.device, dtype=dtype), min_dtype) return mask def flash_attention_mask( batch_size: int, cache_position: torch.Tensor, kv_length: int, kv_offset: int = 0, mask_function: Callable = causal_mask_function, attention_mask: Optional[torch.Tensor] = None, **kwargs, ): """ Create the attention mask necessary to use FA2. Since FA2 is un-padded by definition, here we simply return `None` if the mask is fully causal, or we return the 2D mask which will then be used to extract the seq_lens. We just slice it in case of sliding window. Args: batch_size (`int`): The batch size of the input sequence. cache_position (`torch.Tensor`): A tensor of shape (query_length,) indicating the current indices of the input sequence elements. kv_length (`int`): The size that the key and value states will have during the attention computation. kv_offset (`int`, optional): An optional offset to indicate at which first position the key and values states will refer to. mask_function (`Callable`): The mask factory function describing the mask pattern. attention_mask (`torch.Tensor`, optional): The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length) """ if attention_mask is not None: # Here we need to slice from the right if using sliding or chunked (for full attention, this is equivalent to doing nothing) attention_mask = attention_mask[:, -kv_length:] # We only return an actual mask if there is at least 1 padding token, otherwise we return `None` and use `is_causal` in FA2 # (note that the attention_mask is a boolean dtype here) if attention_mask.all(): attention_mask = None return attention_mask def flex_attention_mask( batch_size: int, cache_position: torch.Tensor, kv_length: int, kv_offset: int = 0, mask_function: Callable = causal_mask_function, attention_mask: Optional[torch.Tensor] = None, **kwargs, ) -> BlockMask: """ Create a 4D block mask which is a compressed representation of the full 4D block causal mask. BlockMask is essential for performant computation of flex attention. See: https://pytorch.org/blog/flexattention/ Args: batch_size (`int`): The batch size of the input sequence. cache_position (`torch.Tensor`): A tensor of shape (query_length,) indicating the current indices of the input sequence elements. kv_length (`int`): The size that the key and value states will have during the attention computation. kv_offset (`int`, optional): An optional offset to indicate at which first position the key and values states will refer to. mask_function (`Callable`): The mask factory function describing the mask pattern. attention_mask (`torch.Tensor`, optional): The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length) """ q_length, q_offset = cache_position.shape[0], cache_position[0] # Potentially add the padding 2D mask if attention_mask is not None: # Older torch (2.5.x) cannot handle sequences not in multiples of 128 (default block size) # Hence we pad to multiples of this as a minimum to ensure this pad_len = ((attention_mask.shape[1] // flex_default_block_size) + 1) * flex_default_block_size pad_len = pad_len - attention_mask.shape[1] if not _is_torch_greater_or_equal_than_2_6 and pad_len > 0: attention_mask = torch.nn.functional.pad(attention_mask, value=0, pad=(0, pad_len)) padding_mask = prepare_padding_mask(attention_mask, kv_length, kv_offset) mask_function = and_masks(mask_function, padding_mask_function(padding_mask)) # Add the offsets on top (because flex interface only allows length, not start and end indices) mask_function = add_offsets_to_mask_function(mask_function, q_offset, kv_offset) # Finally create the block mask block_mask = create_block_mask( mask_mod=mask_function, B=batch_size, H=None, Q_LEN=q_length, KV_LEN=kv_length, device=cache_position.device, _compile=_is_torch_greater_or_equal_than_2_6, ) return block_mask class AttentionMaskInterface(GeneralInterface): # Class instance object, so that a call to `register` can be reflected into all other files correctly, even if # a new instance is created (in order to locally override a given function) _global_mapping = { "sdpa": sdpa_mask, "eager": eager_mask, "flash_attention_2": flash_attention_mask, "flash_attention_3": flash_attention_mask, "flex_attention": flex_attention_mask, } # Global AttentionMaskInterface shared by all models which do not need to overwrite any of the existing ones ALL_MASK_ATTENTION_FUNCTIONS: AttentionMaskInterface = AttentionMaskInterface() def find_packed_sequence_indices(position_ids: torch.Tensor) -> Optional[torch.Tensor]: """ Find the indices of the sequence to which each new query token in the sequence belongs when using packed tensor format (i.e. several sequences packed in the same batch dimension). Args: position_ids (`torch.Tensor`) A 2D tensor of shape (batch_size, query_length) indicating the positions of each token in the sequences. Returns: A 2D tensor where each similar integer indicates that the tokens belong to the same sequence. For example, if we pack 3 sequences of 2, 3 and 1 tokens respectively along a single batch dim, this will return [[0, 0, 1, 1, 1, 2]]. If the there is only one sequence in each batch item (and we don't compile), then we return `None` indicating no packed sequences. This is the same as [[0, 0, 0, 0, 0, 0]] for the example above. """ # What separate different sequences is when 2 consecutive positions_ids are separated by more than 1. So # taking the diff (by prepending the first value - 1 to keep correct indexing) and applying cumsum to the result # gives exactly the sequence indices # Note that we assume that a single sequence cannot span several batch dimensions, i.e. 1 single sequence # cannot be part of the end of the first batch dim and the start of the 2nd one for example first_dummy_value = position_ids[:, :1] - 1 # We just need the diff on this first value to be 1 position_diff = torch.diff(position_ids, prepend=first_dummy_value, dim=-1) packed_sequence_mask = (position_diff != 1).cumsum(-1) # Sadly this is a dynamic control flow, so we cannot enable this check on anything compile related if not is_tracing(packed_sequence_mask) and (packed_sequence_mask[:, -1] == 0).all(): return None return packed_sequence_mask def _preprocess_mask_arguments( config: PreTrainedConfig, input_embeds: torch.Tensor, attention_mask: Optional[Union[torch.Tensor, BlockMask]], cache_position: torch.Tensor, past_key_values: Optional[Cache], position_ids: Optional[torch.Tensor], layer_idx: Optional[int], ) -> tuple[bool, Optional[Union[torch.Tensor, BlockMask]], int, int]: """ Perform some common pre-processing of the mask arguments we get from the modeling code. Mostly determine the key-value length and offsets, and if we should early exit or not. Args: config (`PreTrainedConfig`): The model config. input_embeds (`torch.Tensor`): The input embeddings of shape (batch_size, query_length, hidden_dim). This is used only to infer the batch size, query length and dtype. attention_mask (`torch.Tensor`, optional): The 2D attention mask corresponding to padded tokens of shape (batch_size, number_of_seen_tokens+q_length). It can also be an already prepared 4D mask, in which case it is returned as-is. cache_position (`torch.Tensor`): A tensor of shape (query_length,) indicating the current indices of the input sequence elements. past_key_values (`Cache`, optional): The past key values, if we use a cache. position_ids (`torch.Tensor`, optional) A 2D tensor of shape (batch_size, query_length) indicating the positions of each token in the sequences. layer_idx (`int`, optional): If `past_key_values` is not None, this is the layer index of the cache from which to get the key-value length and offset. Indeed, for hybrid caches, different layers may return different lengths. Returns: early_exit (`bool`): Whether we should early exit mask creation, and return the mask as-is. attention_mask (`torch.Tensor` or `BlockMask` or `None`): The attention mask to either return immediately, or to use in downstream mask creation. packed_sequence_mask (`torch.Tensor`, optional): In case we detected packed sequence format, this is a tensor where each similar integer indicates that the tokens belong to the same sequence. kv_length (`int`):
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/modeling_utils.py
src/transformers/modeling_utils.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import copy import functools import importlib.metadata import inspect import json import os import re import sys import warnings from abc import abstractmethod from collections import defaultdict from collections.abc import Callable, Iterator, Sequence from contextlib import contextmanager from enum import Enum from functools import partial, wraps from itertools import cycle from threading import Thread from typing import Optional, TypeVar, Union, get_type_hints from zipfile import is_zipfile import torch from huggingface_hub import create_repo, is_offline_mode, split_torch_state_dict_into_shards from packaging import version from safetensors import safe_open from safetensors.torch import save_file as safe_save_file from torch import Tensor, nn from torch.distributions import constraints from torch.utils.checkpoint import checkpoint from . import initialization as init from .configuration_utils import PreTrainedConfig from .conversion_mapping import get_model_conversion_mapping from .core_model_loading import ( WeightConverter, WeightRenaming, convert_and_load_state_dict_in_model, revert_weight_conversion, ) from .distributed import DistributedConfig from .dynamic_module_utils import custom_object_save from .generation import CompileConfig, GenerationConfig from .integrations import PeftAdapterMixin, deepspeed_config, is_deepspeed_zero3_enabled, is_fsdp_enabled from .integrations.accelerate import ( _get_device_map, accelerate_disk_offload, accelerate_dispatch, check_and_set_device_map, expand_device_map, get_device, load_offloaded_parameter, ) from .integrations.deepspeed import _load_state_dict_into_zero3_model from .integrations.eager_paged import eager_paged_attention_forward from .integrations.flash_attention import flash_attention_forward from .integrations.flash_paged import paged_attention_forward from .integrations.flex_attention import flex_attention_forward from .integrations.hub_kernels import is_kernel from .integrations.peft import maybe_load_adapters from .integrations.sdpa_attention import sdpa_attention_forward from .integrations.sdpa_paged import sdpa_attention_paged_forward from .integrations.tensor_parallel import ( ALL_PARALLEL_STYLES, _get_parameter_tp_plan, distribute_model, initialize_tensor_parallelism, repack_weights, replace_state_dict_local_with_dtensor, shard_and_distribute_module, verify_tp_plan, ) from .loss.loss_utils import LOSS_MAPPING from .modeling_flash_attention_utils import lazy_import_flash_attention, lazy_import_paged_flash_attention from .modeling_rope_utils import ROPE_INIT_FUNCTIONS from .pytorch_utils import id_tensor_storage from .quantizers import HfQuantizer from .quantizers.auto import get_hf_quantizer from .quantizers.quantizers_utils import get_module_from_name from .safetensors_conversion import auto_conversion from .utils import ( ADAPTER_SAFE_WEIGHTS_NAME, DUMMY_INPUTS, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, KernelConfig, PushToHubMixin, cached_file, check_torch_load_is_safe, copy_func, has_file, is_accelerate_available, is_flash_attn_2_available, is_flash_attn_3_available, is_kernels_available, is_torch_flex_attn_available, is_torch_greater_or_equal, is_torch_mlu_available, is_torch_npu_available, is_torch_xpu_available, logging, ) from .utils.generic import _CAN_RECORD_REGISTRY, GeneralInterface, OutputRecorder from .utils.hub import DownloadKwargs, create_and_tag_model_card, get_checkpoint_shard_files from .utils.import_utils import ( is_huggingface_hub_greater_or_equal, is_sagemaker_mp_enabled, is_tracing, ) from .utils.loading_report import log_state_dict_report from .utils.quantization_config import QuantizationMethod if is_accelerate_available(): from accelerate.hooks import add_hook_to_module from accelerate.utils import extract_model_from_parallel _torch_distributed_available = torch.distributed.is_available() _is_dtensor_available = _torch_distributed_available and is_torch_greater_or_equal("2.5") if _is_dtensor_available: from torch.distributed.tensor import DTensor if is_sagemaker_mp_enabled(): import smdistributed.modelparallel.torch as smp from smdistributed.modelparallel import __version__ as SMP_VERSION IS_SAGEMAKER_MP_POST_1_10 = version.parse(SMP_VERSION) >= version.parse("1.10") else: IS_SAGEMAKER_MP_POST_1_10 = False logger = logging.get_logger(__name__) XLA_USE_BF16 = os.environ.get("XLA_USE_BF16", "0").upper() XLA_DOWNCAST_BF16 = os.environ.get("XLA_DOWNCAST_BF16", "0").upper() SpecificPreTrainedModelType = TypeVar("SpecificPreTrainedModelType", bound="PreTrainedModel") _is_quantized = False _is_ds_init_called = False # Mapping from flash attention implementations to their kernel fallback repositories FLASH_ATTN_KERNEL_FALLBACK = { "flash_attention_2": "kernels-community/flash-attn2", "flash_attention_3": "kernels-community/vllm-flash-attn3", } def is_local_dist_rank_0(): return ( torch.distributed.is_available() and torch.distributed.is_initialized() and int(os.environ.get("LOCAL_RANK", "-1")) == 0 ) @contextmanager def set_quantized_state(): global _is_quantized _is_quantized = True try: yield finally: _is_quantized = False # Skip recursive calls to deepspeed.zero.Init to avoid pinning errors. # This issue occurs with ZeRO stage 3 when using NVMe offloading. # For more details, refer to issue #34429. @contextmanager def set_zero3_state(): global _is_ds_init_called _is_ds_init_called = True try: yield finally: _is_ds_init_called = False @contextmanager def local_torch_dtype(dtype: torch.dtype, model_class_name: str | None = None): """ Locally change the torch default dtype to `dtype`, and restore the old one upon exiting the context. If `model_class_name` is provided, it's used to provide a more helpful error message if `dtype` is not valid. """ # Just a more helping error before we set `torch.set_default_dtype` later on which would crash in this case if not dtype.is_floating_point: if model_class_name is not None: error_message = ( f"{model_class_name} cannot be instantiated under `dtype={dtype}` as it's not a floating-point dtype" ) else: error_message = f"Cannot set `{dtype}` as torch's default as it's not a floating-point dtype" raise ValueError(error_message) original_dtype = torch.get_default_dtype() try: torch.set_default_dtype(dtype) yield finally: torch.set_default_dtype(original_dtype) def get_torch_context_manager_or_global_device(): """ Test if a device context manager is currently in use, or if it is not the case, check if the default device is not "cpu". This is used to infer the correct device to load the model on, in case `device_map` is not provided. """ device_in_context = torch.tensor([]).device # `get_default_device` was only introduced in torch>=2.3 - use cpu otherwise to align the behavior default_device = torch.get_default_device() if is_torch_greater_or_equal("2.3") else torch.device("cpu") # This case means no context manager was used -> we still check if the default that was potentially set is not cpu if device_in_context == default_device: if default_device != torch.device("cpu"): return default_device return None return device_in_context def get_state_dict_dtype(state_dict): """ Returns the first found floating dtype in `state_dict` if there is one, otherwise returns the first dtype. """ for t in state_dict.values(): if t.is_floating_point(): return t.dtype # if no floating dtype was found return whatever the first dtype is if len(state_dict) == 0: return torch.float32 return next(iter(state_dict.values())).dtype str_to_torch_dtype = { "BOOL": torch.bool, "U8": torch.uint8, "I8": torch.int8, "I16": torch.int16, "F16": torch.float16, "BF16": torch.bfloat16, "I32": torch.int32, "F32": torch.float32, "F64": torch.float64, "I64": torch.int64, "F8_E4M3": torch.float8_e4m3fn, "F8_E5M2": torch.float8_e5m2, } if is_torch_greater_or_equal("2.3.0"): str_to_torch_dtype["U16"] = torch.uint16 str_to_torch_dtype["U32"] = torch.uint32 str_to_torch_dtype["U64"] = torch.uint64 def load_state_dict( checkpoint_file: Union[str, os.PathLike], map_location: Union[str, torch.device] = "cpu", weights_only: bool = True ) -> dict[str, torch.Tensor]: """ Reads a `safetensor` or a `.bin` checkpoint file. We load the checkpoint on "cpu" by default. """ # Use safetensors if possible if checkpoint_file.endswith(".safetensors"): with safe_open(checkpoint_file, framework="pt") as f: state_dict = {} for k in f.keys(): if map_location == "meta": _slice = f.get_slice(k) k_dtype = _slice.get_dtype() if k_dtype in str_to_torch_dtype: dtype = str_to_torch_dtype[k_dtype] else: raise ValueError(f"Cannot load safetensors of unknown dtype {k_dtype}") state_dict[k] = torch.empty(size=_slice.get_shape(), dtype=dtype, device="meta") else: state_dict[k] = f.get_tensor(k).to(map_location) return state_dict # Fallback to torch.load (if weights_only was explicitly False, do not check safety as this is known to be unsafe) if weights_only: check_torch_load_is_safe() extra_args = {} # mmap can only be used with files serialized with zipfile-based format. if isinstance(checkpoint_file, str) and map_location != "meta" and is_zipfile(checkpoint_file): extra_args = {"mmap": True} return torch.load(checkpoint_file, map_location=map_location, weights_only=weights_only, **extra_args) def _end_ptr(tensor: torch.Tensor) -> int: # extract the end of the pointer if the tensor is a slice of a bigger tensor if tensor.nelement(): stop = tensor.view(-1)[-1].data_ptr() + tensor.element_size() else: stop = tensor.data_ptr() return stop def _get_tied_weight_keys(module: nn.Module) -> list[str]: tied_weight_keys: list[str] = [] for name, submodule in module.named_modules(): tied = getattr(submodule, "_tied_weights_keys", {}) or {} tied_weight_keys.extend([f"{name}.{k}" if name else k for k in tied.keys()]) return tied_weight_keys def _find_disjoint(tensors: list[set[str]], state_dict: dict[str, torch.Tensor]) -> tuple[list[set[str]], list[str]]: filtered_tensors = [] for shared in tensors: if len(shared) < 2: filtered_tensors.append(shared) continue areas = [] for name in shared: tensor = state_dict[name] areas.append((tensor.data_ptr(), _end_ptr(tensor), name)) areas.sort() _, last_stop, last_name = areas[0] filtered_tensors.append({last_name}) for start, stop, name in areas[1:]: if start >= last_stop: filtered_tensors.append({name}) else: filtered_tensors[-1].add(name) last_stop = stop disjoint_tensors = [] shared_tensors = [] for tensors in filtered_tensors: if len(tensors) == 1: disjoint_tensors.append(tensors.pop()) else: shared_tensors.append(tensors) return shared_tensors, disjoint_tensors def _find_identical(tensors: list[set[str]], state_dict: dict[str, torch.Tensor]) -> tuple[list[set[str]], set[str]]: shared_tensors = [] identical = [] for shared in tensors: if len(shared) < 2: continue areas = collections.defaultdict(set) for name in shared: tensor = state_dict[name] area = (tensor.device, tensor.data_ptr(), _end_ptr(tensor)) areas[area].add(name) if len(areas) == 1: identical.append(shared) else: shared_tensors.append(shared) return shared_tensors, identical def remove_tied_weights_from_state_dict( state_dict: dict[str, torch.Tensor], model: "PreTrainedModel" ) -> dict[str, torch.Tensor]: """ Remove all tied weights from the given `state_dict`, making sure to keep only the main weight that `model` will expect when reloading (even if we know tie weights symmetrically, it's better to keep the intended one). This is because `safetensors` does not allow tensor aliasing - so we're going to remove aliases before saving. """ # To avoid any potential mistakes and mismatches between config and actual tied weights, here we check the pointers # of the Tensors themselves -> we are guaranteed to find all the actual tied weights ptrs = collections.defaultdict(list) for name, tensor in state_dict.items(): if not isinstance(tensor, torch.Tensor): # Sometimes in the state_dict we have non-tensor objects. # e.g. in bitsandbytes we have some `str` objects in the state_dict # In the non-tensor case, fall back to the pointer of the object itself ptrs[id(tensor)].append(name) elif tensor.device.type == "meta": # In offloaded cases, there may be meta tensors in the state_dict. # For these cases, key by the pointer of the original tensor object # (state_dict tensors are detached and therefore no longer shared) tensor = model.get_parameter(name) ptrs[id(tensor)].append(name) else: ptrs[id_tensor_storage(tensor)].append(name) shared_ptrs = {ptr: names for ptr, names in ptrs.items() if len(names) > 1} # Recursively descend to find tied weight keys all_potential_tied_weights_keys = set(_get_tied_weight_keys(model)) error_names = [] to_delete_names = set() # Removing the keys which are declared as known duplicates on load. This allows to make sure the name which is # kept is consistent if all_potential_tied_weights_keys is not None: for names in shared_ptrs.values(): found = 0 for name in sorted(names): matches_pattern = any(re.search(pat, name) for pat in all_potential_tied_weights_keys) if matches_pattern and name in state_dict: found += 1 if found < len(names): to_delete_names.add(name) # We are entering a place where the weights and the transformers configuration do NOT match. shared_names, disjoint_names = _find_disjoint(shared_ptrs.values(), state_dict) # Those are actually tensor sharing but disjoint from each other, we can safely clone them # Reloaded won't have the same property, but it shouldn't matter in any meaningful way. for name in disjoint_names: state_dict[name] = state_dict[name].clone() # When not all duplicates have been cleaned, still remove those keys, but put a clear warning. # If the link between tensors was done at runtime then `from_pretrained` will not get # the key back leading to random tensor. A proper warning will be shown # during reload (if applicable), but since the file is not necessarily compatible with # the config, better show a proper warning. shared_names, identical_names = _find_identical(shared_names, state_dict) # delete tensors that have identical storage for inames in identical_names: known = inames.intersection(to_delete_names) for name in known: del state_dict[name] unknown = inames.difference(to_delete_names) if len(unknown) > 1: error_names.append(unknown) if shared_names: error_names.extend(shared_names) if len(error_names) > 0: raise RuntimeError( f"The weights trying to be saved contained shared tensors {error_names} which are not properly defined. " f"We found all the potential target tied weights keys to be: {all_potential_tied_weights_keys}.\n" "This can also just mean that the module's tied weight keys are wrong vs the actual tied weights in the model.", ) return state_dict def _load_parameter_into_model(model: "PreTrainedModel", param_name: str, tensor: torch.Tensor): """Cast a single parameter or buffer `param_name` into the `model`, with value `tensor`.""" parent, param_type = get_module_from_name(model, param_name) if param_type in parent._parameters and not isinstance(tensor, nn.Parameter): tensor = nn.Parameter(tensor, requires_grad=tensor.is_floating_point()) # We need to use setattr here, as we set non-persistent buffers as well with this function (`load_state_dict` # does not allow to do it) setattr(parent, param_type, tensor) def _add_variant(weights_name: str, variant: Optional[str] = None) -> str: if variant is not None: path, name = weights_name.rsplit(".", 1) weights_name = f"{path}.{variant}.{name}" return weights_name def _get_resolved_checkpoint_files( pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], variant: Optional[str], gguf_file: Optional[str], use_safetensors: Optional[bool], download_kwargs: DownloadKwargs, user_agent: dict, is_remote_code: bool, # Because we can't determine this inside this function, we need it to be passed in transformers_explicit_filename: Optional[str] = None, ) -> tuple[Optional[list[str]], Optional[dict]]: """Get all the checkpoint filenames based on `pretrained_model_name_or_path`, and optional metadata if the checkpoints are sharded. This function will download the data if necessary. """ cache_dir = download_kwargs.get("cache_dir") force_download = download_kwargs.get("force_download", False) proxies = download_kwargs.get("proxies") local_files_only = download_kwargs.get("local_files_only", False) token = download_kwargs.get("token") revision = download_kwargs.get("revision") or "main" subfolder = download_kwargs.get("subfolder", "") commit_hash = download_kwargs.get("commit_hash") if transformers_explicit_filename is not None: if not transformers_explicit_filename.endswith(".safetensors") and not transformers_explicit_filename.endswith( ".safetensors.index.json" ): raise ValueError( "The transformers file in the config seems to be incorrect: it is neither a safetensors file " "(*.safetensors) nor a safetensors index file (*.safetensors.index.json): " f"{transformers_explicit_filename}" ) is_sharded = False if pretrained_model_name_or_path is not None and gguf_file is None: pretrained_model_name_or_path = str(pretrained_model_name_or_path) is_local = os.path.isdir(pretrained_model_name_or_path) if is_local: if transformers_explicit_filename is not None: # If the filename is explicitly defined, load this by default. archive_file = os.path.join(pretrained_model_name_or_path, subfolder, transformers_explicit_filename) is_sharded = transformers_explicit_filename.endswith(".safetensors.index.json") elif use_safetensors is not False and os.path.isfile( os.path.join(pretrained_model_name_or_path, subfolder, _add_variant(SAFE_WEIGHTS_NAME, variant)) ): # Load from a safetensors checkpoint archive_file = os.path.join( pretrained_model_name_or_path, subfolder, _add_variant(SAFE_WEIGHTS_NAME, variant) ) elif use_safetensors is not False and os.path.isfile( os.path.join(pretrained_model_name_or_path, subfolder, _add_variant(SAFE_WEIGHTS_INDEX_NAME, variant)) ): # Load from a sharded safetensors checkpoint archive_file = os.path.join( pretrained_model_name_or_path, subfolder, _add_variant(SAFE_WEIGHTS_INDEX_NAME, variant) ) is_sharded = True elif not use_safetensors and os.path.isfile( os.path.join(pretrained_model_name_or_path, subfolder, _add_variant(WEIGHTS_NAME, variant)) ): # Load from a PyTorch checkpoint archive_file = os.path.join( pretrained_model_name_or_path, subfolder, _add_variant(WEIGHTS_NAME, variant) ) elif not use_safetensors and os.path.isfile( os.path.join(pretrained_model_name_or_path, subfolder, _add_variant(WEIGHTS_INDEX_NAME, variant)) ): # Load from a sharded PyTorch checkpoint archive_file = os.path.join( pretrained_model_name_or_path, subfolder, _add_variant(WEIGHTS_INDEX_NAME, variant) ) is_sharded = True elif use_safetensors: raise OSError( f"Error no file named {_add_variant(SAFE_WEIGHTS_NAME, variant)} found in directory" f" {pretrained_model_name_or_path}." ) else: raise OSError( f"Error no file named {_add_variant(SAFE_WEIGHTS_NAME, variant)}, or {_add_variant(WEIGHTS_NAME, variant)}," f" found in directory {pretrained_model_name_or_path}." ) elif os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)): archive_file = pretrained_model_name_or_path is_local = True else: # set correct filename if transformers_explicit_filename is not None: filename = transformers_explicit_filename is_sharded = transformers_explicit_filename.endswith(".safetensors.index.json") elif use_safetensors is not False: filename = _add_variant(SAFE_WEIGHTS_NAME, variant) else: filename = _add_variant(WEIGHTS_NAME, variant) try: # Load from URL or cache if already cached cached_file_kwargs = { "cache_dir": cache_dir, "force_download": force_download, "proxies": proxies, "local_files_only": local_files_only, "token": token, "user_agent": user_agent, "revision": revision, "subfolder": subfolder, "_raise_exceptions_for_gated_repo": False, "_raise_exceptions_for_missing_entries": False, "_commit_hash": commit_hash, } resolved_archive_file = cached_file(pretrained_model_name_or_path, filename, **cached_file_kwargs) # Since we set _raise_exceptions_for_missing_entries=False, we don't get an exception but a None # result when internet is up, the repo and revision exist, but the file does not. if resolved_archive_file is None and filename == _add_variant(SAFE_WEIGHTS_NAME, variant): # Maybe the checkpoint is sharded, we try to grab the index name in this case. resolved_archive_file = cached_file( pretrained_model_name_or_path, _add_variant(SAFE_WEIGHTS_INDEX_NAME, variant), **cached_file_kwargs, ) if resolved_archive_file is not None: is_sharded = True elif use_safetensors: if revision == "main" and not is_offline_mode(): resolved_archive_file, revision, is_sharded = auto_conversion( pretrained_model_name_or_path, **cached_file_kwargs ) cached_file_kwargs["revision"] = revision if resolved_archive_file is None: raise OSError( f"{pretrained_model_name_or_path} does not appear to have a file named" f" {_add_variant(SAFE_WEIGHTS_NAME, variant)} or {_add_variant(SAFE_WEIGHTS_INDEX_NAME, variant)} " "and thus cannot be loaded with `safetensors`. Please do not set `use_safetensors=True`." ) else: # This repo has no safetensors file of any kind, we switch to PyTorch. filename = _add_variant(WEIGHTS_NAME, variant) resolved_archive_file = cached_file( pretrained_model_name_or_path, filename, **cached_file_kwargs ) if resolved_archive_file is None and filename == _add_variant(WEIGHTS_NAME, variant): # Maybe the checkpoint is sharded, we try to grab the index name in this case. resolved_archive_file = cached_file( pretrained_model_name_or_path, _add_variant(WEIGHTS_INDEX_NAME, variant), **cached_file_kwargs, ) if resolved_archive_file is not None: is_sharded = True if not local_files_only and not is_offline_mode(): if resolved_archive_file is not None: # In a CI environment (CircleCI / Github Actions workflow runs) or in a pytest run, # we set `DISABLE_SAFETENSORS_CONVERSION=true` to prevent the conversion. if ( filename in [WEIGHTS_NAME, WEIGHTS_INDEX_NAME] and os.getenv("DISABLE_SAFETENSORS_CONVERSION", None) != "true" ): # If the PyTorch file was found, check if there is a safetensors file on the repository # If there is no safetensors file on the repositories, start an auto conversion safe_weights_name = SAFE_WEIGHTS_INDEX_NAME if is_sharded else SAFE_WEIGHTS_NAME has_file_kwargs = { "revision": revision, "proxies": proxies, "token": token, "cache_dir": cache_dir, "local_files_only": local_files_only, } cached_file_kwargs = { "cache_dir": cache_dir, "force_download": force_download, "local_files_only": local_files_only, "user_agent": user_agent, "subfolder": subfolder, "_raise_exceptions_for_gated_repo": False, "_raise_exceptions_for_missing_entries": False, "_commit_hash": commit_hash, **has_file_kwargs, } if ( not has_file(pretrained_model_name_or_path, safe_weights_name, **has_file_kwargs) and not is_remote_code ): Thread( target=auto_conversion, args=(pretrained_model_name_or_path,), kwargs={"ignore_errors_during_conversion": True, **cached_file_kwargs}, name="Thread-auto_conversion", ).start() else: # Otherwise, no PyTorch file was found has_file_kwargs = { "revision": revision, "proxies": proxies, "token": token, "cache_dir": cache_dir, "local_files_only": local_files_only, } if variant is not None and has_file( pretrained_model_name_or_path, WEIGHTS_NAME, **has_file_kwargs ): raise OSError( f"{pretrained_model_name_or_path} does not appear to have a file named" f" {_add_variant(WEIGHTS_NAME, variant)} but there is a file without the variant" f" {variant}. Use `variant=None` to load this model from those weights." ) else: raise OSError( f"{pretrained_model_name_or_path} does not appear to have a file named" f" {_add_variant(WEIGHTS_NAME, variant)} or {_add_variant(SAFE_WEIGHTS_NAME, variant)}." ) except OSError: # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted # to the original exception. raise except Exception as e: # For any other exception, we throw a generic error. raise OSError( f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it" " from 'https://huggingface.co/models', make sure you don't have a local directory with the" f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a" f" directory containing a file named {_add_variant(WEIGHTS_NAME, variant)}." ) from e if is_local: logger.info(f"loading weights file {archive_file}") resolved_archive_file = archive_file else: logger.info(f"loading weights file {filename} from cache at {resolved_archive_file}") elif gguf_file: # Case 1: the GGUF file is present locally if os.path.isfile(gguf_file): resolved_archive_file = gguf_file # Case 2: The GGUF path is a location on the Hub # Load from URL or cache if already cached else: cached_file_kwargs = { "cache_dir": cache_dir, "force_download": force_download, "proxies": proxies, "local_files_only": local_files_only, "token": token, "user_agent": user_agent, "revision": revision, "subfolder": subfolder, "_raise_exceptions_for_gated_repo": False, "_raise_exceptions_for_missing_entries": False, "_commit_hash": commit_hash, } resolved_archive_file = cached_file(pretrained_model_name_or_path, gguf_file, **cached_file_kwargs) # We now download and resolve all checkpoint files if the checkpoint is sharded sharded_metadata = None if is_sharded: checkpoint_files, sharded_metadata = get_checkpoint_shard_files(
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/feature_extraction_sequence_utils.py
src/transformers/feature_extraction_sequence_utils.py
# Copyright 2021 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Sequence feature extraction class for common feature extractors to preprocess sequences. """ from typing import Optional, Union import numpy as np from .audio_utils import is_valid_audio, load_audio from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_torch_tensor, logging, to_numpy logger = logging.get_logger(__name__) class SequenceFeatureExtractor(FeatureExtractionMixin): """ This is a general feature extraction class for speech recognition. Args: feature_size (`int`): The feature dimension of the extracted features. sampling_rate (`int`): The sampling rate at which the audio files should be digitalized expressed in hertz (Hz). padding_value (`float`): The value that is used to fill the padding values / vectors. """ def __init__(self, feature_size: int, sampling_rate: int, padding_value: float, **kwargs): self.feature_size = feature_size self.sampling_rate = sampling_rate self.padding_value = padding_value self.padding_side = kwargs.pop("padding_side", "right") self.return_attention_mask = kwargs.pop("return_attention_mask", True) super().__init__(**kwargs) def pad( self, processed_features: Union[ BatchFeature, list[BatchFeature], dict[str, BatchFeature], dict[str, list[BatchFeature]], list[dict[str, BatchFeature]], ], padding: Union[bool, str, PaddingStrategy] = True, max_length: Optional[int] = None, truncation: bool = False, pad_to_multiple_of: Optional[int] = None, return_attention_mask: Optional[bool] = None, return_tensors: Optional[Union[str, TensorType]] = None, ) -> BatchFeature: """ Pad input values / input vectors or a batch of input values / input vectors up to predefined length or to the max sequence length in the batch. Padding side (left/right) padding values are defined at the feature extractor level (with `self.padding_side`, `self.padding_value`) <Tip> If the `processed_features` passed are dictionary of numpy arrays or PyTorch tensors the result will use the same type unless you provide a different tensor type with `return_tensors`. In the case of PyTorch tensors, you will lose the specific device of your tensors however. </Tip> Args: processed_features ([`BatchFeature`], list of [`BatchFeature`], `dict[str, list[float]]`, `dict[str, list[list[float]]` or `list[dict[str, list[float]]]`): Processed inputs. Can represent one input ([`BatchFeature`] or `dict[str, list[float]]`) or a batch of input values / vectors (list of [`BatchFeature`], *dict[str, list[list[float]]]* or *list[dict[str, list[float]]]*) so you can use this method during preprocessing as well as in a PyTorch Dataloader collate function. Instead of `list[float]` you can have tensors (numpy arrays or PyTorch tensors), see the note above for the return type. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`): Select a strategy to pad the returned sequences (according to the model's padding side and padding index) among: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). max_length (`int`, *optional*): Maximum length of the returned list and optionally padding length (see above). truncation (`bool`): Activates truncation to cut input sequences longer than `max_length` to `max_length`. pad_to_multiple_of (`int`, *optional*): If set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. return_attention_mask (`bool`, *optional*): Whether to return the attention mask. If left to the default, will return the attention mask according to the specific feature_extractor's default. [What are attention masks?](../glossary#attention-mask) return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. """ # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(processed_features, (list, tuple)) and isinstance(processed_features[0], (dict, BatchFeature)): # Call .keys() explicitly for compatibility with TensorDict and other Mapping subclasses processed_features = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" f" to this method that includes {self.model_input_names[0]}, but you provided" f" {list(processed_features.keys())}" ) required_input = processed_features[self.model_input_names[0]] return_attention_mask = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(required_input) == 0: if return_attention_mask: processed_features["attention_mask"] = [] return processed_features # If we have PyTorch tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch first_element = required_input[0] if isinstance(first_element, (list, tuple)): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. index = 0 while len(required_input[index]) == 0: index += 1 if index < len(required_input): first_element = required_input[index][0] if return_tensors is None: if is_torch_tensor(first_element): return_tensors = "pt" elif isinstance(first_element, (int, float, list, tuple, np.ndarray)): return_tensors = "np" else: raise ValueError( f"type of {first_element} unknown: {type(first_element)}. " "Should be one of a python, numpy, or pytorch object." ) for key, value in processed_features.items(): if isinstance(value[0], (int, float)): processed_features[key] = to_numpy(value) else: processed_features[key] = [to_numpy(v) for v in value] # Convert padding_strategy in PaddingStrategy padding_strategy = self._get_padding_strategies(padding=padding, max_length=max_length) required_input = processed_features[self.model_input_names[0]] batch_size = len(required_input) if not all(len(v) == batch_size for v in processed_features.values()): raise ValueError("Some items in the output dictionary have a different batch size than others.") truncated_inputs = [] for i in range(batch_size): inputs = {k: v[i] for k, v in processed_features.items()} # truncation inputs_slice = self._truncate( inputs, max_length=max_length, pad_to_multiple_of=pad_to_multiple_of, truncation=truncation, ) truncated_inputs.append(inputs_slice) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length max_length = max(len(input_slice[self.model_input_names[0]]) for input_slice in truncated_inputs) padding_strategy = PaddingStrategy.MAX_LENGTH batch_outputs = {} for i in range(batch_size): # padding outputs = self._pad( truncated_inputs[i], max_length=max_length, padding_strategy=padding_strategy, pad_to_multiple_of=pad_to_multiple_of, return_attention_mask=return_attention_mask, ) for key, value in outputs.items(): if key not in batch_outputs: batch_outputs[key] = [] if value.dtype is np.dtype(np.float64): value = value.astype(np.float32) batch_outputs[key].append(value) return BatchFeature(batch_outputs, tensor_type=return_tensors) def _pad( self, processed_features: Union[dict[str, np.ndarray], BatchFeature], max_length: Optional[int] = None, padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, pad_to_multiple_of: Optional[int] = None, return_attention_mask: Optional[bool] = None, ) -> dict: """ Pad inputs (on left/right and up to predefined length or max length in the batch) Args: processed_features (`Union[dict[str, np.ndarray], BatchFeature]`): Dictionary of input values (`np.ndarray[float]`) / input vectors (`list[np.ndarray[float]]`) or batch of inputs values (`list[np.ndarray[int]]`) / input vectors (`list[np.ndarray[int]]`) max_length (`int`, *optional*): Maximum length of the returned list and optionally padding length (see below) padding_strategy (`PaddingStrategy`, *optional*, default to `PaddingStrategy.DO_NOT_PAD`): PaddingStrategy to use for padding. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch - PaddingStrategy.MAX_LENGTH: Pad to the max length (default) - PaddingStrategy.DO_NOT_PAD: Do not pad The feature_extractor padding sides are defined in self.padding_side: - 'left': pads on the left of the sequences - 'right': pads on the right of the sequences pad_to_multiple_of (`int`, *optional*): Integer if set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. return_attention_mask (`bool`, *optional*): Set to False to avoid returning attention mask (default: set to model specifics) """ required_input = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: max_length = len(required_input) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) < max_length if return_attention_mask and "attention_mask" not in processed_features: processed_features["attention_mask"] = np.ones(len(required_input), dtype=np.int32) if needs_to_be_padded: difference = max_length - len(required_input) if self.padding_side == "right": if return_attention_mask: processed_features["attention_mask"] = np.pad( processed_features["attention_mask"], (0, difference) ) padding_shape = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) processed_features[self.model_input_names[0]] = np.pad( required_input, padding_shape, "constant", constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: processed_features["attention_mask"] = np.pad( processed_features["attention_mask"], (difference, 0) ) padding_shape = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) processed_features[self.model_input_names[0]] = np.pad( required_input, padding_shape, "constant", constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side)) return processed_features def _truncate( self, processed_features: Union[dict[str, np.ndarray], BatchFeature], max_length: Optional[int] = None, pad_to_multiple_of: Optional[int] = None, truncation: Optional[bool] = None, ): """ Truncate inputs to predefined length or max length in the batch Args: processed_features(`Union[dict[str, np.ndarray], BatchFeature]`): Dictionary of input values (`np.ndarray[float]`) / input vectors (`list[np.ndarray[float]]`) or batch of inputs values (`list[np.ndarray[int]]`) / input vectors (`list[np.ndarray[int]]`) max_length (`int`, *optional*): maximum length of the returned list and optionally padding length (see below) pad_to_multiple_of (`int`, *optional*) : Integer if set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. truncation (`bool`, *optional*): Activates truncation to cut input sequences longer than `max_length` to `max_length`. """ if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined.") required_input = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of needs_to_be_truncated = len(required_input) > max_length if needs_to_be_truncated: processed_features[self.model_input_names[0]] = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: processed_features["attention_mask"] = processed_features["attention_mask"][:max_length] return processed_features def _get_padding_strategies(self, padding=False, max_length=None): """ Find the correct padding strategy """ # Get padding strategy if padding is not False: if padding is True: padding_strategy = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(padding, PaddingStrategy): padding_strategy = PaddingStrategy(padding) elif isinstance(padding, PaddingStrategy): padding_strategy = padding else: padding_strategy = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f"When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy def fetch_audio(self, audio_url_or_urls: Union[str, list[str], list[list[str]]]): """ Convert a single or a list of urls into the corresponding `np.ndarray` objects. If a single url is passed, the return value will be a single object. If a list is passed a list of objects is returned. """ if isinstance(audio_url_or_urls, list): return [self.fetch_audio(x) for x in audio_url_or_urls] elif isinstance(audio_url_or_urls, str): return load_audio(audio_url_or_urls) elif is_valid_audio(audio_url_or_urls): return audio_url_or_urls else: raise TypeError(f"only a single or a list of entries is supported but got type={type(audio_url_or_urls)}")
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/audio_utils.py
src/transformers/audio_utils.py
# Copyright 2023 The HuggingFace Inc. team and the librosa & torchaudio authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Audio processing functions to extract features from audio waveforms. This code is pure numpy to support all frameworks and remove unnecessary dependencies. """ import base64 import importlib import io import os import warnings from collections.abc import Sequence from io import BytesIO from typing import TYPE_CHECKING, Any, Optional, Union import httpx import numpy as np from packaging import version from .utils import ( is_librosa_available, is_numpy_array, is_soundfile_available, is_torch_tensor, is_torchcodec_available, requires_backends, ) if TYPE_CHECKING: import torch if is_soundfile_available(): import soundfile as sf if is_librosa_available(): import librosa # TODO: @eustlb, we actually don't need librosa but soxr is installed with librosa import soxr if is_torchcodec_available(): TORCHCODEC_VERSION = version.parse(importlib.metadata.version("torchcodec")) AudioInput = Union[np.ndarray, "torch.Tensor", Sequence[np.ndarray], Sequence["torch.Tensor"]] def load_audio(audio: Union[str, np.ndarray], sampling_rate=16000, timeout=None) -> np.ndarray: """ Loads `audio` to an np.ndarray object. Args: audio (`str` or `np.ndarray`): The audio to be loaded to the numpy array format. sampling_rate (`int`, *optional*, defaults to 16000): The sampling rate to be used when loading the audio. It should be same as the sampling rate the model you will be using further was trained with. timeout (`float`, *optional*): The timeout value in seconds for the URL request. Returns: `np.ndarray`: A numpy array representing the audio. """ if isinstance(audio, str): # Try to load with `torchcodec` but do not enforce users to install it. If not found # fallback to `librosa`. If using an audio-only model, most probably `torchcodec` won't be # needed. Do not raise any errors if not installed or versions do not match if is_torchcodec_available() and TORCHCODEC_VERSION >= version.parse("0.3.0"): audio = load_audio_torchcodec(audio, sampling_rate=sampling_rate) else: audio = load_audio_librosa(audio, sampling_rate=sampling_rate, timeout=timeout) elif not isinstance(audio, np.ndarray): raise TypeError( "Incorrect format used for `audio`. Should be an url linking to an audio, a local path, or numpy array." ) return audio def load_audio_torchcodec(audio: Union[str, np.ndarray], sampling_rate=16000) -> np.ndarray: """ Loads `audio` to an np.ndarray object using `torchcodec`. Args: audio (`str` or `np.ndarray`): The audio to be loaded to the numpy array format. sampling_rate (`int`, *optional*, defaults to 16000): The sampling rate to be used when loading the audio. It should be same as the sampling rate the model you will be using further was trained with. Returns: `np.ndarray`: A numpy array representing the audio. """ # Lazy import so that issues in torchcodec compatibility don't crash the whole library requires_backends(load_audio_torchcodec, ["torchcodec"]) from torchcodec.decoders import AudioDecoder # Set `num_channels` to `1` which is what most models expects and the default in librosa decoder = AudioDecoder(audio, sample_rate=sampling_rate, num_channels=1) audio = decoder.get_all_samples().data[0].numpy() # NOTE: feature extractors don't accept torch tensors return audio def load_audio_librosa(audio: Union[str, np.ndarray], sampling_rate=16000, timeout=None) -> np.ndarray: """ Loads `audio` to an np.ndarray object using `librosa`. Args: audio (`str` or `np.ndarray`): The audio to be loaded to the numpy array format. sampling_rate (`int`, *optional*, defaults to 16000): The sampling rate to be used when loading the audio. It should be same as the sampling rate the model you will be using further was trained with. timeout (`float`, *optional*): The timeout value in seconds for the URL request. Returns: `np.ndarray`: A numpy array representing the audio. """ requires_backends(load_audio_librosa, ["librosa"]) # Load audio from URL (e.g https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/translate_to_chinese.wav) if audio.startswith("http://") or audio.startswith("https://"): audio = librosa.load( BytesIO(httpx.get(audio, follow_redirects=True, timeout=timeout).content), sr=sampling_rate )[0] elif os.path.isfile(audio): audio = librosa.load(audio, sr=sampling_rate)[0] return audio def load_audio_as( audio: str, return_format: str, timeout: Optional[int] = None, force_mono: bool = False, sampling_rate: Optional[int] = None, ) -> Union[str, dict[str, Any], io.BytesIO, None]: """ Load audio from either a local file path or URL and return in specified format. Args: audio (`str`): Either a local file path or a URL to an audio file return_format (`str`): Format to return the audio in: - "base64": Base64 encoded string - "dict": Dictionary with data and format - "buffer": BytesIO object timeout (`int`, *optional*): Timeout for URL requests in seconds force_mono (`bool`): Whether to convert stereo audio to mono sampling_rate (`int`, *optional*): If provided, the audio will be resampled to the specified sampling rate. Returns: `Union[str, Dict[str, Any], io.BytesIO, None]`: - `str`: Base64 encoded audio data (if return_format="base64") - `dict`: Dictionary with 'data' (base64 encoded audio data) and 'format' keys (if return_format="dict") - `io.BytesIO`: BytesIO object containing audio data (if return_format="buffer") """ # TODO: @eustlb, we actually don't need librosa but soxr is installed with librosa requires_backends(load_audio_as, ["librosa"]) if return_format not in ["base64", "dict", "buffer"]: raise ValueError(f"Invalid return_format: {return_format}. Must be 'base64', 'dict', or 'buffer'") try: # Load audio bytes from URL or file audio_bytes = None if audio.startswith(("http://", "https://")): response = httpx.get(audio, follow_redirects=True, timeout=timeout) response.raise_for_status() audio_bytes = response.content elif os.path.isfile(audio): with open(audio, "rb") as audio_file: audio_bytes = audio_file.read() else: raise ValueError(f"File not found: {audio}") # Process audio data with io.BytesIO(audio_bytes) as audio_file: with sf.SoundFile(audio_file) as f: audio_array = f.read(dtype="float32") original_sr = f.samplerate audio_format = f.format if sampling_rate is not None and sampling_rate != original_sr: # Resample audio to target sampling rate audio_array = soxr.resample(audio_array, original_sr, sampling_rate, quality="HQ") else: sampling_rate = original_sr # Convert to mono if needed if force_mono and audio_array.ndim != 1: audio_array = audio_array.mean(axis=1) buffer = io.BytesIO() sf.write(buffer, audio_array, sampling_rate, format=audio_format.upper()) buffer.seek(0) if return_format == "buffer": return buffer elif return_format == "base64": return base64.b64encode(buffer.read()).decode("utf-8") elif return_format == "dict": return { "data": base64.b64encode(buffer.read()).decode("utf-8"), "format": audio_format.lower(), } except Exception as e: raise ValueError(f"Error loading audio: {e}") def conv1d_output_length(module: "torch.nn.Conv1d", input_length: int) -> int: """ Computes the output length of a 1D convolution layer according to torch's documentation: https://docs.pytorch.org/docs/stable/generated/torch.nn.Conv1d.html """ return int( (input_length + 2 * module.padding[0] - module.dilation[0] * (module.kernel_size[0] - 1) - 1) / module.stride[0] + 1 ) def is_valid_audio(audio): return is_numpy_array(audio) or is_torch_tensor(audio) def is_valid_list_of_audio(audio): return audio and all(is_valid_audio(audio_i) for audio_i in audio) def make_list_of_audio( audio: Union[list[AudioInput], AudioInput], ) -> AudioInput: """ Ensure that the output is a list of audio. Args: audio (`Union[list[AudioInput], AudioInput]`): The input audio. Returns: list: A list of audio. """ # If it's a list of audios, it's already in the right format if isinstance(audio, (list, tuple)) and is_valid_list_of_audio(audio): return audio # If it's a single audio, convert it to a list of if is_valid_audio(audio): return [audio] raise ValueError("Invalid input type. Must be a single audio or a list of audio") def hertz_to_mel(freq: Union[float, np.ndarray], mel_scale: str = "htk") -> Union[float, np.ndarray]: """ Convert frequency from hertz to mels. Args: freq (`float` or `np.ndarray`): The frequency, or multiple frequencies, in hertz (Hz). mel_scale (`str`, *optional*, defaults to `"htk"`): The mel frequency scale to use, `"htk"`, `"kaldi"` or `"slaney"`. Returns: `float` or `np.ndarray`: The frequencies on the mel scale. """ if mel_scale not in ["slaney", "htk", "kaldi"]: raise ValueError('mel_scale should be one of "htk", "slaney" or "kaldi".') if mel_scale == "htk": return 2595.0 * np.log10(1.0 + (freq / 700.0)) elif mel_scale == "kaldi": return 1127.0 * np.log(1.0 + (freq / 700.0)) min_log_hertz = 1000.0 min_log_mel = 15.0 logstep = 27.0 / np.log(6.4) mels = 3.0 * freq / 200.0 if isinstance(freq, np.ndarray): log_region = freq >= min_log_hertz mels[log_region] = min_log_mel + np.log(freq[log_region] / min_log_hertz) * logstep elif freq >= min_log_hertz: mels = min_log_mel + np.log(freq / min_log_hertz) * logstep return mels def mel_to_hertz(mels: Union[float, np.ndarray], mel_scale: str = "htk") -> Union[float, np.ndarray]: """ Convert frequency from mels to hertz. Args: mels (`float` or `np.ndarray`): The frequency, or multiple frequencies, in mels. mel_scale (`str`, *optional*, `"htk"`): The mel frequency scale to use, `"htk"`, `"kaldi"` or `"slaney"`. Returns: `float` or `np.ndarray`: The frequencies in hertz. """ if mel_scale not in ["slaney", "htk", "kaldi"]: raise ValueError('mel_scale should be one of "htk", "slaney" or "kaldi".') if mel_scale == "htk": return 700.0 * (np.power(10, mels / 2595.0) - 1.0) elif mel_scale == "kaldi": return 700.0 * (np.exp(mels / 1127.0) - 1.0) min_log_hertz = 1000.0 min_log_mel = 15.0 logstep = np.log(6.4) / 27.0 freq = 200.0 * mels / 3.0 if isinstance(mels, np.ndarray): log_region = mels >= min_log_mel freq[log_region] = min_log_hertz * np.exp(logstep * (mels[log_region] - min_log_mel)) elif mels >= min_log_mel: freq = min_log_hertz * np.exp(logstep * (mels - min_log_mel)) return freq def hertz_to_octave(freq: Union[float, np.ndarray], tuning: float = 0.0, bins_per_octave: int = 12): """ Convert frequency from hertz to fractional octave numbers. Adapted from *librosa*. Args: freq (`float` or `np.ndarray`): The frequency, or multiple frequencies, in hertz (Hz). tuning (`float`, defaults to `0.`): Tuning deviation from the Stuttgart pitch (A440) in (fractional) bins per octave. bins_per_octave (`int`, defaults to `12`): Number of bins per octave. Returns: `float` or `np.ndarray`: The frequencies on the octave scale. """ stuttgart_pitch = 440.0 * 2.0 ** (tuning / bins_per_octave) octave = np.log2(freq / (float(stuttgart_pitch) / 16)) return octave def _create_triangular_filter_bank(fft_freqs: np.ndarray, filter_freqs: np.ndarray) -> np.ndarray: """ Creates a triangular filter bank. Adapted from *torchaudio* and *librosa*. Args: fft_freqs (`np.ndarray` of shape `(num_frequency_bins,)`): Discrete frequencies of the FFT bins in Hz. filter_freqs (`np.ndarray` of shape `(num_mel_filters,)`): Center frequencies of the triangular filters to create, in Hz. Returns: `np.ndarray` of shape `(num_frequency_bins, num_mel_filters)` """ filter_diff = np.diff(filter_freqs) slopes = np.expand_dims(filter_freqs, 0) - np.expand_dims(fft_freqs, 1) down_slopes = -slopes[:, :-2] / filter_diff[:-1] up_slopes = slopes[:, 2:] / filter_diff[1:] return np.maximum(np.zeros(1), np.minimum(down_slopes, up_slopes)) def chroma_filter_bank( num_frequency_bins: int, num_chroma: int, sampling_rate: int, tuning: float = 0.0, power: Optional[float] = 2.0, weighting_parameters: Optional[tuple[float, float]] = (5.0, 2.0), start_at_c_chroma: bool = True, ): """ Creates a chroma filter bank, i.e a linear transformation to project spectrogram bins onto chroma bins. Adapted from *librosa*. Args: num_frequency_bins (`int`): Number of frequencies used to compute the spectrogram (should be the same as in `stft`). num_chroma (`int`): Number of chroma bins (i.e pitch classes). sampling_rate (`float`): Sample rate of the audio waveform. tuning (`float`): Tuning deviation from A440 in fractions of a chroma bin. power (`float`, *optional*, defaults to 2.0): If 12.0, normalizes each column with their L2 norm. If 1.0, normalizes each column with their L1 norm. weighting_parameters (`tuple[float, float]`, *optional*, defaults to `(5., 2.)`): If specified, apply a Gaussian weighting parameterized by the first element of the tuple being the center and the second element being the Gaussian half-width. start_at_c_chroma (`bool`, *optional*, defaults to `True`): If True, the filter bank will start at the 'C' pitch class. Otherwise, it will start at 'A'. Returns: `np.ndarray` of shape `(num_frequency_bins, num_chroma)` """ # Get the FFT bins, not counting the DC component frequencies = np.linspace(0, sampling_rate, num_frequency_bins, endpoint=False)[1:] freq_bins = num_chroma * hertz_to_octave(frequencies, tuning=tuning, bins_per_octave=num_chroma) # make up a value for the 0 Hz bin = 1.5 octaves below bin 1 # (so chroma is 50% rotated from bin 1, and bin width is broad) freq_bins = np.concatenate(([freq_bins[0] - 1.5 * num_chroma], freq_bins)) bins_width = np.concatenate((np.maximum(freq_bins[1:] - freq_bins[:-1], 1.0), [1])) chroma_filters = np.subtract.outer(freq_bins, np.arange(0, num_chroma, dtype="d")).T num_chroma2 = np.round(float(num_chroma) / 2) # Project into range -num_chroma/2 .. num_chroma/2 # add on fixed offset of 10*num_chroma to ensure all values passed to # rem are positive chroma_filters = np.remainder(chroma_filters + num_chroma2 + 10 * num_chroma, num_chroma) - num_chroma2 # Gaussian bumps - 2*D to make them narrower chroma_filters = np.exp(-0.5 * (2 * chroma_filters / np.tile(bins_width, (num_chroma, 1))) ** 2) # normalize each column if power is not None: chroma_filters = chroma_filters / np.sum(chroma_filters**power, axis=0, keepdims=True) ** (1.0 / power) # Maybe apply scaling for fft bins if weighting_parameters is not None: center, half_width = weighting_parameters chroma_filters *= np.tile( np.exp(-0.5 * (((freq_bins / num_chroma - center) / half_width) ** 2)), (num_chroma, 1), ) if start_at_c_chroma: chroma_filters = np.roll(chroma_filters, -3 * (num_chroma // 12), axis=0) # remove aliasing columns, copy to ensure row-contiguity return np.ascontiguousarray(chroma_filters[:, : int(1 + num_frequency_bins / 2)]) def mel_filter_bank( num_frequency_bins: int, num_mel_filters: int, min_frequency: float, max_frequency: float, sampling_rate: int, norm: Optional[str] = None, mel_scale: str = "htk", triangularize_in_mel_space: bool = False, ) -> np.ndarray: """ Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency. Different banks of mel filters were introduced in the literature. The following variations are supported: - MFCC FB-20: introduced in 1980 by Davis and Mermelstein, it assumes a sampling frequency of 10 kHz and a speech bandwidth of `[0, 4600]` Hz. - MFCC FB-24 HTK: from the Cambridge HMM Toolkit (HTK) (1995) uses a filter bank of 24 filters for a speech bandwidth of `[0, 8000]` Hz. This assumes sampling rate ≥ 16 kHz. - MFCC FB-40: from the Auditory Toolbox for MATLAB written by Slaney in 1998, assumes a sampling rate of 16 kHz and speech bandwidth of `[133, 6854]` Hz. This version also includes area normalization. - HFCC-E FB-29 (Human Factor Cepstral Coefficients) of Skowronski and Harris (2004), assumes a sampling rate of 12.5 kHz and speech bandwidth of `[0, 6250]` Hz. This code is adapted from *torchaudio* and *librosa*. Note that the default parameters of torchaudio's `melscale_fbanks` implement the `"htk"` filters while librosa uses the `"slaney"` implementation. Args: num_frequency_bins (`int`): Number of frequency bins (should be the same as `n_fft // 2 + 1` where `n_fft` is the size of the Fourier Transform used to compute the spectrogram). num_mel_filters (`int`): Number of mel filters to generate. min_frequency (`float`): Lowest frequency of interest in Hz. max_frequency (`float`): Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`. sampling_rate (`int`): Sample rate of the audio waveform. norm (`str`, *optional*): If `"slaney"`, divide the triangular mel weights by the width of the mel band (area normalization). mel_scale (`str`, *optional*, defaults to `"htk"`): The mel frequency scale to use, `"htk"`, `"kaldi"` or `"slaney"`. triangularize_in_mel_space (`bool`, *optional*, defaults to `False`): If this option is enabled, the triangular filter is applied in mel space rather than frequency space. This should be set to `true` in order to get the same results as `torchaudio` when computing mel filters. Returns: `np.ndarray` of shape (`num_frequency_bins`, `num_mel_filters`): Triangular filter bank matrix. This is a projection matrix to go from a spectrogram to a mel spectrogram. """ if norm is not None and norm != "slaney": raise ValueError('norm must be one of None or "slaney"') if num_frequency_bins < 2: raise ValueError(f"Require num_frequency_bins: {num_frequency_bins} >= 2") if min_frequency > max_frequency: raise ValueError(f"Require min_frequency: {min_frequency} <= max_frequency: {max_frequency}") # center points of the triangular mel filters mel_min = hertz_to_mel(min_frequency, mel_scale=mel_scale) mel_max = hertz_to_mel(max_frequency, mel_scale=mel_scale) mel_freqs = np.linspace(mel_min, mel_max, num_mel_filters + 2) filter_freqs = mel_to_hertz(mel_freqs, mel_scale=mel_scale) if triangularize_in_mel_space: # frequencies of FFT bins in Hz, but filters triangularized in mel space fft_bin_width = sampling_rate / ((num_frequency_bins - 1) * 2) fft_freqs = hertz_to_mel(fft_bin_width * np.arange(num_frequency_bins), mel_scale=mel_scale) filter_freqs = mel_freqs else: # frequencies of FFT bins in Hz fft_freqs = np.linspace(0, sampling_rate // 2, num_frequency_bins) mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs) if norm is not None and norm == "slaney": # Slaney-style mel is scaled to be approx constant energy per channel enorm = 2.0 / (filter_freqs[2 : num_mel_filters + 2] - filter_freqs[:num_mel_filters]) mel_filters *= np.expand_dims(enorm, 0) if (mel_filters.max(axis=0) == 0.0).any(): warnings.warn( "At least one mel filter has all zero values. " f"The value for `num_mel_filters` ({num_mel_filters}) may be set too high. " f"Or, the value for `num_frequency_bins` ({num_frequency_bins}) may be set too low." ) return mel_filters def optimal_fft_length(window_length: int) -> int: """ Finds the best FFT input size for a given `window_length`. This function takes a given window length and, if not already a power of two, rounds it up to the next power or two. The FFT algorithm works fastest when the length of the input is a power of two, which may be larger than the size of the window or analysis frame. For example, if the window is 400 samples, using an FFT input size of 512 samples is more optimal than an FFT size of 400 samples. Using a larger FFT size does not affect the detected frequencies, it simply gives a higher frequency resolution (i.e. the frequency bins are smaller). """ return 2 ** int(np.ceil(np.log2(window_length))) def window_function( window_length: int, name: str = "hann", periodic: bool = True, frame_length: Optional[int] = None, center: bool = True, ) -> np.ndarray: """ Returns an array containing the specified window. This window is intended to be used with `stft`. The following window types are supported: - `"boxcar"`: a rectangular window - `"hamming"`: the Hamming window - `"hann"`: the Hann window - `"povey"`: the Povey window Args: window_length (`int`): The length of the window in samples. name (`str`, *optional*, defaults to `"hann"`): The name of the window function. periodic (`bool`, *optional*, defaults to `True`): Whether the window is periodic or symmetric. frame_length (`int`, *optional*): The length of the analysis frames in samples. Provide a value for `frame_length` if the window is smaller than the frame length, so that it will be zero-padded. center (`bool`, *optional*, defaults to `True`): Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided. Returns: `np.ndarray` of shape `(window_length,)` or `(frame_length,)` containing the window. """ length = window_length + 1 if periodic else window_length if name == "boxcar": window = np.ones(length) elif name in ["hamming", "hamming_window"]: window = np.hamming(length) elif name in ["hann", "hann_window"]: window = np.hanning(length) elif name == "povey": window = np.power(np.hanning(length), 0.85) else: raise ValueError(f"Unknown window function '{name}'") if periodic: window = window[:-1] if frame_length is None: return window if window_length > frame_length: raise ValueError( f"Length of the window ({window_length}) may not be larger than frame_length ({frame_length})" ) padded_window = np.zeros(frame_length) offset = (frame_length - window_length) // 2 if center else 0 padded_window[offset : offset + window_length] = window return padded_window # TODO This method does not support batching yet as we are mainly focused on inference. def spectrogram( waveform: np.ndarray, window: np.ndarray, frame_length: int, hop_length: int, fft_length: Optional[int] = None, power: Optional[float] = 1.0, center: bool = True, pad_mode: str = "reflect", onesided: bool = True, dither: float = 0.0, preemphasis: Optional[float] = None, mel_filters: Optional[np.ndarray] = None, mel_floor: float = 1e-10, log_mel: Optional[str] = None, reference: float = 1.0, min_value: float = 1e-10, db_range: Optional[float] = None, remove_dc_offset: bool = False, dtype: np.dtype = np.float32, ) -> np.ndarray: """ Calculates a spectrogram over one waveform using the Short-Time Fourier Transform. This function can create the following kinds of spectrograms: - amplitude spectrogram (`power = 1.0`) - power spectrogram (`power = 2.0`) - complex-valued spectrogram (`power = None`) - log spectrogram (use `log_mel` argument) - mel spectrogram (provide `mel_filters`) - log-mel spectrogram (provide `mel_filters` and `log_mel`) How this works: 1. The input waveform is split into frames of size `frame_length` that are partially overlapping by `frame_length - hop_length` samples. 2. Each frame is multiplied by the window and placed into a buffer of size `fft_length`. 3. The DFT is taken of each windowed frame. 4. The results are stacked into a spectrogram. We make a distinction between the following "blocks" of sample data, each of which may have a different lengths: - The analysis frame. This is the size of the time slices that the input waveform is split into. - The window. Each analysis frame is multiplied by the window to avoid spectral leakage. - The FFT input buffer. The length of this determines how many frequency bins are in the spectrogram. In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame. A padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame, typically the next power of two. Note: This function is not optimized for speed yet. It should be mostly compatible with `librosa.stft` and `torchaudio.functional.transforms.Spectrogram`, although it is more flexible due to the different ways spectrograms can be constructed. Args: waveform (`np.ndarray` of shape `(length,)`): The input waveform. This must be a single real-valued, mono waveform. window (`np.ndarray` of shape `(frame_length,)`): The windowing function to apply, including zero-padding if necessary. The actual window length may be shorter than `frame_length`, but we're assuming the array has already been zero-padded. frame_length (`int`): The length of the analysis frames in samples. With librosa this is always equal to `fft_length` but we also allow smaller sizes. hop_length (`int`): The stride between successive analysis frames in samples. fft_length (`int`, *optional*): The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have. For optimal speed, this should be a power of two. If `None`, uses `frame_length`. power (`float`, *optional*, defaults to 1.0): If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `None`, returns complex numbers. center (`bool`, *optional*, defaults to `True`): Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `False`, frame `t` will start at time `t * hop_length`. pad_mode (`str`, *optional*, defaults to `"reflect"`): Padding mode used when `center` is `True`. Possible values are: `"constant"` (pad with zeros), `"edge"` (pad with edge values), `"reflect"` (pads with mirrored values). onesided (`bool`, *optional*, defaults to `True`): If True, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1` frequency bins. If False, also computes the negative frequencies and returns `fft_length` frequency bins. dither (`float`, *optional*, defaults to 0.0): Adds dithering. In other words, adds a small Gaussian noise to each frame. E.g. use 4.0 to add dithering with a normal distribution centered around 0.0 with standard deviation 4.0, 0.0 means no dithering. Dithering has similar effect as `mel_floor`. It reduces the high log_mel_fbank values for signals with hard-zero sections, when VAD cutoff is present in the signal. preemphasis (`float`, *optional*) Coefficient for a low-pass filter that applies pre-emphasis before the DFT. mel_filters (`np.ndarray` of shape `(num_freq_bins, num_mel_filters)`, *optional*): The mel filter bank. If supplied, applies a this filter bank to create a mel spectrogram. mel_floor (`float`, *optional*, defaults to 1e-10): Minimum value of mel frequency banks. log_mel (`str`, *optional*): How to convert the spectrogram to log scale. Possible options are: `None` (don't convert), `"log"` (take the natural logarithm) `"log10"` (take the base-10 logarithm), `"dB"` (convert to decibels). Can only be used when `power` is not `None`. reference (`float`, *optional*, defaults to 1.0): Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero. min_value (`float`, *optional*, defaults to `1e-10`): The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking `log(0)`. For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an amplitude spectrogram, the value `1e-5` corresponds to -100 dB. Must be greater than zero. db_range (`float`, *optional*): Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero. remove_dc_offset (`bool`, *optional*): Subtract mean from waveform on each frame, applied before pre-emphasis. This should be set to `true` in order to get the same results as `torchaudio.compliance.kaldi.fbank` when computing mel filters. dtype (`np.dtype`, *optional*, defaults to `np.float32`): Data type of the spectrogram tensor. If `power` is None, this argument is ignored and the dtype will be `np.complex64`. Returns: `nd.array` containing a spectrogram of shape `(num_frequency_bins, length)` for a regular spectrogram or shape `(num_mel_filters, length)` for a mel spectrogram. """ window_length = len(window) if fft_length is None: fft_length = frame_length if frame_length > fft_length:
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/training_args_seq2seq.py
src/transformers/training_args_seq2seq.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from dataclasses import dataclass, field from pathlib import Path from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings logger = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__) class Seq2SeqTrainingArguments(TrainingArguments): """ Args: predict_with_generate (`bool`, *optional*, defaults to `False`): Whether to use generate to calculate generative metrics (ROUGE, BLEU). generation_max_length (`int`, *optional*): The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default to the `max_length` value of the model configuration. generation_num_beams (`int`, *optional*): The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default to the `num_beams` value of the model configuration. generation_config (`str` or `Path` or [`~generation.GenerationConfig`], *optional*): Allows to load a [`~generation.GenerationConfig`] from the `from_pretrained` method. This can be either: - a string, the *model id* of a pretrained model configuration hosted inside a model repo on huggingface.co. - a path to a *directory* containing a configuration file saved using the [`~GenerationConfig.save_pretrained`] method, e.g., `./my_model_directory/`. - a [`~generation.GenerationConfig`] object. """ sortish_sampler: bool = field(default=False, metadata={"help": "Whether to use SortishSampler or not."}) predict_with_generate: bool = field( default=False, metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) generation_max_length: int | None = field( default=None, metadata={ "help": ( "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `max_length` value of the model configuration." ) }, ) generation_num_beams: int | None = field( default=None, metadata={ "help": ( "The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `num_beams` value of the model configuration." ) }, ) generation_config: str | Path | GenerationConfig | None = field( default=None, metadata={ "help": "Model id, file path or url pointing to a GenerationConfig json file, to use during prediction." }, ) def to_dict(self): """ Serializes this instance while replace `Enum` by their values and `GenerationConfig` by dictionaries (for JSON serialization support). It obfuscates the token values by removing their value. """ # filter out fields that are defined as field(init=False) d = super().to_dict() for k, v in d.items(): if isinstance(v, GenerationConfig): d[k] = v.to_dict() return d
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/core_model_loading.py
src/transformers/core_model_loading.py
# coding=utf-8 # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Core helpers for loading model checkpoints.""" from __future__ import annotations import math import os import re from abc import abstractmethod from collections import defaultdict from collections.abc import Callable, MutableMapping, MutableSet from concurrent.futures import Future, ThreadPoolExecutor from contextlib import contextmanager from copy import deepcopy from dataclasses import dataclass, field from itertools import chain from typing import TYPE_CHECKING, Any, Optional, Union import torch from .integrations.accelerate import get_device, offload_weight from .integrations.tensor_parallel import ALL_PARALLEL_STYLES from .utils import is_env_variable_true, is_torch_greater_or_equal, logging _torch_distributed_available = torch.distributed.is_available() _is_dtensor_available = _torch_distributed_available and is_torch_greater_or_equal("2.5") if _is_dtensor_available: from torch.distributed.tensor import DTensor, Replicate if TYPE_CHECKING: from .integrations.tensor_parallel import TensorParallelLayer from .modeling_utils import PreTrainedModel from .quantizers import HfQuantizer logger = logging.get_logger(__name__) def build_glob_alternation( globs: list[Union[WeightRenaming, WeightConverter, str]], ) -> tuple[re.Pattern, dict[str, str], dict[str, str]]: """ Build a single alternation regex with one named group per glob. """ src_group_to_glob: dict[str, str] = {} tgt_group_to_glob: dict[str, str] = {} branches: list[str] = [] i = 0 for glob in globs: if isinstance(glob, (WeightRenaming, WeightConverter)): for src in glob.source_patterns: group_name = f"g{i}" src_group_to_glob[group_name] = src i += 1 body = src.replace("*", r".*") branches.append(f"(?P<{group_name}>{body})") tgt_group_to_glob[group_name] = glob.target_patterns[0] # we index witht the first target else: group_name = f"g{i}" src_group_to_glob[group_name] = glob i += 1 body = glob body = body.replace("*", r".*") branches.append(f"(?P<{group_name}>{body})") tgt_group_to_glob[group_name] = glob alternation = re.compile("|".join(branches)) return alternation, src_group_to_glob, tgt_group_to_glob class ConversionOps: """Base class for weight conversion operations.""" def __repr__(self): if hasattr(self, "dim"): return f"{self.__class__.__name__}(dim={self.dim})" else: return f"{self.__class__.__name__}" @abstractmethod def convert( self, input_dict: dict[str, Any], source_patterns: list[str], target_patterns: list[str], **kwargs ) -> dict[str, list[torch.Tensor]]: raise NotImplementedError @property def reverse_op(self) -> ConversionOps: raise NotImplementedError class Chunk(ConversionOps): """Split a tensor along ``dim`` into equally sized chunks.""" def __init__(self, dim: int = 0): self.dim = dim @torch.no_grad def convert( self, input_dict: dict[str, torch.Tensor], source_patterns: list[str], target_patterns: list[str], **kwargs ) -> dict[str, torch.Tensor]: tensors = next(iter(input_dict.values())) tensor = tensors[0] if isinstance(tensors, list) else tensors targets = self.get_target_pattern(input_dict, target_patterns) sizes = len(targets) chunks = torch.chunk(tensor, sizes, dim=self.dim) return dict(zip(targets, chunks)) def get_target_pattern(self, input_dict: dict, target_patterns: list[str]) -> list[str]: # Here we always return the target patterns if len(input_dict) > 1 or len(target_patterns) == 1: raise ValueError("Undefined Operation encountered!") return target_patterns @property def reverse_op(self) -> ConversionOps: return Concatenate(self.dim) class Concatenate(ConversionOps): """Concatenate tensors along `dim`.""" def __init__(self, dim: int = 0): self.dim = dim @torch.no_grad def convert( self, input_dict: dict[str, list[torch.Tensor]], source_patterns: list[str], target_patterns: list[str], **kwargs, ) -> dict[str, torch.Tensor]: target_pattern = self.get_target_pattern(target_patterns) all_tensors = [] # Very important to keep the relative order of the source patterms here, so we iterate over them not the # input directly as it's unordered! for source_pattern in source_patterns: tensors = input_dict[source_pattern] if isinstance(tensors, list): all_tensors.extend(tensors) else: all_tensors.append(tensors) return {target_pattern: torch.cat(all_tensors, dim=self.dim)} def get_target_pattern(self, target_patterns: list[str]) -> str: # Here we always return the target pattern if len(target_patterns) > 1: raise ValueError("Undefined Operation encountered!") return target_patterns[0] @property def reverse_op(self) -> ConversionOps: return Chunk(self.dim) class MergeModulelist(ConversionOps): """ Merge a list of tensors into a single tensor along the first dimension. We explicitly define this because for EP or TP you want to make sure you know what you are doing! """ def __init__(self, dim: int = 0): self.dim = dim @torch.no_grad def convert( self, input_dict: dict[str, list[torch.Tensor]], source_patterns: list[str], target_patterns: list[str], **kwargs, ) -> dict[str, torch.Tensor]: merged: dict[str, torch.Tensor] = {} for source_pattern, tensors in input_dict.items(): target_pattern = self.get_target_pattern(input_dict, source_pattern, target_patterns) merged[target_pattern] = torch.stack(tensors, dim=self.dim) return merged def get_target_pattern(self, input_dict: dict, source_pattern: str, target_patterns: list[str]) -> str: # Here it's a single operation, so we use the target if len(input_dict) == 1: if len(target_patterns) == 1: return target_patterns[0] else: raise ValueError("Undefined Operation encountered!") # Here it's the first operation in a chain, so we use the source as they were replaced before in the chain else: return source_pattern @property def reverse_op(self) -> ConversionOps: return SplitModulelist(self.dim) class SplitModulelist(ConversionOps): """Inverse of :class:`MergeModulelist` using explicit split sizes per group.""" def __init__(self, dim: int = 0): self.dim = dim @torch.no_grad def convert( self, input_dict: dict[str, torch.Tensor], source_patterns: list[str], target_patterns: list[str], **kwargs ) -> dict[str, torch.Tensor]: all_tensors = {} for source_pattern, tensors in input_dict.items(): tensor = tensors[0] if isinstance(tensors, list) else tensors # We split in the number of tensors present in the given dim sizes = tensor.size(self.dim) targets = self.get_target_patterns(input_dict, source_pattern, target_patterns, sizes) chunks = torch.chunk(tensor, sizes, dim=self.dim) # We squeeze each chunk here as well to make sure to give them their original shape all_tensors.update({target: chunk.squeeze() for target, chunk in zip(targets, chunks)}) return all_tensors def get_target_patterns( self, input_dict: dict, source_pattern: str, target_patterns: list[str], sizes: int ) -> list[str]: # Here it's a single operation, so we use the target if len(input_dict) == 1: if len(target_patterns) == 1: return [target_patterns[0].replace("*", f"{i}") for i in range(sizes)] else: raise ValueError("Undefined Operation encountered!") # Here it's the last operation in a chain, so we use the source as they were replaced before in the chain else: return [source_pattern.replace("*", f"{i}") for i in range(sizes)] @property def reverse_op(self) -> ConversionOps: return MergeModulelist(self.dim) class PermuteForRope(ConversionOps): """ Applies the permutation required to convert complex RoPE weights to the split sin/cos format. """ def __init__(self): pass def _apply(self, tensor: torch.Tensor) -> torch.Tensor: dim1, dim2 = tensor.shape n_heads = self.config.getattr("num_attention_heads", 1) tensor = tensor.view(n_heads, dim1 // n_heads // 2, 2, dim2) tensor = tensor.transpose(1, 2).reshape(dim1, dim2) return tensor @torch.no_grad def convert( self, input_dict: dict[str, list[torch.Tensor]], source_patterns: list[str], target_patterns: list[str], config, **kwargs, ) -> dict[str, list[torch.Tensor]]: self.config = config output: dict[str, list[torch.Tensor]] = {} for key, tensors in input_dict.items(): if len(tensors) != 1: raise ValueError("PermuteForRope expects a single tensor per key.") output[key] = [self._apply(tensors[0])] return output class ErnieFuseAndSplitTextVisionExperts(ConversionOps): r""" Special operation that splits a module list over all keys and fuses over the number of original modules. Example with 2 original modules "Gate" and "Up" with 2 target keys "Text" and "Vision": ModuleList 1 ModuleList 2 [ Gate ] [ Up ] | | | | [Gate_Text] [Gate_Vision] [Up_Text] [Up_Vision] \ \ / / \ \ / / \ / \ / \ / \ / [GateUp_Text] [GateUp_Vision] The splits are equal and are defined by the amount of target keys. The final fusions are defined by the amount of original module lists. """ def __init__(self, stack_dim: int = 0, concat_dim: int = 1): self.stack_dim = stack_dim self.concat_dim = concat_dim def split_list_into_chunks(self, tensor_list: list[torch.Tensor], chunks: int = 2): split_size = math.ceil(len(tensor_list) / chunks) # best effort split size return [tensor_list[i * split_size : (i + 1) * split_size] for i in range(chunks)] @torch.no_grad() def convert( self, input_dict: dict[str, list[torch.Tensor]], source_patterns: list[str], target_patterns: list[str], config, **kwargs, ) -> dict[str, list[torch.Tensor]]: valid_keys = input_dict.keys() split_and_fused = defaultdict(list) for key in source_patterns: if key not in valid_keys: raise ValueError( f"Expected pattern {key} in collected tensors but only found tensors for: {valid_keys}" ) tensors = input_dict.get(key, []) split_tensor_lists = self.split_list_into_chunks(tensors, chunks=len(target_patterns)) stacked_tensors = (torch.stack(tensor_group, dim=self.stack_dim) for tensor_group in split_tensor_lists) for idx, tensor_group in enumerate(stacked_tensors): split_and_fused[target_patterns[idx]].append(tensor_group) for k, v in split_and_fused.items(): split_and_fused[k] = torch.cat(v, dim=self.concat_dim) return split_and_fused @property def reverse_op(self) -> ConversionOps: return ErnieSplitAndDecoupleTextVisionExperts(stack_dim=self.stack_dim, concat_dim=self.concat_dim) class ErnieSplitAndDecoupleTextVisionExperts(ConversionOps): r""" Special operation that splits a fused module list over all original modules and then decouples them into a mixed module list each over all keys. Example with 2 original modules "Gate" and "Up" with 2 target keys "Text" and "Vision": [GateUp_Text] [GateUp_Vision] / \ / \ / \ / \ / / \ \ / / \ \ [Gate_Text] [Gate_Vision] [Up_Text] [Up_Vision] | | | | [ Gate ] [ Up ] ModuleList 1 ModuleList 2 The splits are equal and are defined by the amount of original module lists. The final decoupled module lists are defined by the amount of keys. """ def __init__(self, stack_dim: int = 0, concat_dim: int = 1): self.stack_dim = stack_dim self.concat_dim = concat_dim @torch.no_grad() def convert( self, input_dict: dict[str, list[torch.Tensor]], source_patterns: list[str], target_patterns: list[str], config, **kwargs, ) -> dict[str, list[torch.Tensor]]: fused_modules = len(target_patterns) valid_keys = input_dict.keys() split_tensors = [] for key in source_patterns: if key not in valid_keys: raise ValueError( f"Expected pattern {key} in collected tensors but only found tensors for: {valid_keys}" ) # Assuming that we get single sized lists here to index with 0 split_tensors.append(input_dict[key][0].chunk(fused_modules, dim=self.concat_dim)) decoupled = {} for idx, key in enumerate(target_patterns): tensor_groups = [ list(torch.unbind(tensor_group[idx], dim=self.stack_dim)) for tensor_group in split_tensors ] tensor_list = list(chain.from_iterable(tensor_groups)) targets = [key.replace("*", f"{i}") for i in range(len(tensor_list))] decoupled |= dict(zip(targets, tensor_list)) return decoupled @property def reverse_op(self) -> ConversionOps: return ErnieFuseAndSplitTextVisionExperts(stack_dim=self.stack_dim, concat_dim=self.concat_dim) class Transpose(ConversionOps): """ Transposes the given tensor along dim0 and dim1. """ def __init__(self, dim0: int = 0, dim1: int = 1): self.dim0 = dim0 self.dim1 = dim1 @torch.no_grad() def convert( self, input_dict: dict[str, list[torch.Tensor]], source_patterns: list[str], target_patterns: list[str], config, **kwargs, ) -> dict[str, list[torch.Tensor]]: if len(input_dict) != len(target_patterns): raise ValueError( f"Transpose conversion can only happen on each key ({len(input_dict)}) " f"and should match exact one target ({len(target_patterns)})." ) output: dict[str, list[torch.Tensor]] = {} for key, target_pattern in zip(input_dict.keys(), target_patterns): tensor = input_dict.get(key, []) if len(tensor) != 1: raise ValueError(f"Transpose conversion requires exactly one tensor, found {len(tensor)}.") output[target_pattern] = torch.transpose(tensor[0], dim0=self.dim0, dim1=self.dim1) return output @property def reverse_op(self) -> ConversionOps: return Transpose(dim0=self.dim1, dim1=self.dim0) @dataclass(slots=True) class WeightTransform: source_patterns: Union[str, list[str]] = field(init=True) target_patterns: Union[str, list[str]] = field(init=True) compiled_sources: re.Pattern = field(init=False) distributed_operation: Optional[TensorParallelLayer] = None quantization_operation: Optional[ConversionOps] = None collected_tensors: dict[str, list[Future]] = field(default_factory=lambda: defaultdict(list), init=False) layer_targets: dict[str, set[str]] = field(default_factory=lambda: defaultdict(set), init=False) def __post_init__(self): if isinstance(self.source_patterns, str): self.source_patterns = [self.source_patterns] if isinstance(self.target_patterns, str): self.target_patterns = [self.target_patterns] # Due to how our `_checkpoint_conversion_mapping` mappings are written, we need a few exceptions here # when instantiating the reverse mapping (i.e. the targets become sources, and sources become targets) # The issues lie in the sources usually, so here we need to check the targets for the reversed mapping for i, pattern in enumerate(self.target_patterns): # Some mapping contains `^` to notify start of string when matching -> remove it during reverse mapping pattern = pattern.removeprefix("^") # Some mapping contains `$` to notify end of string when matching -> remove it during reverse mapping pattern = pattern.removesuffix("$") # Remove negative lookahead/behind if any. This is ugly but needed for reverse mapping of # Qwen2.5, Sam3, Ernie4.5 VL MoE! pattern = re.sub(r"\(\?.+\)", "", pattern) # Allow capturing groups in patterns, i.e. to add/remove a prefix to all keys (e.g. timm_wrapper, sam3) if r"(.+)" in pattern: pattern = pattern.replace(r"(.+)", r"\1") self.target_patterns[i] = pattern # We also need to check capturing groups in the sources during reverse mapping (e.g. timm_wrapper, sam3) for i, pattern in enumerate(self.source_patterns): if r"\1" in pattern: pattern = pattern.replace(r"\1", r"(.+)") self.source_patterns[i] = pattern # Construct the regex we will use to rename keys from the sources to the targets branches = [] for i, source_pattern in enumerate(self.source_patterns): group_name = f"g{i}" pattern = source_pattern.replace(".*.", r"\..*\.") branches.append(f"(?P<{group_name}>{pattern})") self.compiled_sources = re.compile("|".join(branches)) def add_tensor(self, target_key: str, source_key: str, source_pattern: str, future: Future): self.collected_tensors[source_pattern].append(future) self.layer_targets[target_key].add(source_key) def rename_source_key(self, source_key: str) -> tuple[str, str | None]: """ Return a tuple (renamed_key, source_pattern_producing_the_match). Try renaming `source_key` according to the source and target patterns of the current WeightTransform. In case of a one-to-many transform, i.e. we have several target patterns, the matching source pattern will be replaced by the first of all the target patterns (they are then correctly expanded in the Operations). """ # Try matching one of the alternation branches match_object = self.compiled_sources.search(source_key) if match_object is None: return source_key, None # Find the source that produced the match (it's the first group that matched, as the search stops after first branch match) matching_group_name = next(name for name, val in match_object.groupdict().items() if val is not None) source_pattern_that_matched = self.source_patterns[int(matching_group_name[1:])] # If we matched, we always replace with the first target pattern, in case we have several (one to many transform) replacement = self.target_patterns[0] # Allow capturing groups in patterns, i.e. to add a prefix to all keys (e.g. timm_wrapper, sam3) if r"\1" in replacement: # The index of the internal group we need to replace is the index of the matched named group as it comes # inside that matched named group replaced_group_idx = self.compiled_sources.groupindex[matching_group_name] + 1 replacement = replacement.replace(r"\1", match_object.group(replaced_group_idx)) renamed_key = source_key.replace(match_object.group(0), replacement) return renamed_key, source_pattern_that_matched def reverse_transform(self) -> WeightTransform: """Reverse the current `WeightTransform` instance, to be able to save with the opposite weight transformations.""" # TODO: check this and relax when quantizer have `reverse_op` if self.quantization_operation is not None: raise ValueError("Cannot reverse the transform with TP or quantization") kwargs = {} # Add the reverse ops if applicable (it needs to be provided at __init__) if hasattr(self, "operations"): # All reverse ops, in reverse order kwargs["operations"] = [op.reverse_op for op in self.operations[::-1]] reverse_transform = self.__class__( source_patterns=self.target_patterns, target_patterns=self.source_patterns, **kwargs ) return reverse_transform def materialize_tensors(self) -> dict[str, list[torch.Tensor]]: """ Materialize all the tensors that were saved in `self.collected_tensors`. This function removes them from the internal attribute to avoid keeping them in memory during the different `self.convert` operations, and return a new dictionary (otherwise we use more memory than needed during loading). We basically have 3 cases here: - async loading (default): the tensors are Future instances that we need to wait for - sync loading: the tensors are Callable, we need to call the Callable to actually load them from disk - saving: the tensors are already torch.Tensor instances (the existing model weights) """ collected_tensors = {} for key in set(self.collected_tensors.keys()): # Remove from internal attribute tensors = self.collected_tensors.pop(key) # Async loading if isinstance(tensors[0], Future): tensors = [future.result() for future in tensors] # Sync loading elif callable(tensors[0]): tensors = [func() for func in tensors] # Add them to the new dictionary collected_tensors[key] = tensors return collected_tensors @dataclass(slots=True) class WeightRenaming(WeightTransform): # Special case of WeightTransform that only renames keys without any conversion. def convert( self, layer_name: str, model=None, config=None, hf_quantizer=None, missing_keys: Optional[MutableSet[str]] = None, conversion_errors: Optional[MutableMapping[str, str]] = None, ): # Collect the tensors here - we use a new dictionary to avoid keeping them in memory in the internal # attribute during the whole process collected_tensors = self.materialize_tensors() # Perform renaming op (for a simple WeightRenaming, `self.source_patterns` and `self.target_patterns` can # only be of length 1, and are actually the full key names - we also have only 1 single related tensor) target_key = self.target_patterns[0] collected_tensors = {target_key: collected_tensors[self.source_patterns[0]]} if hf_quantizer is not None and self.quantization_operation is not None: with log_conversion_errors( layer_name, conversion_errors, (len(collected_tensors), layer_name), self.quantization_operation ): collected_tensors = self.quantization_operation.convert( collected_tensors, source_patterns=self.source_patterns, target_patterns=self.target_patterns, full_layer_name=target_key, model=model, config=config, missing_keys=missing_keys, ) return collected_tensors, conversion_errors # List of classes that are known to be able to use m:n _INTERNAL_MANY_TO_MANY_CONVERSIONS = ( ErnieFuseAndSplitTextVisionExperts, ErnieSplitAndDecoupleTextVisionExperts, ) @dataclass(slots=True) class WeightConverter(WeightTransform): operations: list[ConversionOps] = field(default_factory=list, repr=False) def __post_init__(self): WeightTransform.__post_init__(self) if bool(len(self.source_patterns) - 1) + bool(len(self.target_patterns) - 1) >= 2: # We allow many-to-many only if we use an internal operation that can handle it if not any(isinstance(op, _INTERNAL_MANY_TO_MANY_CONVERSIONS) for op in self.operations): raise ValueError( f"source keys={self.source_patterns}, target_patterns={self.target_patterns} but you can only have one to many, one to one or many to one." ) if not self.operations: raise ValueError("WeightConverter requires at least one operation.") def convert( self, layer_name: str, model=None, config=None, hf_quantizer=None, missing_keys: Optional[MutableSet[str]] = None, conversion_errors: Optional[MutableMapping[str, str]] = None, ): # Collect the tensors here - we use a new dictionary to avoid keeping them in memory in the internal # attribute during the whole process collected_tensors = self.materialize_tensors() for op in self.operations: with log_conversion_errors(layer_name, conversion_errors, (len(collected_tensors), layer_name), op): collected_tensors = op.convert( collected_tensors, source_patterns=self.source_patterns, target_patterns=self.target_patterns, # Additional kwargs, ususally not used full_layer_name=layer_name, model=model, config=config, missing_keys=missing_keys, ) # Tensors are returned from ops with the target patterns, we need to expand them to full name. # This means we need to grab the prefix and suffix to add to every target key full_name = layer_name if ".*." in layer_name: full_name = layer_name.replace(".*.", ".0.") try: prefix, _, suffix = next(full_name.partition(k) for k in collected_tensors.keys() if k in full_name) # Rename the tensors collected_tensors = {prefix + k + suffix: v for k, v in collected_tensors.items()} # some quantizers need to already rename in `convert` as they cannot only rely on prefix and suffix except StopIteration: pass if hf_quantizer is not None and self.quantization_operation is not None: with log_conversion_errors( layer_name, conversion_errors, (len(collected_tensors), layer_name), self.quantization_operation ): collected_tensors = self.quantization_operation.convert( collected_tensors, source_patterns=self.source_patterns, target_patterns=self.target_patterns, full_layer_name=layer_name, config=config, model=model, missing_keys=missing_keys, ) return collected_tensors, conversion_errors # For I/O bound operations (i.e. here reading files), it is better to have fewer threads, e.g. 4 is a good default. # Having too many is actually harming performances quite a lot, i.e. using 16 can sometimes lead to taking TWICE # as much time to load the same model GLOBAL_WORKERS = min(4, os.cpu_count() or 4) def _materialize_copy(tensor: torch.Tensor, device=None, dtype=None) -> torch.Tensor: # This slicing is what actually loads the tensor from the safetensors slice object tensor = tensor[...] if dtype is not None or device is not None: tensor = tensor.to(device=device, dtype=dtype) return tensor def spawn_materialize( thread_pool: ThreadPoolExecutor | None, tensor: torch.Tensor, device=None, dtype=None ) -> Future | Callable: """Materialize a tensor from file asynchronously if `thread_pool` is provided, or return a Callable that will load the tensor synchronously when called.""" def _job(): return _materialize_copy(tensor, device, dtype) if thread_pool is not None: return thread_pool.submit(_job) else: # Return the Callable here, not the Tensor itself, so we actually delay loading to avoid saturating cpu # memory during Conversion return _job def spawn_tp_materialize( thread_pool: ThreadPoolExecutor | None, tensor: torch.Tensor, sharding_method, tensor_idx, device=None, dtype=None ) -> Future | Callable: """Materialize and shard a tensor (according to the TP-plan) from file asynchronously if `thread_pool` is provided, or return a Callable that will load the tensor synchronously when called.""" def _job(): return sharding_method.shard_tensor(tensor, tensor_idx=tensor_idx, device=device, dtype=dtype) if thread_pool is not None: return thread_pool.submit(_job) else: # Return the Callable here, not the Tensor itself, so we actually delay loading to avoid saturating cpu # memory during Conversion return _job def dot_natural_key(s: str): parts = s.split(".") for i, p in enumerate(parts): # whole-segment digits -> int; otherwise leave as str if p.isdigit(): parts[i] = int(p) return parts @contextmanager def log_conversion_errors( first_target_key: str, conversion_errors: MutableMapping[str, str], extras: Any = None, op: Union[list[ConversionOps], ConversionOps, None] = None, ): """Catch all exceptions during `convert` calls, and log the errors for later. Re-raise a `SkipParameters` exception that will be catched later to skip the parameters that raised the original Exception.""" try: yield except Exception as e: def _format_op_name(curr_op: Union[list[ConversionOps], ConversionOps, None]) -> Optional[str]: if curr_op is None: return None if isinstance(curr_op, (list, tuple, set)): names = [o.__class__.__name__ for o in curr_op if o is not None] if not names: return None return ", ".join(names) return curr_op.__class__.__name__ op_name = _format_op_name(op) if isinstance(extras, tuple) and len(extras) == 2: length, target_keys = extras descriptor = f"{op_name} " if op_name else "" conversion_errors[first_target_key] = ( f"{e}\nError: {descriptor}on tensors destined for {target_keys}. Ckpt contains: {length}" ) elif isinstance(extras, str): suffix = f" via {op_name}" if op_name else "" conversion_errors[first_target_key] = f"{e}\nError{suffix} when processing parameter {extras}" elif extras is None and op_name: conversion_errors[first_target_key] = f"{op_name}: {e}" else: conversion_errors[first_target_key] = f"{extras} |Error: {e}" # Raise a specific Exception that we can catch easily raise SkipParameters() def set_param_for_module( model: PreTrainedModel, target_name: str,
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/model_debugging_utils.py
src/transformers/model_debugging_utils.py
# Copyright 2025 The HuggingFace Inc. team. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools import json import os import re from contextlib import contextmanager, redirect_stdout from io import StringIO from typing import Optional from .utils import logging from .utils.import_utils import is_torch_available, requires if is_torch_available(): import torch from safetensors.torch import save_file _torch_distributed_available = False # Note to code inspectors: this toolbox is intended for people who add models to `transformers`. if torch.distributed.is_available(): import torch.distributed.tensor _torch_distributed_available = True else: _torch_distributed_available = False logger = logging.get_logger(__name__) def _is_rank_zero(): """Return True if rank=0 or we aren't running distributed.""" if not (_torch_distributed_available and torch.distributed.is_initialized()): return True return torch.distributed.get_rank() == 0 MEMORY_ADDRESS_REGEX = re.compile(r"object at 0x[0-9A-Fa-f]+") def _sanitize_repr_for_diff(x_str: str) -> str: """ Replace memory addresses in an object's repr with a stable placeholder so that beautiful JSON diffs won't be ruined by ephemeral addresses. """ return MEMORY_ADDRESS_REGEX.sub("object at 0xXXXXXXXX", x_str) def _dtensor_repr(x): """Return a stable string representation for a DTensor-like object.""" if _is_rank_zero(): return f"DTensor (rank0) -> {repr(x._local_tensor)}" return "DTensor(non-rank0)" def _serialize_tensor_like_io( value, debug_path: Optional[str] = None, use_repr: bool = True, path_to_value: Optional[str] = None ): """ Converts Tensors and DTensors to a JSON-serializable dictionary representation. Args: value: Any Python object, often including torch Tensors, lists, dicts, etc. debug_path (`str`, *optional*, defaults to `None`): Directory to dump debug JSON and SafeTensors files. use_repr (bool, *optional*, defaults to `True`): Whether to save a `repr()`-ized version of the tensor as the `value` property in the asscoiated FULL_TENSORS.json file, or to store the full tensors in separate SafeTensors file and store the relative path to that file in the `value` property in the dictionary. path_to_value (`str`, *optional*, defaults to `None`): The file name for the SafeTensors file holding the full tensor value if `use_repr=False`. Returns: A nested Python structure (list, dict, or sanitized string) that is safe to json.dump. """ torch.set_printoptions(sci_mode=True) if use_repr: value_out = _repr_to_list(value) elif path_to_value: if not path_to_value.endswith(".safetensors"): path_to_value += ".safetensors" filepath = os.path.join(debug_path, path_to_value) if debug_path else path_to_value save_file({"data": value.contiguous().detach().cpu()}, filepath) value_out = f"./{path_to_value}" else: raise ValueError(f"{use_repr=} and {path_to_value=} cannot both be falsy.") out = { "shape": repr(value.shape), "dtype": repr(value.dtype), "value": value_out, } if value.dtype in {torch.float16, torch.float32, torch.bfloat16}: out.update( { "mean": _sanitize_repr_for_diff(repr(value.mean())), "std": _sanitize_repr_for_diff(repr(value.std())), "min": _sanitize_repr_for_diff(repr(value.min())), "max": _sanitize_repr_for_diff(repr(value.max())), } ) return out def _serialize_io(value, debug_path: Optional[str] = None, use_repr: bool = True, path_to_value: Optional[str] = None): """ Recursively build a JSON-serializable Python structure from `value`. Tensors and DTensors become either sanitized repr strings, or are saved to disk as SafeTensors files and their relative paths are recorded in the returned Python structure. Lists/tuples/dicts are recursed into. All memory addresses are replaced with a stable placeholder. Args: value: Any Python object, often including torch Tensors, lists, dicts, etc. debug_path (`str`, *optional*, defaults to `None`): Directory to dump debug JSON and SafeTensors files. use_repr (bool, *optional*, defaults to `True`): Whether to save a `repr()`-ized version of the tensors as the `value` property in the asscoiated FULL_TENSORS.json file, or to store full tensors in separate SafeTensors files and store the relative path to that file in the `value` property. path_to_value (`str`, *optional*, defaults to `None`): The file name for the SafeTensors file holding the full tensor value if `use_repr=False`. Returns: A nested Python structure (list, dict, or sanitized string) that is safe to json.dump. """ if isinstance(value, (list, tuple)): return [ _serialize_io(v, debug_path=debug_path, use_repr=use_repr, path_to_value=f"{path_to_value}_{i}") for i, v in enumerate(value) ] if isinstance(value, dict): return { k: _serialize_io(v, debug_path=debug_path, use_repr=use_repr, path_to_value=f"{path_to_value}_{k}") for k, v in value.items() } if hasattr(value, "_local_tensor"): return _serialize_tensor_like_io( value._local_tensor, debug_path=debug_path, use_repr=use_repr, path_to_value=path_to_value ) if isinstance(value, torch.Tensor): return _serialize_tensor_like_io(value, debug_path=debug_path, use_repr=use_repr, path_to_value=path_to_value) return _sanitize_repr_for_diff(repr(value)) def _repr_to_list(value: torch.Tensor): """ Converts a tensor into a sanitized multi-line string representation. Args: value (`torch.Tensor`): The tensor to represent. Returns: `list[str]`: List of string lines representing the tensor. """ torch.set_printoptions(sci_mode=True, linewidth=120) with StringIO() as buf, redirect_stdout(buf): print(value) # to redirected stdout to avoid line splits raw = buf.getvalue() return _sanitize_repr_for_diff(raw).splitlines() def prune_outputs_if_children(node): # if there are children, remove this node's "outputs" # so we only see outputs at the leaf level if node.get("children"): node.pop("outputs", None) for child in node["children"]: prune_outputs_if_children(child) LAYER_SUFFIX_RE = re.compile(r"(.*)\.(\d+)$") # should be generic enough, ends with a number def is_layer_block(node): """ Checks whether a node represents a layer block with submodules. Args: node (`dict`): A node from the call tree. Returns: `bool`: Whether the node is a layer block. """ match = LAYER_SUFFIX_RE.match(node.get("module_path", "")) if not match or not node.get("children"): return False number = match.group(2) return any(f".{number}." in child.get("module_path", "") for child in node["children"]) def prune_intermediate_layers(node): """ Recursively removes intermediate layers from the tree to improve readability. Keeps at least the first and last layers if many consecutive layers are present. Args: node (`dict`): The root or subnode to prune recursively. """ if not node.get("children"): return layer_blocks = [(i, child) for i, child in enumerate(node["children"]) if is_layer_block(child)] if len(layer_blocks) > 2: to_remove = [i for i, _ in layer_blocks[1:-1]] node["children"] = [child for i, child in enumerate(node["children"]) if i not in to_remove] for child in node["children"]: prune_intermediate_layers(child) def log_model_debug_trace(debug_path: Optional[str], model): if debug_path: try: os.makedirs(debug_path, exist_ok=True) base = os.path.join(debug_path, model._debugger_module_dump_name + "_debug_tree") except Exception as e: raise ValueError(f"Unexpected or existing debug_path={debug_path}.") from e else: base = model._debugger_module_dump_name + "_debug_tree" logger.info(f"Writing model trace at {base}.json") full_path = base + "_FULL_TENSORS.json" summary_path = base + "_SUMMARY.json" prune_outputs_if_children(model._call_tree) with open(full_path, "w") as f: json.dump(model._call_tree, f, indent=2) # summary-only version for readability - traversing the tree again #TODO optimize? def strip_values(node): def clean(val): if isinstance(val, dict): val.pop("value", None) for v in val.values(): clean(v) elif isinstance(val, list): for item in val: clean(item) clean(node.get("inputs", {})) clean(node.get("outputs", {})) for child in node.get("children", []): strip_values(child) tree_copy = json.loads(json.dumps(model._call_tree)) # deep copy strip_values(tree_copy) with open(summary_path, "w") as f: json.dump(tree_copy, f, indent=2) def _attach_debugger_logic( model, debug_path: str = ".", do_prune_layers: bool = True, use_repr: bool = True, ): """ Attaches a debugging wrapper to every module in the model. This records structured inputs and outputs during the forward pass into a call tree. Args: model (`PreTrainedModel`, `nn.Module`): Model to wrap. debug_path (`str`): Optional directory to dump debug JSON files. do_prune_layers (`bool`, *optional*, defaults to `True`): Whether to prune intermediate layers. use_repr (bool, *optional*, defaults to `True`): Whether to save a `repr()`-ized version of the tensors as the `value` property in the associated FULL_TENSORS.json file, or to store full tensors in separate SafeTensors files and store the relative path to that file in the `value` property. """ class_name = model.__class__.__name__ # Prepare data structures on the model object model._call_tree = {"module_path": class_name, "inputs": None, "outputs": None, "children": []} model._debugger_model_call_stack = [] model._debugger_module_dump_name = class_name # used for final JSON filename if debug_path: try: os.makedirs(debug_path, exist_ok=True) except Exception as e: raise ValueError(f"Unexpected or existing debug_path={debug_path}.") from e def wrap_forward(module, full_path): orig_forward = module.forward @functools.wraps(orig_forward) def wrapped_forward(*inps, **kws): if _is_rank_zero(): dict_inputs = {"args": inps, "kwargs": kws} dict_inputs = {k: dict_inputs[k] for k in dict_inputs if len(dict_inputs[k]) > 0} node = { "module_path": full_path, "inputs": _serialize_io( dict_inputs, debug_path=debug_path, use_repr=use_repr, path_to_value=f"{full_path}_inputs", ), "outputs": None, "children": [], } model._debugger_model_call_stack.append(node) with torch.no_grad(): out = orig_forward(*inps, **kws) if _is_rank_zero(): if sum(1 for _ in module.named_children()) > 0: node["outputs"] = None else: node["outputs"] = _serialize_io( out, debug_path=debug_path, use_repr=use_repr, path_to_value=f"{full_path}_outputs", ) finished = model._debugger_model_call_stack.pop() # prune empty vertices here as well (mostly empty children nodes) if not finished["children"]: finished.pop("children") if model._debugger_model_call_stack: model._debugger_model_call_stack[-1]["children"].append(finished) return out module.forward = wrapped_forward # wrap all submodules for name, submodule in model.named_modules(): if name == "": continue wrap_forward(submodule, f"{class_name}.{name}") # wrap top-level forward real_top_forward = model.forward @functools.wraps(real_top_forward) def top_wrapped_forward(*inps, **kws): if _is_rank_zero(): top_node = { "module_path": f"{class_name} (top-level)", "inputs": _serialize_io( {"args": inps, "kwargs": kws}, debug_path=debug_path, use_repr=use_repr, path_to_value=f"{class_name}_inputs", ), "outputs": None, "children": [], } model._debugger_model_call_stack.append(top_node) out = real_top_forward(*inps, **kws) if _is_rank_zero() and model._debugger_model_call_stack: top_node["outputs"] = _serialize_io( out, debug_path=debug_path, use_repr=use_repr, path_to_value=f"{class_name}_outputs", ) finished = model._debugger_model_call_stack.pop() model._call_tree["inputs"] = finished["inputs"] model._call_tree["outputs"] = finished["outputs"] model._call_tree["children"] = finished["children"] # prune empty stuff for visibility [model._call_tree.pop(k, None) for k in list(model._call_tree.keys()) if not model._call_tree[k]] # prune layers that are not 0 or last if do_prune_layers: prune_intermediate_layers(model._call_tree) # Write final JSON trace here log_model_debug_trace(debug_path=debug_path, model=model) return out model.forward = top_wrapped_forward @requires(backends=("torch",)) @contextmanager def model_addition_debugger_context( model, debug_path: Optional[str] = None, do_prune_layers: bool = True, use_repr: bool = True, ): """ # Model addition debugger - context manager for model adders This context manager is a power user tool intended for model adders. It tracks all forward calls within a model forward and logs a slice of each input and output on a nested JSON file. If `use_repr=True` (the default), the JSON file will record a `repr()`-ized version of the tensors as a list of strings. If `use_repr=False`, the full tensors will be stored in separate SafeTensors files and the JSON file will provide a relative path to that file. To note, this context manager enforces `torch.no_grad()`. ## Usage add the context manager to a model to debug ```python import torch from PIL import Image from transformers import LlavaProcessor, LlavaForConditionalGeneration, model_addition_debugger_context torch.random.manual_seed(673) # load pretrained model and processor model_id = "llava-hf/llava-1.5-7b-hf" processor = LlavaProcessor.from_pretrained(model_id) model = LlavaForConditionalGeneration.from_pretrained(model_id) # create random image input random_image = Image.fromarray(torch.randint(0, 256, (224, 224, 3), dtype=torch.uint8).numpy()) # prompt prompt = "<image>Describe this image." # process inputs inputs = processor(text=prompt, images=random_image, return_tensors="pt") # call forward method (not .generate!) with model_addition_debugger_context(model, debug_path="Your_debug_path", do_prune_layers=False): output = model.forward(**inputs) ``` """ orig_forwards = {m: m.forward for _, m in model.named_modules()} orig_forwards[model] = model.forward _attach_debugger_logic(model, debug_path, do_prune_layers, use_repr) try: yield model finally: for module_instance, forward_method in orig_forwards.items(): module_instance.forward = forward_method
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/trainer_seq2seq.py
src/transformers/trainer_seq2seq.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import contextlib from collections.abc import Callable from copy import deepcopy from pathlib import Path from typing import TYPE_CHECKING, Any, Optional, Union import torch from torch import nn from torch.distributed.fsdp import FullyShardedDataParallel from torch.utils.data import Dataset from .generation.configuration_utils import GenerationConfig from .integrations.deepspeed import is_deepspeed_zero3_enabled from .integrations.fsdp import is_fsdp_managed_module from .trainer import Trainer from .utils import is_datasets_available, logging if is_datasets_available(): import datasets if TYPE_CHECKING: from torch.utils.data import IterableDataset from .data.data_collator import DataCollator from .feature_extraction_utils import FeatureExtractionMixin from .image_processing_utils import BaseImageProcessor from .modeling_utils import PreTrainedModel from .processing_utils import ProcessorMixin from .tokenization_utils_base import PreTrainedTokenizerBase from .trainer_callback import TrainerCallback from .trainer_utils import EvalPrediction, PredictionOutput from .training_args import TrainingArguments logger = logging.get_logger(__name__) class Seq2SeqTrainer(Trainer): def __init__( self, model: Union["PreTrainedModel", nn.Module] | None = None, args: Optional["TrainingArguments"] = None, data_collator: Optional["DataCollator"] = None, train_dataset: Union[Dataset, "IterableDataset", "datasets.Dataset"] | None = None, eval_dataset: Dataset | dict[str, Dataset] | None = None, processing_class: Union[ "PreTrainedTokenizerBase", "BaseImageProcessor", "FeatureExtractionMixin", "ProcessorMixin" ] | None = None, model_init: Callable[[], "PreTrainedModel"] | None = None, compute_loss_func: Callable | None = None, compute_metrics: Callable[["EvalPrediction"], dict] | None = None, callbacks: list["TrainerCallback"] | None = None, optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, ): super().__init__( model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, processing_class=processing_class, model_init=model_init, compute_loss_func=compute_loss_func, compute_metrics=compute_metrics, callbacks=callbacks, optimizers=optimizers, preprocess_logits_for_metrics=preprocess_logits_for_metrics, ) # Override self.model.generation_config if a GenerationConfig is specified in args. # Priority: args.generation_config > model.generation_config > default GenerationConfig. if self.args.generation_config is not None: gen_config = self.load_generation_config(self.args.generation_config) self.model.generation_config = gen_config @staticmethod def load_generation_config(gen_config_arg: str | GenerationConfig) -> GenerationConfig: """ Loads a `~generation.GenerationConfig` from the `Seq2SeqTrainingArguments.generation_config` arguments. Args: gen_config_arg (`str` or [`~generation.GenerationConfig]`): `Seq2SeqTrainingArguments.generation_config` argument. Returns: A `~generation.GenerationConfig`. """ # GenerationConfig provided, nothing to do if isinstance(gen_config_arg, GenerationConfig): gen_config = deepcopy(gen_config_arg) else: # str or Path pretrained_model_name = Path(gen_config_arg) if isinstance(gen_config_arg, str) else gen_config_arg config_file_name = None # Figuring if it is path pointing to a file, pointing to a directory or else a model id or URL # This step is required in order to determine config_file_name if pretrained_model_name.is_file(): config_file_name = pretrained_model_name.name pretrained_model_name = pretrained_model_name.parent # dir path elif pretrained_model_name.is_dir(): pass # model id or URL else: pretrained_model_name = gen_config_arg gen_config = GenerationConfig.from_pretrained(pretrained_model_name, config_file_name) # Strict validation to fail early. `GenerationConfig.save_pretrained()`, run at the end of training, throws # an exception if there are warnings at validation time. try: gen_config.validate(strict=True) except ValueError as exc: raise ValueError(str(exc) + "\n\nFix these issues to train your model.") return gen_config def evaluate( self, eval_dataset: Dataset | None = None, ignore_keys: list[str] | None = None, metric_key_prefix: str = "eval", **gen_kwargs, ) -> dict[str, float]: """ Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init `compute_metrics` argument). You can also subclass and override this method to inject custom behavior. Args: eval_dataset (`Dataset`, *optional*): Pass a dataset if you wish to override `self.eval_dataset`. If it is an [`~datasets.Dataset`], columns not accepted by the `model.forward()` method are automatically removed. It must implement the `__len__` method. ignore_keys (`list[str]`, *optional*): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. metric_key_prefix (`str`, *optional*, defaults to `"eval"`): An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is `"eval"` (default) max_length (`int`, *optional*): The maximum target length to use when predicting with the generate method. num_beams (`int`, *optional*): Number of beams for beam search that will be used when predicting with the generate method. 1 means no beam search. gen_kwargs: Additional `generate` specific kwargs. Returns: A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The dictionary also contains the epoch number which comes from the training state. """ gen_kwargs = gen_kwargs.copy() # Use legacy argument setting if a) the option is not explicitly passed; and b) the argument is set in the # training args if ( gen_kwargs.get("max_length") is None and gen_kwargs.get("max_new_tokens") is None and self.args.generation_max_length is not None ): gen_kwargs["max_length"] = self.args.generation_max_length if gen_kwargs.get("num_beams") is None and self.args.generation_num_beams is not None: gen_kwargs["num_beams"] = self.args.generation_num_beams # We don't want to drop samples in general self.gather_function = self.accelerator.gather self._gen_kwargs = gen_kwargs return super().evaluate(eval_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix) def predict( self, test_dataset: Dataset, ignore_keys: list[str] | None = None, metric_key_prefix: str = "test", **gen_kwargs, ) -> "PredictionOutput": """ Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in `evaluate()`. Args: test_dataset (`Dataset`): Dataset to run the predictions on. If it is a [`~datasets.Dataset`], columns not accepted by the `model.forward()` method are automatically removed. Has to implement the method `__len__` ignore_keys (`list[str]`, *optional*): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. metric_key_prefix (`str`, *optional*, defaults to `"eval"`): An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is `"eval"` (default) max_length (`int`, *optional*): The maximum target length to use when predicting with the generate method. num_beams (`int`, *optional*): Number of beams for beam search that will be used when predicting with the generate method. 1 means no beam search. gen_kwargs: Additional `generate` specific kwargs. <Tip> If your predictions or labels have different sequence lengths (for instance because you're doing dynamic padding in a token classification task) the predictions will be padded (on the right) to allow for concatenation into one array. The padding index is -100. </Tip> Returns: *NamedTuple* A namedtuple with the following keys: - predictions (`np.ndarray`): The predictions on `test_dataset`. - label_ids (`np.ndarray`, *optional*): The labels (if the dataset contained some). - metrics (`dict[str, float]`, *optional*): The potential dictionary of metrics (if the dataset contained labels). """ gen_kwargs = gen_kwargs.copy() # Use legacy argument setting if a) the option is not explicitly passed; and b) the argument is set in the # training args if ( gen_kwargs.get("max_length") is None and gen_kwargs.get("max_new_tokens") is None and self.args.generation_max_length is not None ): gen_kwargs["max_length"] = self.args.generation_max_length if gen_kwargs.get("num_beams") is None and self.args.generation_num_beams is not None: gen_kwargs["num_beams"] = self.args.generation_num_beams self.gather_function = self.accelerator.gather self._gen_kwargs = gen_kwargs return super().predict(test_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix) def prediction_step( self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], prediction_loss_only: bool, ignore_keys: list[str] | None = None, **gen_kwargs, ) -> tuple[float | None, torch.Tensor | None, torch.Tensor | None]: """ Perform an evaluation step on `model` using `inputs`. Subclass and override to inject custom behavior. Args: model (`nn.Module`): The model to evaluate. inputs (`dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument `labels`. Check your model's documentation for all accepted arguments. prediction_loss_only (`bool`): Whether or not to return the loss only. gen_kwargs: Additional `generate` specific kwargs. Return: tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and labels (each being optional). """ if not self.args.predict_with_generate or prediction_loss_only: return super().prediction_step( model, inputs, prediction_loss_only=prediction_loss_only, ignore_keys=ignore_keys ) has_labels = "labels" in inputs inputs = self._prepare_inputs(inputs) # Priority (handled in generate): # non-`None` gen_kwargs > model.generation_config > default GenerationConfig() if len(gen_kwargs) == 0 and hasattr(self, "_gen_kwargs"): gen_kwargs = self._gen_kwargs.copy() if "num_beams" in gen_kwargs and gen_kwargs["num_beams"] is None: gen_kwargs.pop("num_beams") if "max_length" in gen_kwargs and gen_kwargs["max_length"] is None: gen_kwargs.pop("max_length") default_synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self.model) gen_kwargs["synced_gpus"] = gen_kwargs.get("synced_gpus", default_synced_gpus) generation_inputs = inputs.copy() # If the `decoder_input_ids` was created from `labels`, evict the former, so that the model can freely generate # (otherwise, it would continue generating from the padded `decoder_input_ids`) if ( "labels" in generation_inputs and "decoder_input_ids" in generation_inputs and generation_inputs["labels"].shape == generation_inputs["decoder_input_ids"].shape ): generation_inputs = { k: v for k, v in inputs.items() if k not in ("decoder_input_ids", "decoder_attention_mask") } summon_full_params_context = ( FullyShardedDataParallel.summon_full_params(self.model) if isinstance(self.model, FullyShardedDataParallel) else contextlib.nullcontext() ) with summon_full_params_context: generated_tokens = self.model.generate(**generation_inputs, **gen_kwargs) # Temporary hack to ensure the generation config is not initialized for each iteration of the evaluation loop # TODO: remove this hack when the legacy code that initializes generation_config from a model config is # removed in https://github.com/huggingface/transformers/blob/98d88b23f54e5a23e741833f1e973fdf600cc2c5/src/transformers/generation/utils.py#L1183 if self.model.generation_config._from_model_config: self.model.generation_config._from_model_config = False # Retrieves GenerationConfig from model.generation_config # Update with defaults because earlier the generation config used ot be init # with default values. Now we init it with `None` and keep defaults for BC gen_config = self.model.generation_config default_gen_config = gen_config._get_default_generation_params() gen_config.update(**default_gen_config, defaults_only=True) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_config.max_length: generated_tokens = self._pad_tensors_to_max_len(generated_tokens, gen_config.max_length) elif gen_config.max_new_tokens is not None and generated_tokens.shape[-1] < gen_config.max_new_tokens + 1: generated_tokens = self._pad_tensors_to_max_len(generated_tokens, gen_config.max_new_tokens + 1) with torch.no_grad(): if has_labels: with self.compute_loss_context_manager(): outputs = model(**inputs) if self.label_smoother is not None: loss = self.label_smoother(outputs, inputs["labels"]).detach().mean() else: loss = (outputs["loss"] if isinstance(outputs, dict) else outputs[0]).detach().mean() else: loss = None if self.args.prediction_loss_only: return loss, None, None if has_labels: labels = inputs["labels"] if labels.shape[-1] < gen_config.max_length: labels = self._pad_tensors_to_max_len(labels, gen_config.max_length) elif gen_config.max_new_tokens is not None and labels.shape[-1] < gen_config.max_new_tokens + 1: labels = self._pad_tensors_to_max_len(labels, gen_config.max_new_tokens + 1) else: labels = None return loss, generated_tokens, labels def _pad_tensors_to_max_len(self, tensor, max_length): if self.processing_class is not None and hasattr(self.processing_class, "pad_token_id"): # If PAD token is not defined at least EOS token has to be defined pad_token_id = ( self.processing_class.pad_token_id if self.processing_class.pad_token_id is not None else self.processing_class.eos_token_id ) else: if self.model.config.pad_token_id is not None: pad_token_id = self.model.config.pad_token_id else: raise ValueError("Pad_token_id must be set in the configuration of the model, in order to pad tensors") padded_tensor = pad_token_id * torch.ones( (tensor.shape[0], max_length), dtype=tensor.dtype, device=tensor.device ) padded_tensor[:, : tensor.shape[-1]] = tensor return padded_tensor
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/file_utils.py
src/transformers/file_utils.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ File utilities: utilities related to download and cache models This module should not be update anymore and is only left for backward compatibility. """ from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, HF_MODULES_CACHE, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TRANSFORMERS_DYNAMIC_MODULE_NAME, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, define_sagemaker_information, get_torch_version, has_file, http_user_agent, is_apex_available, is_bs4_available, is_coloredlogs_available, is_datasets_available, is_detectron2_available, is_faiss_available, is_ftfy_available, is_g2p_en_available, is_in_notebook, is_ipex_available, is_librosa_available, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_py3nvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_available, is_spacy_available, is_speech_available, is_tensor, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_cuda_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tf32_available, is_torch_xla_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/safetensors_conversion.py
src/transformers/safetensors_conversion.py
from typing import Optional import httpx from huggingface_hub import Discussion, HfApi, get_repo_discussions from .utils import cached_file, http_user_agent, logging logger = logging.get_logger(__name__) def previous_pr(api: HfApi, model_id: str, pr_title: str, token: str) -> Optional["Discussion"]: main_commit = api.list_repo_commits(model_id, token=token)[0].commit_id for discussion in get_repo_discussions(repo_id=model_id, token=token): if discussion.title == pr_title and discussion.status == "open" and discussion.is_pull_request: commits = api.list_repo_commits(model_id, revision=discussion.git_reference, token=token) if main_commit == commits[1].commit_id: return discussion return None def spawn_conversion(token: str, private: bool, model_id: str): logger.info("Attempting to convert .bin model on the fly to safetensors.") safetensors_convert_space_url = "https://safetensors-convert.hf.space" sse_url = f"{safetensors_convert_space_url}/call/run" def start(_sse_connection): for line in _sse_connection.iter_lines(): line = line.decode() if line.startswith("event:"): status = line[7:] logger.debug(f"Safetensors conversion status: {status}") if status == "complete": return elif status == "heartbeat": logger.debug("Heartbeat") else: logger.debug(f"Unknown status {status}") else: logger.debug(line) data = {"data": [model_id, private, token]} result = httpx.post(sse_url, follow_redirects=True, json=data).json() event_id = result["event_id"] with httpx.stream("GET", f"{sse_url}/{event_id}") as sse_connection: try: logger.debug("Spawning safetensors automatic conversion.") start(sse_connection) except Exception as e: logger.warning(f"Error during conversion: {repr(e)}") def get_conversion_pr_reference(api: HfApi, model_id: str, **kwargs): private = api.model_info(model_id).private logger.info("Attempting to create safetensors variant") pr_title = "Adding `safetensors` variant of this model" token = kwargs.get("token") # This looks into the current repo's open PRs to see if a PR for safetensors was already open. If so, it # returns it. It checks that the PR was opened by the bot and not by another user so as to prevent # security breaches. pr = previous_pr(api, model_id, pr_title, token=token) if pr is None or (not private and pr.author != "SFconvertbot"): spawn_conversion(token, private, model_id) pr = previous_pr(api, model_id, pr_title, token=token) else: logger.info("Safetensors PR exists") if pr is None: raise OSError( "Could not create safetensors conversion PR. The repo does not appear to have a file named pytorch_model.bin or model.safetensors." "If you are loading with variant, use `use_safetensors=False` to load the original model." ) sha = f"refs/pr/{pr.num}" return sha def auto_conversion(pretrained_model_name_or_path: str, ignore_errors_during_conversion=False, **cached_file_kwargs): try: api = HfApi(token=cached_file_kwargs.get("token"), headers={"user-agent": http_user_agent()}) sha = get_conversion_pr_reference(api, pretrained_model_name_or_path, **cached_file_kwargs) if sha is None: return None, None cached_file_kwargs["revision"] = sha del cached_file_kwargs["_commit_hash"] # This is an additional HEAD call that could be removed if we could infer sharded/non-sharded from the PR # description. sharded = api.file_exists( pretrained_model_name_or_path, "model.safetensors.index.json", revision=sha, token=cached_file_kwargs.get("token"), ) filename = "model.safetensors.index.json" if sharded else "model.safetensors" resolved_archive_file = cached_file(pretrained_model_name_or_path, filename, **cached_file_kwargs) return resolved_archive_file, sha, sharded except Exception as e: if not ignore_errors_during_conversion: raise e
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/image_processing_utils.py
src/transformers/image_processing_utils.py
# Copyright 2022 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math from collections.abc import Iterable from typing import Optional, Union import numpy as np from .image_processing_base import BatchFeature, ImageProcessingMixin from .image_transforms import center_crop, normalize, rescale from .image_utils import ChannelDimension, ImageInput, get_image_size from .processing_utils import ImagesKwargs, Unpack from .utils import logging from .utils.import_utils import requires logger = logging.get_logger(__name__) INIT_SERVICE_KWARGS = [ "processor_class", "image_processor_type", ] @requires(backends=("vision",)) class BaseImageProcessor(ImageProcessingMixin): valid_kwargs = ImagesKwargs def __init__(self, **kwargs): super().__init__(**kwargs) @property def is_fast(self) -> bool: """ `bool`: Whether or not this image processor is a fast processor (backed by PyTorch and TorchVision). """ return False def __call__(self, images: ImageInput, *args, **kwargs: Unpack[ImagesKwargs]) -> BatchFeature: """Preprocess an image or a batch of images.""" return self.preprocess(images, *args, **kwargs) def preprocess(self, images, **kwargs) -> BatchFeature: raise NotImplementedError("Each image processor must implement its own preprocess method") def rescale( self, image: np.ndarray, scale: float, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs, ) -> np.ndarray: """ Rescale an image by a scale factor. image = image * scale. Args: image (`np.ndarray`): Image to rescale. scale (`float`): The scaling factor to rescale pixel values by. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the output image. If unset, the channel dimension format of the input image is used. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. Returns: `np.ndarray`: The rescaled image. """ return rescale(image, scale=scale, data_format=data_format, input_data_format=input_data_format, **kwargs) def normalize( self, image: np.ndarray, mean: Union[float, Iterable[float]], std: Union[float, Iterable[float]], data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs, ) -> np.ndarray: """ Normalize an image. image = (image - image_mean) / image_std. Args: image (`np.ndarray`): Image to normalize. mean (`float` or `Iterable[float]`): Image mean to use for normalization. std (`float` or `Iterable[float]`): Image standard deviation to use for normalization. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the output image. If unset, the channel dimension format of the input image is used. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. Returns: `np.ndarray`: The normalized image. """ return normalize( image, mean=mean, std=std, data_format=data_format, input_data_format=input_data_format, **kwargs ) def center_crop( self, image: np.ndarray, size: dict[str, int], data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs, ) -> np.ndarray: """ Center crop an image to `(size["height"], size["width"])`. If the input size is smaller than `crop_size` along any edge, the image is padded with 0's and then center cropped. Args: image (`np.ndarray`): Image to center crop. size (`dict[str, int]`): Size of the output image. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the output image. If unset, the channel dimension format of the input image is used. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. """ size = get_size_dict(size) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}") return center_crop( image, size=(size["height"], size["width"]), data_format=data_format, input_data_format=input_data_format, **kwargs, ) def to_dict(self): encoder_dict = super().to_dict() encoder_dict.pop("_valid_processor_keys", None) return encoder_dict VALID_SIZE_DICT_KEYS = ( {"height", "width"}, {"shortest_edge"}, {"shortest_edge", "longest_edge"}, {"longest_edge"}, {"max_height", "max_width"}, ) def is_valid_size_dict(size_dict): if not isinstance(size_dict, dict): return False size_dict_keys = set(size_dict.keys()) for allowed_keys in VALID_SIZE_DICT_KEYS: if size_dict_keys == allowed_keys: return True return False def convert_to_size_dict( size, max_size: Optional[int] = None, default_to_square: bool = True, height_width_order: bool = True ): # By default, if size is an int we assume it represents a tuple of (size, size). if isinstance(size, int) and default_to_square: if max_size is not None: raise ValueError("Cannot specify both size as an int, with default_to_square=True and max_size") return {"height": size, "width": size} # In other configs, if size is an int and default_to_square is False, size represents the length of # the shortest edge after resizing. elif isinstance(size, int) and not default_to_square: size_dict = {"shortest_edge": size} if max_size is not None: size_dict["longest_edge"] = max_size return size_dict # Otherwise, if size is a tuple it's either (height, width) or (width, height) elif isinstance(size, (tuple, list)) and height_width_order: return {"height": size[0], "width": size[1]} elif isinstance(size, (tuple, list)) and not height_width_order: return {"height": size[1], "width": size[0]} elif size is None and max_size is not None: if default_to_square: raise ValueError("Cannot specify both default_to_square=True and max_size") return {"longest_edge": max_size} raise ValueError(f"Could not convert size input to size dict: {size}") def get_size_dict( size: Optional[Union[int, Iterable[int], dict[str, int]]] = None, max_size: Optional[int] = None, height_width_order: bool = True, default_to_square: bool = True, param_name="size", ) -> dict: """ Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height, width) or (width, height) format. - If `size` is tuple, it is converted to `{"height": size[0], "width": size[1]}` or `{"height": size[1], "width": size[0]}` if `height_width_order` is `False`. - If `size` is an int, and `default_to_square` is `True`, it is converted to `{"height": size, "width": size}`. - If `size` is an int and `default_to_square` is False, it is converted to `{"shortest_edge": size}`. If `max_size` is set, it is added to the dict as `{"longest_edge": max_size}`. Args: size (`Union[int, Iterable[int], dict[str, int]]`, *optional*): The `size` parameter to be cast into a size dictionary. max_size (`Optional[int]`, *optional*): The `max_size` parameter to be cast into a size dictionary. height_width_order (`bool`, *optional*, defaults to `True`): If `size` is a tuple, whether it's in (height, width) or (width, height) order. default_to_square (`bool`, *optional*, defaults to `True`): If `size` is an int, whether to default to a square image or not. """ if not isinstance(size, dict): size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order) logger.info( f"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}." f" Converted to {size_dict}.", ) else: size_dict = size if not is_valid_size_dict(size_dict): raise ValueError( f"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}" ) return size_dict def select_best_resolution(original_size: tuple, possible_resolutions: list) -> tuple: """ Selects the best resolution from a list of possible resolutions based on the original size. This is done by calculating the effective and wasted resolution for each possible resolution. The best fit resolution is the one that maximizes the effective resolution and minimizes the wasted resolution. Args: original_size (tuple): The original size of the image in the format (height, width). possible_resolutions (list): A list of possible resolutions in the format [(height1, width1), (height2, width2), ...]. Returns: tuple: The best fit resolution in the format (height, width). """ original_height, original_width = original_size best_fit = None max_effective_resolution = 0 min_wasted_resolution = float("inf") for height, width in possible_resolutions: scale = min(width / original_width, height / original_height) downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale) effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height) wasted_resolution = (width * height) - effective_resolution if effective_resolution > max_effective_resolution or ( effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution ): max_effective_resolution = effective_resolution min_wasted_resolution = wasted_resolution best_fit = (height, width) return best_fit def get_patch_output_size(image, target_resolution, input_data_format): """ Given an image and a target resolution, calculate the output size of the image after cropping to the target """ original_height, original_width = get_image_size(image, channel_dim=input_data_format) target_height, target_width = target_resolution scale_w = target_width / original_width scale_h = target_height / original_height if scale_w < scale_h: new_width = target_width new_height = min(math.ceil(original_height * scale_w), target_height) else: new_height = target_height new_width = min(math.ceil(original_width * scale_h), target_width) return new_height, new_width
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/cache_utils.py
src/transformers/cache_utils.py
from abc import ABC, abstractmethod from collections.abc import Iterable from typing import Any, Optional import torch from .configuration_utils import PreTrainedConfig from .utils import ( is_hqq_available, is_quanto_greater, is_torch_greater_or_equal, is_torchdynamo_compiling, logging, ) if is_hqq_available(): from hqq.core.quantize import Quantizer as HQQQuantizer _is_torch_greater_or_equal_than_2_7 = is_torch_greater_or_equal("2.7", accept_dev=True) logger = logging.get_logger(__name__) class CacheLayerMixin(ABC): """Base, abstract class for a single layer's cache.""" is_compileable = False def __init__(self): self.keys: Optional[torch.Tensor] = None self.values: Optional[torch.Tensor] = None self.is_initialized = False def __repr__(self): return f"{self.__class__.__name__}" @abstractmethod def lazy_initialization(self, key_states: torch.Tensor): ... @abstractmethod def update( self, key_states: torch.Tensor, value_states: torch.Tensor, cache_kwargs: Optional[dict[str, Any]] = None ) -> tuple[torch.Tensor, torch.Tensor]: ... @abstractmethod def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]: ... @abstractmethod def get_seq_length(self) -> int: ... @abstractmethod def get_max_cache_shape(self) -> int: ... def offload(self): """Offload this layer's data to CPU device.""" if self.is_initialized: self.keys = self.keys.to("cpu", non_blocking=True) self.values = self.values.to("cpu", non_blocking=True) def prefetch(self): """In case of layer offloading, this allows to move the data back to the layer's device ahead of time.""" if self.is_initialized and self.keys.device != self.device: self.keys = self.keys.to(self.device, non_blocking=True) self.values = self.values.to(self.device, non_blocking=True) def reset(self) -> None: """Resets the cache values while preserving the objects""" if self.is_initialized: self.keys.zero_() self.values.zero_() # This attribute is set on several Layers if hasattr(self, "cumulative_length"): self.cumulative_length = 0 def reorder_cache(self, beam_idx: torch.LongTensor) -> None: """Reorders this layer's cache for beam search.""" if self.get_seq_length() > 0: self.keys = self.keys.index_select(0, beam_idx.to(self.keys.device)) self.values = self.values.index_select(0, beam_idx.to(self.values.device)) class DynamicLayer(CacheLayerMixin): """ A cache layer that grows dynamically as more tokens are generated. This is the default for generative models. It stores the key and value states as tensors of shape `[batch_size, num_heads, seq_len, head_dim]`. """ is_sliding = False def lazy_initialization(self, key_states: torch.Tensor): self.dtype, self.device = key_states.dtype, key_states.device self.keys = torch.tensor([], dtype=self.dtype, device=self.device) self.values = torch.tensor([], dtype=self.dtype, device=self.device) self.is_initialized = True def update( self, key_states: torch.Tensor, value_states: torch.Tensor, cache_kwargs: Optional[dict[str, Any]] = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Update the key and value caches in-place, and return the necessary keys and value states. Args: key_states (`torch.Tensor`): The new key states to cache. value_states (`torch.Tensor`): The new value states to cache. cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache. Returns: tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states. """ # Lazy initialization if not self.is_initialized: self.lazy_initialization(key_states) self.keys = torch.cat([self.keys, key_states], dim=-2) self.values = torch.cat([self.values, value_states], dim=-2) return self.keys, self.values def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]: """Return the length and offset of the cache, used to generate the mask""" kv_offset = 0 query_length = cache_position.shape[0] kv_length = self.get_seq_length() + query_length return kv_length, kv_offset def get_seq_length(self) -> int: """Returns the sequence length of the cached states.""" if not self.is_initialized or self.keys.numel() == 0: return 0 return self.keys.shape[-2] def get_max_cache_shape(self) -> int: """Returns the maximum sequence length of the cache object. DynamicLayer does not have a maximum length.""" return -1 def crop(self, max_length: int) -> None: """ Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be negative to remove `max_length` tokens. """ if max_length < 0: max_length = self.get_seq_length() - abs(max_length) if self.get_seq_length() <= max_length: return self.keys = self.keys[..., :max_length, :] self.values = self.values[..., :max_length, :] def batch_repeat_interleave(self, repeats: int) -> None: """Repeat the cache `repeats` times in the batch dimension.""" if self.get_seq_length() > 0: self.keys = self.keys.repeat_interleave(repeats, dim=0) self.values = self.values.repeat_interleave(repeats, dim=0) def batch_select_indices(self, indices: torch.Tensor) -> None: """Only keep the `indices` in the batch dimension of the cache.""" if self.get_seq_length() > 0: self.keys = self.keys[indices, ...] self.values = self.values[indices, ...] class DynamicSlidingWindowLayer(DynamicLayer): """ A cache layer that grows dynamically as more tokens are generated, up until the sliding window size. It stores the key and value states as tensors of shape `[batch_size, num_heads, min(seq_len, sliding_window), head_dim]`. """ is_sliding = True def __init__(self, sliding_window: int): super().__init__() self.sliding_window = sliding_window self.cumulative_length = 0 self._sliding_window_tensor = torch.tensor(self.sliding_window, dtype=torch.long) def lazy_initialization(self, key_states: torch.Tensor) -> None: super().lazy_initialization(key_states) self._sliding_window_tensor = self._sliding_window_tensor.to(self.device) def update( self, key_states: torch.Tensor, value_states: torch.Tensor, cache_kwargs: Optional[dict[str, Any]] = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Update the key and value caches in-place, and return the necessary keys and value states. Args: key_states (`torch.Tensor`): The new key states to cache. value_states (`torch.Tensor`): The new value states to cache. cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache. Returns: tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states. """ # Lazy initialization if not self.is_initialized: self.lazy_initialization(key_states) self.cumulative_length += key_states.shape[-2] # Compute the full states full_key_states = torch.cat([self.keys, key_states], dim=-2) full_value_states = torch.cat([self.values, value_states], dim=-2) # Only cache the last `self.sliding_window - 1` tokens (or all of them if lower than that) self.keys = full_key_states[:, :, -self.sliding_window + 1 :, :] self.values = full_value_states[:, :, -self.sliding_window + 1 :, :] # Return the full states return full_key_states, full_value_states def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]: """Return the length and offset of the cache, used to generate the attention mask""" query_length = cache_position.shape[0] is_full = self.cumulative_length >= self.sliding_window kv_offset = max(self.cumulative_length - self.sliding_window + 1, 0) if is_full: kv_length = self.sliding_window - 1 + query_length else: kv_length = self.cumulative_length + query_length return kv_length, kv_offset def get_seq_length(self) -> int: """Returns the sequence length of the cached states.""" return self.cumulative_length def get_max_cache_shape(self) -> int: """Return the maximum cache shape of the cache""" return self.sliding_window def crop(self, max_length: int) -> None: """ Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be negative to remove `max_length` tokens. """ if self.get_seq_length() >= self.sliding_window: raise ValueError( "Cannot `crop` a `DynamicSlidingWindowLayer` after it has seen more tokens than its" "sliding window (otherwise some states are lost)" ) super().crop(max_length) self.cumulative_length = self.keys.shape[-2] class StaticLayer(CacheLayerMixin): """ A static cache layer that stores the key and value states as static tensors of shape `[batch_size, num_heads, max_cache_len), head_dim]`. It lazily allocates its full backing tensors, and then mutates them in-place. Built for `torch.compile` support. Args: max_cache_len (`int`): Maximum number of tokens that can be stored, used for tensor preallocation. """ is_compileable = True is_sliding = False def __init__(self, max_cache_len: int): super().__init__() self.max_cache_len = max_cache_len def lazy_initialization(self, key_states: torch.Tensor): """ Lazy initialization of the keys and values tensors. This allows to get all properties (dtype, device, num_heads in case of TP etc...) at runtime directly, which is extremely practical as it avoids moving devices, dtypes etc later on for each `update` (which could break the static dynamo addresses as well). If this is unwanted, one can call `early_initialization(...)` on the Cache directly, which will call this function ahead-of-time (this is required for `torch.export` for example). Note that for `compile`, as we internally don't compile the prefill, this is guaranteed to have been called already when compiling. If compiling the prefill as well, e.g. calling `model.compile(...)` before `generate` with a static cache, it is still supported in general, but without guarantees depending on the compilation options (e.g. cuda graphs, i.e. `mode="reduce-overhead"` is known to fail). But it will in general work correctly, and prefill should not be compiled anyway for performances! """ self.max_batch_size, self.num_heads, _, self.head_dim = key_states.shape self.dtype, self.device = key_states.dtype, key_states.device self.keys = torch.zeros( (self.max_batch_size, self.num_heads, self.max_cache_len, self.head_dim), dtype=self.dtype, device=self.device, ) self.values = torch.zeros( (self.max_batch_size, self.num_heads, self.max_cache_len, self.head_dim), dtype=self.dtype, device=self.device, ) # Note: `mark_static_address` is used to tag the cache as a fixed data pointer, preventing compiled graph # breaks when updating the cache. However, it is not supported when tracing the graph, so we skip it in this case. # As prefill should never be compiled, this is not an issue and it will still be run (except when users compile # prefill explicitly, but this should be avoided!) if not is_torchdynamo_compiling(): torch._dynamo.mark_static_address(self.keys) torch._dynamo.mark_static_address(self.values) self.is_initialized = True def update( self, key_states: torch.Tensor, value_states: torch.Tensor, cache_kwargs: Optional[dict[str, Any]] = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Update the key and value caches in-place, and return the necessary keys and value states. Args: key_states (`torch.Tensor`): The new key states to cache. value_states (`torch.Tensor`): The new value states to cache. cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache. Returns: tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states. """ # Lazy initialization if not self.is_initialized: self.lazy_initialization(key_states) # Some old models give None for `cache_position` or even omit passing `cache_kwargs` when used as cross-attention, # in which case we should copy the whole Layer (key_states.shape[-2] == self.max_cache_len) cache_position = cache_kwargs.get("cache_position") if cache_kwargs is not None else None cache_position = ( cache_position if cache_position is not None else torch.arange(key_states.shape[-2], device=self.device) ) # Update the cache try: self.keys.index_copy_(2, cache_position, key_states) self.values.index_copy_(2, cache_position, value_states) except NotImplementedError: # Fallback for devices like MPS where index_copy_ might not be supported. self.keys[:, :, cache_position] = key_states self.values[:, :, cache_position] = value_states return self.keys, self.values def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]: """Return the length and offset of the cache, used to generate the attention mask""" kv_offset = 0 kv_length = self.max_cache_len return kv_length, kv_offset def get_seq_length(self) -> int: """Returns the sequence length of the cached states.""" # Occupied cache == any slot in the 3rd dim (sequence length) holds a non-zero value. To save on compute, let's # limit the check to the first batch member and head dimension. return (self.keys[0, 0].any(dim=-1)).sum() if self.is_initialized else 0 def get_max_cache_shape(self) -> int: """Return the maximum cache shape of the cache""" return self.max_cache_len class StaticSlidingWindowLayer(StaticLayer): """ A static cache layer that stores the key and value states as static tensors of shape `[batch_size, num_heads, min(max_cache_len, sliding_window), head_dim]`. It lazily allocates its full backing tensors, and then mutates them in-place. Built for `torch.compile` support. Args: max_cache_len (`int`): Maximum number of tokens that can be stored, used for tensor preallocation. sliding_window (`int`): The size of the sliding window. """ is_sliding = True def __init__(self, max_cache_len: int, sliding_window: int): effective_max_cache_len = min(sliding_window, max_cache_len) super().__init__(max_cache_len=effective_max_cache_len) self.cumulative_length = 0 def update( self, key_states: torch.Tensor, value_states: torch.Tensor, cache_kwargs: Optional[dict[str, Any]] = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Update the key and value caches in-place, and return the necessary keys and value states. Args: key_states (`torch.Tensor`): The new key states to cache. value_states (`torch.Tensor`): The new value states to cache. cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache. Returns: tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states. """ # Lazy initialization if not self.is_initialized: self.lazy_initialization(key_states) # Some old models give None for `cache_position` or even omit passing `cache_kwargs` when used as cross-attention, # in which case we should copy the whole Layer (key_states.shape[-2] == self.max_cache_len) cache_position = cache_kwargs.get("cache_position") if cache_kwargs is not None else None cache_position = ( cache_position if cache_position is not None else torch.arange(key_states.shape[-2], device=self.device) ) cumulative_length = self.cumulative_length is_full = cumulative_length >= self.max_cache_len # Update it now that we saved the value above self.cumulative_length += key_states.shape[-2] if is_full: # In general, we should use a much simpler `cat` here as well, independently of the states size. However, # dynamo is currently bugged when doing it - see https://github.com/pytorch/pytorch/issues/159855 for more details if key_states.shape[-2] == 1: # Roll all values to the left by 1 position new_keys = self.keys.roll(-1, dims=-2) new_values = self.values.roll(-1, dims=-2) # Overwrite the last position with new states # (note: very important to use a tensor to index here, see https://github.com/pytorch/pytorch/issues/159855) index = torch.tensor([-1], dtype=int, device=self.device) new_keys[:, :, index] = key_states new_values[:, :, index] = value_states # Copy back into `self` (do not just assign again) in order to keep the static dynamo address self.keys.copy_(new_keys) self.values.copy_(new_values) # Very important to return the `self` tensors here, as they have the static dynamo address return self.keys, self.values # Already full but using more than 1 new token (e.g. prefill caching, chat continuation, etc...) else: full_key_states = torch.cat((self.keys[:, :, 1:, :], key_states), dim=-2) full_value_states = torch.cat((self.values[:, :, 1:, :], value_states), dim=-2) # Not yet full, but becoming full on this update elif cumulative_length + key_states.shape[2] > self.max_cache_len: # Fast prefill path, no need to cat() in this case, as the cache is currently empty if cumulative_length == 0: full_key_states = key_states full_value_states = value_states else: full_key_states = torch.cat((self.keys[:, :, :cumulative_length, :], key_states), dim=-2) full_value_states = torch.cat((self.values[:, :, :cumulative_length, :], value_states), dim=-2) else: try: self.keys.index_copy_(2, cache_position, key_states) self.values.index_copy_(2, cache_position, value_states) except NotImplementedError: self.keys[:, :, cache_position] = key_states self.values[:, :, cache_position] = value_states # Very important to return the `self` tensors here, as they have the static dynamo address return self.keys, self.values # We only cache the last `sliding_window` tokens self.keys.copy_(full_key_states[:, :, -self.max_cache_len :, :]) self.values.copy_(full_value_states[:, :, -self.max_cache_len :, :]) # we should return the whole states instead of `self.keys/values` here, as otherwise we lose some context return full_key_states, full_value_states def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]: """Return the length and offset of the cache, used to generate the attention mask""" query_length = cache_position.shape[0] sliding_window = self.max_cache_len is_full = self.cumulative_length >= self.max_cache_len kv_offset = max(self.cumulative_length - sliding_window + 1, 0) # The cache is already full if is_full: kv_length = sliding_window + query_length - 1 # Not yet full, but becoming full on this update elif self.cumulative_length + query_length > sliding_window: kv_length = self.cumulative_length + query_length # Here the Cache is still smaller than the local size, but we return the local size as it's static else: kv_length = sliding_window return kv_length, kv_offset def get_seq_length(self) -> int: """Returns the sequence length of the cached states.""" return self.cumulative_length class QuantizedLayer(DynamicLayer): """ A quantized layer similar to what is described in the [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache paper](https://huggingface.co/papers/2402.02750). It allows the model to generate longer sequence length without allocating too much memory for the key and value caches by applying quantization. The cache has two types of storage, one for original precision and one for the quantized cache. A `residual length` is set as a maximum capacity for the original precision cache. When the length goes beyond maximum capacity, the original precision cache is discarded and moved into the quantized cache. The quantization is done per-channel with a set `q_group_size` for both Keys and Values, in contrast to what was described in the paper. """ def __init__( self, nbits: int = 4, axis_key: int = 0, axis_value: int = 0, q_group_size: int = 64, residual_length: int = 128, ): super().__init__() self.nbits = nbits self.axis_key = axis_key self.axis_value = axis_value self.q_group_size = q_group_size self.residual_length = residual_length self.cumulative_length = 0 def update( self, key_states: torch.Tensor, value_states: torch.Tensor, cache_kwargs: Optional[dict[str, Any]] = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Update the key and value caches in-place, and return the necessary keys and value states. Args: key_states (`torch.Tensor`): The new key states to cache. value_states (`torch.Tensor`): The new value states to cache. cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache. Returns: tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states. """ self.cumulative_length += key_states.shape[-2] # Lazy initialization if not self.is_initialized: self.lazy_initialization(key_states) self._quantized_keys = self._quantize(key_states.contiguous(), axis=self.axis_key) self._quantized_values = self._quantize(value_states.contiguous(), axis=self.axis_value) return key_states, value_states dequant_keys = self._dequantize(self._quantized_keys) dequant_values = self._dequantize(self._quantized_values) keys_to_return = torch.cat([dequant_keys, self.keys, key_states], dim=-2) values_to_return = torch.cat([dequant_values, self.values, value_states], dim=-2) if self.keys.dim() == 4 and self.keys.shape[-2] + 1 >= self.residual_length: self._quantized_keys = self._quantize(keys_to_return.contiguous(), axis=self.axis_key) self._quantized_values = self._quantize(values_to_return.contiguous(), axis=self.axis_value) self.keys = torch.tensor([], dtype=key_states.dtype, device=key_states.device) self.values = torch.tensor([], dtype=key_states.dtype, device=key_states.device) else: self.keys = torch.cat([self.keys, key_states], dim=-2) self.values = torch.cat([self.values, value_states], dim=-2) return keys_to_return, values_to_return @abstractmethod def _quantize(self, tensor, axis): ... @abstractmethod def _dequantize(self, q_tensor): ... def get_seq_length(self) -> int: """Returns the sequence length of the cached states.""" return self.cumulative_length class QuantoQuantizedLayer(QuantizedLayer): def __init__( self, nbits: int = 4, axis_key: int = 0, axis_value: int = 0, q_group_size: int = 64, residual_length: int = 128, ): super().__init__( nbits=nbits, axis_key=axis_key, axis_value=axis_value, q_group_size=q_group_size, residual_length=residual_length, ) # We need to import quanto here to avoid circular imports due to optimum/quanto/models/transformers_models.py if is_quanto_greater("0.2.5", accept_dev=True): from optimum.quanto import MaxOptimizer, qint2, qint4 else: raise ImportError( "You need optimum-quanto package version to be greater or equal than 0.2.5 to use `QuantoQuantizedCache`. " ) if self.nbits not in [2, 4]: raise ValueError(f"`nbits` for `quanto` backend has to be one of [`2`, `4`] but got {self.nbits}") if self.axis_key not in [0, -1]: raise ValueError(f"`axis_key` for `quanto` backend has to be one of [`0`, `-1`] but got {self.axis_key}") if self.axis_value not in [0, -1]: raise ValueError( f"`axis_value` for `quanto` backend has to be one of [`0`, `-1`] but got {self.axis_value}" ) self.qtype = qint4 if self.nbits == 4 else qint2 self.optimizer = MaxOptimizer() # hardcode as it's the only one for per-channel quantization def _quantize(self, tensor, axis): from optimum.quanto import quantize_weight scale, zeropoint = self.optimizer(tensor, self.qtype, axis, self.q_group_size) qtensor = quantize_weight(tensor, self.qtype, axis, scale, zeropoint, self.q_group_size) return qtensor def _dequantize(self, qtensor): return qtensor.dequantize() class HQQQuantizedLayer(QuantizedLayer): def __init__( self, nbits: int = 4, axis_key: int = 0, axis_value: int = 0, q_group_size: int = 64, residual_length: int = 128, ): super().__init__( nbits=nbits, axis_key=axis_key, axis_value=axis_value, q_group_size=q_group_size, residual_length=residual_length, ) if not is_hqq_available(): raise ImportError("You need to install `hqq` to use `HQQQuantizedLayer`") if self.nbits not in [1, 2, 3, 4, 8]: raise ValueError( f"`nbits` for `HQQ` backend has to be one of [`1`, `2`, `3`, `4`, `8`] but got {self.nbits}" ) if self.axis_key not in [0, 1]: raise ValueError(f"`axis_key` for `HQQ` backend has to be one of [`0`, `1`] but got {self.axis_key}") if self.axis_value not in [0, 1]: raise ValueError(f"`axis_value` for `HQQ` backend has to be one of [`0`, `1`] but got {self.axis_value}") self.quantizer = HQQQuantizer def _quantize(self, tensor, axis): qtensor, meta = self.quantizer.quantize( tensor, axis=axis, device=self.keys.device, compute_dtype=self.keys.dtype, nbits=self.nbits, group_size=self.q_group_size, ) meta["compute_dtype"] = self.keys.dtype self.quantizer.cuda(qtensor, meta=meta, device=self.keys.device) # Move to device and cast to dtype meta["scale"] = meta["scale"].to(qtensor.device) meta["zero"] = meta["zero"].to(qtensor.device) return qtensor, meta def _dequantize(self, qtensor): quant_tensor, meta = qtensor tensor = self.quantizer.dequantize(quant_tensor, meta) return tensor class Cache: """ A `Cache` is mostly a list of `CacheLayerMixin` objects, one per model layer. It serves as a container for the Cache of each layer. Args: layers (`Optional`, *optional*): A list of pre-created `CacheLayerMixin`. If omitted (`None`), then `layer_class_to_replicate` will be used. layer_class_to_replicate (`type[CacheLayerMixin]`, *optional*): Only used if `layers` is omitted (`None`), in which case it will be used as the base class for each layer, and the layers will be added lazily as soon as `update` is called with a `layer_idx` greater than the current list of layers. offloading (`bool`, *optional*, defaults to `False`): Whether to perform offloading of the layers to `cpu`, to save GPU memory. offload_only_non_sliding (`bool`, *optional*, defaults to `True`): If `offloading` is `True`, this further decides if only the non-sliding layers will be offloaded (because usually the sliding layers are small in size, so there is no need to offload them, and skipping it is faster). """ def __init__( self, layers: Optional[list[CacheLayerMixin]] = None, layer_class_to_replicate: Optional[type[CacheLayerMixin]] = None, offloading: bool = False, offload_only_non_sliding: bool = True, ): if layers is not None and layer_class_to_replicate is not None: raise ValueError( "You can construct a Cache either from a list `layers` of all the predefined `CacheLayer`, or from a " "`layer_class_to_replicate`, in which case the Cache will append a new layer corresponding to " "`layer_class_to_replicate` for each new call to `update` with an idx not already in the Cache." ) if layers is None and layer_class_to_replicate is None: raise ValueError( "You should provide exactly one of `layers` or `layer_class_to_replicate` to initialize a Cache." ) self.layers = layers if layers is not None else [] self.layer_class_to_replicate = layer_class_to_replicate self.offloading = offloading if self.offloading: self.only_non_sliding = offload_only_non_sliding self.prefetch_stream = torch.Stream() if _is_torch_greater_or_equal_than_2_7 else torch.cuda.Stream() def __repr__(self): return f"{self.__class__.__name__}(layers={self.layers})" def prefetch(self, layer_idx: int, only_non_sliding: bool = True): """ Prefetch a given layer on its device. If `only_non_sliding` is True, it will try to prefetch only the layers which are non-sliding. If the `layer_idx` is outside the range, this will circle back to the first layers. Note that we use a non-default stream for this, to avoid blocking. """ if only_non_sliding: # Try to find next non-sliding, starting at `layer_idx` try: layer_idx = layer_idx + self.is_sliding[layer_idx:].index(False) # In this case, we need to circle back to the beginning except ValueError: layer_idx = self.is_sliding.index(False) else: layer_idx = layer_idx if layer_idx < len(self.layers) else 0 # Prefetch with self.prefetch_stream if _is_torch_greater_or_equal_than_2_7 else torch.cuda.stream(self.prefetch_stream): self.layers[layer_idx].prefetch() def offload(self, layer_idx: int, only_non_sliding: bool = True): """ Offload a given `layer_idx`. If `only_non_sliding` is True, it will offload `layer_idx` only if it is a non-sliding layer. Note that we do it on the default stream, so that we ensure all earlier computation in the layer's `update` methods are finished. """ if not (only_non_sliding and self.is_sliding[layer_idx]): self.layers[layer_idx].offload() def update( self, key_states: torch.Tensor, value_states: torch.Tensor,
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/dependency_versions_check.py
src/transformers/dependency_versions_check.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers pkgs_to_check_at_runtime = [ "python", "tqdm", "regex", "requests", "packaging", "filelock", "numpy", "tokenizers", "huggingface-hub", "safetensors", "accelerate", "pyyaml", ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py") def dep_version_check(pkg, hint=None): require_version(deps[pkg], hint)
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/hf_argparser.py
src/transformers/hf_argparser.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import dataclasses import json import os import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from collections.abc import Callable, Iterable from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Literal, NewType, Optional, Union, get_type_hints import yaml DataClass = NewType("DataClass", Any) DataClassType = NewType("DataClassType", Any) # From https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse def string_to_bool(v): if isinstance(v, bool): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( f"Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)." ) def make_choice_type_function(choices: list) -> Callable[[str], Any]: """ Creates a mapping function from each choices string representation to the actual value. Used to support multiple value types for a single argument. Args: choices (list): List of choices. Returns: Callable[[str], Any]: Mapping function from string representation to actual value for each choice. """ str_to_choice = {str(choice): choice for choice in choices} return lambda arg: str_to_choice.get(arg, arg) def HfArg( *, aliases: Optional[Union[str, list[str]]] = None, help: Optional[str] = None, default: Any = dataclasses.MISSING, default_factory: Callable[[], Any] = dataclasses.MISSING, metadata: Optional[dict] = None, **kwargs, ) -> dataclasses.Field: """Argument helper enabling a concise syntax to create dataclass fields for parsing with `HfArgumentParser`. Example comparing the use of `HfArg` and `dataclasses.field`: ``` @dataclass class Args: regular_arg: str = dataclasses.field(default="Huggingface", metadata={"aliases": ["--example", "-e"], "help": "This syntax could be better!"}) hf_arg: str = HfArg(default="Huggingface", aliases=["--example", "-e"], help="What a nice syntax!") ``` Args: aliases (Union[str, list[str]], optional): Single string or list of strings of aliases to pass on to argparse, e.g. `aliases=["--example", "-e"]`. Defaults to None. help (str, optional): Help string to pass on to argparse that can be displayed with --help. Defaults to None. default (Any, optional): Default value for the argument. If not default or default_factory is specified, the argument is required. Defaults to dataclasses.MISSING. default_factory (Callable[[], Any], optional): The default_factory is a 0-argument function called to initialize a field's value. It is useful to provide default values for mutable types, e.g. lists: `default_factory=list`. Mutually exclusive with `default=`. Defaults to dataclasses.MISSING. metadata (dict, optional): Further metadata to pass on to `dataclasses.field`. Defaults to None. Returns: Field: A `dataclasses.Field` with the desired properties. """ if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls metadata = {} if aliases is not None: metadata["aliases"] = aliases if help is not None: metadata["help"] = help return dataclasses.field(metadata=metadata, default=default, default_factory=default_factory, **kwargs) class HfArgumentParser(ArgumentParser): """ This subclass of `argparse.ArgumentParser` uses type hints on dataclasses to generate arguments. The class is designed to play well with the native argparse. In particular, you can add more (non-dataclass backed) arguments to the parser after initialization and you'll get the output back after parsing as an additional namespace. Optional: To create sub argument groups use the `_argument_group_name` attribute in the dataclass. Args: dataclass_types (`DataClassType` or `Iterable[DataClassType]`, *optional*): Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args. kwargs (`dict[str, Any]`, *optional*): Passed to `argparse.ArgumentParser()` in the regular way. """ dataclass_types: Iterable[DataClassType] def __init__(self, dataclass_types: Optional[Union[DataClassType, Iterable[DataClassType]]] = None, **kwargs): # Make sure dataclass_types is an iterable if dataclass_types is None: dataclass_types = [] elif not isinstance(dataclass_types, Iterable): dataclass_types = [dataclass_types] # To make the default appear when using --help if "formatter_class" not in kwargs: kwargs["formatter_class"] = ArgumentDefaultsHelpFormatter super().__init__(**kwargs) if dataclasses.is_dataclass(dataclass_types): dataclass_types = [dataclass_types] self.dataclass_types = list(dataclass_types) for dtype in self.dataclass_types: self._add_dataclass_arguments(dtype) @staticmethod def _parse_dataclass_field(parser: ArgumentParser, field: dataclasses.Field): # Long-option strings are conventionlly separated by hyphens rather # than underscores, e.g., "--long-format" rather than "--long_format". # Argparse converts hyphens to underscores so that the destination # string is a valid attribute name. Hf_argparser should do the same. long_options = [f"--{field.name}"] if "_" in field.name: long_options.append(f"--{field.name.replace('_', '-')}") kwargs = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type, str): raise RuntimeError( "Unresolved type detected, which should have been done with the help of " "`typing.get_type_hints` method by default" ) aliases = kwargs.pop("aliases", []) if isinstance(aliases, str): aliases = [aliases] origin_type = getattr(field.type, "__origin__", field.type) if origin_type is Union or (hasattr(types, "UnionType") and isinstance(origin_type, types.UnionType)): if str not in field.type.__args__ and ( len(field.type.__args__) != 2 or type(None) not in field.type.__args__ ): raise ValueError( "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" " the argument parser only supports one type per argument." f" Problem encountered in field '{field.name}'." ) if type(None) not in field.type.__args__: # filter `str` in Union field.type = field.type.__args__[0] if field.type.__args__[1] is str else field.type.__args__[1] origin_type = getattr(field.type, "__origin__", field.type) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) field.type = ( field.type.__args__[0] if isinstance(None, field.type.__args__[1]) else field.type.__args__[1] ) origin_type = getattr(field.type, "__origin__", field.type) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) bool_kwargs = {} if origin_type is Literal or (isinstance(field.type, type) and issubclass(field.type, Enum)): if origin_type is Literal: kwargs["choices"] = field.type.__args__ else: kwargs["choices"] = [x.value for x in field.type] kwargs["type"] = make_choice_type_function(kwargs["choices"]) if field.default is not dataclasses.MISSING: kwargs["default"] = field.default else: kwargs["required"] = True elif field.type is bool or field.type == Optional[bool]: # Copy the correct kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument bool_kwargs = copy(kwargs) # Hack because type=bool in argparse does not behave as we want. kwargs["type"] = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. default = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --{field.name} in any way kwargs["default"] = default # This tells argparse we accept 0 or 1 value after --{field.name} kwargs["nargs"] = "?" # This is the value that will get picked if we do --{field.name} (without value) kwargs["const"] = True elif isclass(origin_type) and issubclass(origin_type, list): kwargs["type"] = field.type.__args__[0] kwargs["nargs"] = "+" if field.default_factory is not dataclasses.MISSING: kwargs["default"] = field.default_factory() elif field.default is dataclasses.MISSING: kwargs["required"] = True else: kwargs["type"] = field.type if field.default is not dataclasses.MISSING: kwargs["default"] = field.default elif field.default_factory is not dataclasses.MISSING: kwargs["default"] = field.default_factory() else: kwargs["required"] = True parser.add_argument(*long_options, *aliases, **kwargs) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): bool_kwargs["default"] = False parser.add_argument( f"--no_{field.name}", f"--no-{field.name.replace('_', '-')}", action="store_false", dest=field.name, **bool_kwargs, ) def _add_dataclass_arguments(self, dtype: DataClassType): if hasattr(dtype, "_argument_group_name"): parser = self.add_argument_group(dtype._argument_group_name) else: parser = self try: type_hints: dict[str, type] = get_type_hints(dtype) except NameError: raise RuntimeError( f"Type resolution failed for {dtype}. Try declaring the class in global scope or " "removing line of `from __future__ import annotations` which opts in Postponed " "Evaluation of Annotations (PEP 563)" ) for field in dataclasses.fields(dtype): if not field.init: continue field.type = type_hints[field.name] self._parse_dataclass_field(parser, field) def parse_args_into_dataclasses( self, args=None, return_remaining_strings=False, look_for_args_file=True, args_filename=None, args_file_flag=None, ) -> tuple[DataClass, ...]: """ Parse command-line args into instances of the specified dataclass types. This relies on argparse's `ArgumentParser.parse_known_args`. See the doc at: docs.python.org/3/library/argparse.html#argparse.ArgumentParser.parse_args Args: args: List of strings to parse. The default is taken from sys.argv. (same as argparse.ArgumentParser) return_remaining_strings: If true, also return a list of remaining argument strings. look_for_args_file: If true, will look for a ".args" file with the same base name as the entry point script for this process, and will append its potential content to the command line args. args_filename: If not None, will uses this file instead of the ".args" file specified in the previous argument. args_file_flag: If not None, will look for a file in the command-line args specified with this flag. The flag can be specified multiple times and precedence is determined by the order (last one wins). Returns: Tuple consisting of: - the dataclass instances in the same order as they were passed to the initializer.abspath - if applicable, an additional namespace for more (non-dataclass backed) arguments added to the parser after initialization. - The potential list of remaining argument strings. (same as argparse.ArgumentParser.parse_known_args) """ if args_file_flag or args_filename or (look_for_args_file and len(sys.argv)): args_files = [] if args_filename: args_files.append(Path(args_filename)) elif look_for_args_file and len(sys.argv): args_files.append(Path(sys.argv[0]).with_suffix(".args")) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values args_file_parser = ArgumentParser() args_file_parser.add_argument(args_file_flag, type=str, action="append") # Use only remaining args for further parsing (remove the args_file_flag) cfg, args = args_file_parser.parse_known_args(args=args) cmd_args_file_paths = vars(cfg).get(args_file_flag.lstrip("-"), None) if cmd_args_file_paths: args_files.extend([Path(p) for p in cmd_args_file_paths]) file_args = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last args = file_args + args if args is not None else file_args + sys.argv[1:] namespace, remaining_args = self.parse_known_args(args=args) outputs = [] for dtype in self.dataclass_types: keys = {f.name for f in dataclasses.fields(dtype) if f.init} inputs = {k: v for k, v in vars(namespace).items() if k in keys} for k in keys: delattr(namespace, k) obj = dtype(**inputs) outputs.append(obj) if len(namespace.__dict__) > 0: # additional namespace. outputs.append(namespace) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {remaining_args}") return (*outputs,) def parse_dict(self, args: dict[str, Any], allow_extra_keys: bool = False) -> tuple[DataClass, ...]: """ Alternative helper method that does not use `argparse` at all, instead uses a dict and populating the dataclass types. Args: args (`dict`): dict containing config values allow_extra_keys (`bool`, *optional*, defaults to `False`): Defaults to False. If False, will raise an exception if the dict contains keys that are not parsed. Returns: Tuple consisting of: - the dataclass instances in the same order as they were passed to the initializer. """ unused_keys = set(args.keys()) outputs = [] for dtype in self.dataclass_types: keys = {f.name for f in dataclasses.fields(dtype) if f.init} inputs = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys()) obj = dtype(**inputs) outputs.append(obj) if not allow_extra_keys and unused_keys: raise ValueError(f"Some keys are not used by the HfArgumentParser: {sorted(unused_keys)}") return tuple(outputs) def parse_json_file( self, json_file: Union[str, os.PathLike], allow_extra_keys: bool = False ) -> tuple[DataClass, ...]: """ Alternative helper method that does not use `argparse` at all, instead loading a json file and populating the dataclass types. Args: json_file (`str` or `os.PathLike`): File name of the json file to parse allow_extra_keys (`bool`, *optional*, defaults to `False`): Defaults to False. If False, will raise an exception if the json file contains keys that are not parsed. Returns: Tuple consisting of: - the dataclass instances in the same order as they were passed to the initializer. """ with open(Path(json_file), encoding="utf-8") as open_json_file: data = json.loads(open_json_file.read()) outputs = self.parse_dict(data, allow_extra_keys=allow_extra_keys) return tuple(outputs) def parse_yaml_file( self, yaml_file: Union[str, os.PathLike], allow_extra_keys: bool = False ) -> tuple[DataClass, ...]: """ Alternative helper method that does not use `argparse` at all, instead loading a yaml file and populating the dataclass types. Args: yaml_file (`str` or `os.PathLike`): File name of the yaml file to parse allow_extra_keys (`bool`, *optional*, defaults to `False`): Defaults to False. If False, will raise an exception if the json file contains keys that are not parsed. Returns: Tuple consisting of: - the dataclass instances in the same order as they were passed to the initializer. """ outputs = self.parse_dict(yaml.safe_load(Path(yaml_file).read_text()), allow_extra_keys=allow_extra_keys) return tuple(outputs)
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/dependency_versions_table.py
src/transformers/dependency_versions_table.py
# THIS FILE HAS BEEN AUTOGENERATED. To update: # 1. modify the `_deps` dict in setup.py # 2. run `make deps_table_update`` deps = { "Pillow": "Pillow>=10.0.1,<=15.0", "accelerate": "accelerate>=1.1.0", "av": "av", "beautifulsoup4": "beautifulsoup4", "blobfile": "blobfile", "codecarbon": "codecarbon>=2.8.1", "cookiecutter": "cookiecutter==1.7.3", "datasets": "datasets>=2.15.0", "deepspeed": "deepspeed>=0.9.3", "diffusers": "diffusers", "dill": "dill<0.3.5", "evaluate": "evaluate>=0.4.6", "faiss-cpu": "faiss-cpu", "fastapi": "fastapi", "filelock": "filelock", "ftfy": "ftfy", "fugashi": "fugashi>=1.0", "GitPython": "GitPython<3.1.19", "hf-doc-builder": "hf-doc-builder>=0.3.0", "hf_xet": "hf_xet", "huggingface-hub": "huggingface-hub>=1.2.1,<2.0", "importlib_metadata": "importlib_metadata", "ipadic": "ipadic>=1.0.0,<2.0", "jinja2": "jinja2>=3.1.0", "jmespath": "jmespath>=1.0.1", "kenlm": "kenlm", "kernels": "kernels>=0.10.2,<0.11", "librosa": "librosa", "natten": "natten>=0.14.6,<0.15.0", "nltk": "nltk<=3.8.1", "num2words": "num2words", "numpy": "numpy>=1.17", "openai": "openai>=1.98.0", "opencv-python": "opencv-python", "optimum-benchmark": "optimum-benchmark>=0.3.0", "optuna": "optuna", "pandas": "pandas<2.3.0", "packaging": "packaging>=20.0", "parameterized": "parameterized>=0.9", "peft": "peft>=0.18.0", "phonemizer": "phonemizer", "protobuf": "protobuf", "psutil": "psutil", "pyyaml": "pyyaml>=5.1", "pydantic": "pydantic>=2", "pytest": "pytest>=7.2.0,<9.0.0", "pytest-asyncio": "pytest-asyncio>=1.2.0", "pytest-rerunfailures": "pytest-rerunfailures<16.0", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "pytest-order": "pytest-order", "python": "python>=3.10.0", "ray[tune]": "ray[tune]>=2.7.0", "regex": "regex!=2019.12.17", "requests": "requests", "rhoknp": "rhoknp>=1.1.0,<1.3.1", "rjieba": "rjieba", "rouge-score": "rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1", "ruff": "ruff==0.13.1", "sacrebleu": "sacrebleu>=1.4.12,<2.0.0", "sacremoses": "sacremoses", "safetensors": "safetensors>=0.4.3", "sagemaker": "sagemaker>=2.31.0", "schedulefree": "schedulefree>=1.2.6", "scikit-learn": "scikit-learn", "scipy": "scipy", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "starlette": "starlette", "sudachipy": "sudachipy>=0.6.6", "sudachidict_core": "sudachidict_core>=20220729", "tensorboard": "tensorboard", "timeout-decorator": "timeout-decorator", "tiktoken": "tiktoken", "timm": "timm>=1.0.20", "tokenizers": "tokenizers>=0.22.0,<=0.23.0", "torch": "torch>=2.2", "torchaudio": "torchaudio", "torchvision": "torchvision", "pyctcdecode": "pyctcdecode>=0.4.0", "tqdm": "tqdm>=4.27", "typer-slim": "typer-slim", "unidic": "unidic>=1.0.2", "unidic_lite": "unidic_lite>=1.0.7", "urllib3": "urllib3<2.0.0", "uvicorn": "uvicorn", "pytest-rich": "pytest-rich", "libcst": "libcst", "rich": "rich", "opentelemetry-api": "opentelemetry-api", "mistral-common[opencv]": "mistral-common[opencv]>=1.6.3", }
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/time_series_utils.py
src/transformers/time_series_utils.py
# Copyright 2023 The HuggingFace Inc. team. # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Time series distributional output classes and utilities. """ from collections.abc import Callable import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class AffineTransformed(TransformedDistribution): def __init__(self, base_distribution: Distribution, loc=None, scale=None, event_dim=0): self.scale = 1.0 if scale is None else scale self.loc = 0.0 if loc is None else loc super().__init__(base_distribution, [AffineTransform(loc=self.loc, scale=self.scale, event_dim=event_dim)]) @property def mean(self): """ Returns the mean of the distribution. """ return self.base_dist.mean * self.scale + self.loc @property def variance(self): """ Returns the variance of the distribution. """ return self.base_dist.variance * self.scale**2 @property def stddev(self): """ Returns the standard deviation of the distribution. """ return self.variance.sqrt() class ParameterProjection(nn.Module): def __init__( self, in_features: int, args_dim: dict[str, int], domain_map: Callable[..., tuple[torch.Tensor]], **kwargs ) -> None: super().__init__(**kwargs) self.args_dim = args_dim self.proj = nn.ModuleList([nn.Linear(in_features, dim) for dim in args_dim.values()]) self.domain_map = domain_map def forward(self, x: torch.Tensor) -> tuple[torch.Tensor]: params_unbounded = [proj(x) for proj in self.proj] return self.domain_map(*params_unbounded) class LambdaLayer(nn.Module): def __init__(self, function): super().__init__() self.function = function def forward(self, x, *args): return self.function(x, *args) class DistributionOutput: distribution_class: type in_features: int args_dim: dict[str, int] def __init__(self, dim: int = 1) -> None: self.dim = dim self.args_dim = {k: dim * self.args_dim[k] for k in self.args_dim} def _base_distribution(self, distr_args): if self.dim == 1: return self.distribution_class(*distr_args) else: return Independent(self.distribution_class(*distr_args), 1) def distribution( self, distr_args, loc: torch.Tensor | None = None, scale: torch.Tensor | None = None, ) -> Distribution: distr = self._base_distribution(distr_args) if loc is None and scale is None: return distr else: return AffineTransformed(distr, loc=loc, scale=scale, event_dim=self.event_dim) @property def event_shape(self) -> tuple: r""" Shape of each individual event contemplated by the distributions that this object constructs. """ return () if self.dim == 1 else (self.dim,) @property def event_dim(self) -> int: r""" Number of event dimensions, i.e., length of the `event_shape` tuple, of the distributions that this object constructs. """ return len(self.event_shape) @property def value_in_support(self) -> float: r""" A float that will have a valid numeric value when computing the log-loss of the corresponding distribution. By default 0.0. This value will be used when padding data series. """ return 0.0 def get_parameter_projection(self, in_features: int) -> nn.Module: r""" Return the parameter projection layer that maps the input to the appropriate parameters of the distribution. """ return ParameterProjection( in_features=in_features, args_dim=self.args_dim, domain_map=LambdaLayer(self.domain_map), ) def domain_map(self, *args: torch.Tensor): r""" Converts arguments to the right shape and domain. The domain depends on the type of distribution, while the correct shape is obtained by reshaping the trailing axis in such a way that the returned tensors define a distribution of the right event_shape. """ raise NotImplementedError() @staticmethod def squareplus(x: torch.Tensor) -> torch.Tensor: r""" Helper to map inputs to the positive orthant by applying the square-plus operation. Reference: https://twitter.com/jon_barron/status/1387167648669048833 """ return (x + torch.sqrt(torch.square(x) + 4.0)) / 2.0 class StudentTOutput(DistributionOutput): """ Student-T distribution output class. """ args_dim: dict[str, int] = {"df": 1, "loc": 1, "scale": 1} distribution_class: type = StudentT @classmethod def domain_map(cls, df: torch.Tensor, loc: torch.Tensor, scale: torch.Tensor): scale = cls.squareplus(scale).clamp_min(torch.finfo(scale.dtype).eps) df = 2.0 + cls.squareplus(df) return df.squeeze(-1), loc.squeeze(-1), scale.squeeze(-1) class NormalOutput(DistributionOutput): """ Normal distribution output class. """ args_dim: dict[str, int] = {"loc": 1, "scale": 1} distribution_class: type = Normal @classmethod def domain_map(cls, loc: torch.Tensor, scale: torch.Tensor): scale = cls.squareplus(scale).clamp_min(torch.finfo(scale.dtype).eps) return loc.squeeze(-1), scale.squeeze(-1) class NegativeBinomialOutput(DistributionOutput): """ Negative Binomial distribution output class. """ args_dim: dict[str, int] = {"total_count": 1, "logits": 1} distribution_class: type = NegativeBinomial @classmethod def domain_map(cls, total_count: torch.Tensor, logits: torch.Tensor): total_count = cls.squareplus(total_count) return total_count.squeeze(-1), logits.squeeze(-1) def _base_distribution(self, distr_args) -> Distribution: total_count, logits = distr_args if self.dim == 1: return self.distribution_class(total_count=total_count, logits=logits) else: return Independent(self.distribution_class(total_count=total_count, logits=logits), 1) # Overwrites the parent class method. We cannot scale using the affine # transformation since negative binomial should return integers. Instead # we scale the parameters. def distribution( self, distr_args, loc: torch.Tensor | None = None, scale: torch.Tensor | None = None ) -> Distribution: total_count, logits = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits))
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/modeling_flash_attention_utils.py
src/transformers/modeling_flash_attention_utils.py
# Copyright 2025 The Fairseq Authors and the HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import os from collections.abc import Callable from functools import partial from typing import Optional, TypedDict import torch import torch.nn.functional as F from .utils import ( is_flash_attn_2_available, is_flash_attn_3_available, is_flash_attn_greater_or_equal_2_10, is_torch_npu_available, is_torch_xpu_available, logging, ) logger = logging.get_logger(__name__) # TODO Deprecate when all models have the attention interface def flash_attn_supports_top_left_mask(): if is_flash_attn_3_available(): return False if is_flash_attn_2_available(): return not is_flash_attn_greater_or_equal_2_10() from .integrations.npu_flash_attention import is_npu_fa2_top_left_aligned_causal_mask return is_npu_fa2_top_left_aligned_causal_mask() # TODO Deprecate when all models have the attention interface def is_flash_attn_available(): return ( is_flash_attn_3_available() or is_flash_attn_2_available() or is_torch_npu_available() or is_torch_xpu_available() ) # `globals()` is not compatible with dynamo, hence we have do define them in global scope ourselves _loaded_implementation = None _flash_fn = None _flash_varlen_fn = None _pad_fn = None _unpad_fn = None # function that processes kwargs, generalized to handle any supported kwarg within the function _process_flash_kwargs_fn = None # exceptions where hf API doesn't match the original flash attention API _hf_api_to_flash_mapping = { "dropout": "dropout_p", "sliding_window": "window_size", } def _lazy_imports(implementation: Optional[str], attention_wrapper: Optional[Callable] = None): """ Lazy loads the respective flash attention implementations. Return: flash_attn_func: The base flash attention function. flash_attn_varlen_func: The flash attention function supporting variable sequence lengths, e.g. for padding-free training. pad_input: The function to pad inputs into one sequence and returning the respective kwargs. unpad_input: The function to unpad outputs based on the kwargs (from pad_input). """ is_fa2 = is_flash_attn_2_available() is_fa3 = is_flash_attn_3_available() pad_input, unpad_input = _pad_input, _unpad_input is_paged = implementation.startswith("paged|") implementation = implementation.split("|")[1] if is_paged else implementation if (implementation == "flash_attention_2" and is_fa2) or (implementation is None and is_fa2 and not is_fa3): from flash_attn import flash_attn_func, flash_attn_varlen_func from flash_attn.bert_padding import pad_input, unpad_input elif is_torch_npu_available(): # Package `flash-attn` is unavailable on Ascend NPU, which will cause ImportError # Flash-Attention2 related apis for Ascend NPU must be imported from `.integrations.npu_flash_attention` module from .integrations.npu_flash_attention import npu_flash_attn_func as flash_attn_func from .integrations.npu_flash_attention import npu_flash_attn_varlen_func as flash_attn_varlen_func else: if implementation == "flash_attention_3" or (implementation is None and is_fa3): from flash_attn_interface import flash_attn_func, flash_attn_varlen_func # Kernels fallback else: from .integrations.hub_kernels import load_and_register_attn_kernel # We want to explicitly register the name with `paged|` if found kernel_implementation = f"paged|{implementation}" if is_paged else implementation kernel = load_and_register_attn_kernel(kernel_implementation, attention_wrapper) flash_attn_func = getattr(kernel, "flash_attn_func", None) flash_attn_varlen_func = getattr(kernel, "flash_attn_varlen_func", None) if flash_attn_varlen_func is None: raise ValueError( f"Could not find the currently requested flash attention implementation at `{implementation}`." "Make sure that you request a valid kernel from the hub, e.g. `kernels-community/flash-attn2`." ) if flash_attn_func is None: logger.warning( f"The loaded flash attention implementation at `{implementation}` only supports varlen, i.e. " "it can only be used with continous batching and does not support the full functionality for " "the base transformers generation methods." ) return flash_attn_func, flash_attn_varlen_func, pad_input, unpad_input def _lazy_define_process_function(flash_function): """ Depending on the version and kernel some features are not supported. Due to limitations in `torch.compile`, we opt to statically type which (optional) kwarg parameters are supported within `_process_flash_attention_kwargs`. NOTE: While all supported kwargs are marked as `True`, everything else is marked as `False`. This might be confusing for kwargs that we use in any case, e.g. `is_causal`. """ flash_parameters = inspect.signature(flash_function).parameters process_parameters = inspect.signature(_process_flash_attention_kwargs).parameters supports_mapping = {} for param in process_parameters: fa_param = _hf_api_to_flash_mapping.get(param, param) supports_mapping[fa_param] = fa_param in flash_parameters return partial(_process_flash_attention_kwargs, supports_mapping=supports_mapping) def lazy_import_flash_attention(implementation: Optional[str], attention_wrapper: Optional[Callable] = None): """ Lazily import flash attention and return the respective functions + flags. NOTE: For fullgraph, this needs to be called before compile, while no fullgraph can work without preloading. See `load_and_register_attn_kernel` in `integrations.hub_kernels`. """ global _loaded_implementation if implementation is None and _loaded_implementation is None: raise ValueError("Could not find any flash attn implementation based on your environment.") global _flash_fn, _flash_varlen_fn, _pad_fn, _unpad_fn, _process_flash_kwargs_fn if implementation is not None and _loaded_implementation != implementation: _loaded_implementation = implementation _flash_fn, _flash_varlen_fn, _pad_fn, _unpad_fn = _lazy_imports(implementation, attention_wrapper) _process_flash_kwargs_fn = _lazy_define_process_function(_flash_varlen_fn) return (_flash_fn, _flash_varlen_fn, _pad_fn, _unpad_fn), _process_flash_kwargs_fn def lazy_import_paged_flash_attention(implementation: Optional[str]): """ Same as `lazy_import_flash_attention` but explicitly wrapping it with the paged implementation. """ from .integrations.flash_paged import paged_attention_forward (_, flash_attn_varlen_func, _, _), _ = lazy_import_flash_attention( implementation, attention_wrapper=paged_attention_forward ) return flash_attn_varlen_func def _index_first_axis(tensor, indices): """ A local implementation of the PyTorch indexing operation `tensor[indices]` on the first axis, after flattening the first two dimensions of the tensor. This is functionally equivalent to FA2's `index_first_axis` and replaces the need to import it. """ # The input tensor is expected to be of shape (batch, seq_len, ...). We flatten the first # two dimensions to get (total_tokens, ...) before indexing. reshaped_tensor = tensor.reshape(-1, *tensor.shape[2:]) return reshaped_tensor[indices] def _unpad_input(hidden_states, attention_mask, unused_mask=None): """ unpad_input function for flash attention variants that do not have them within their pkg themselves, e.g. fa3. Arguments: hidden_states: (batch, seqlen, ...) attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid. unused_mask: (batch, seqlen), bool / int, 1 means the element is allocated but unused. Return: hidden_states: (total_nnz, ...), where total_nnz = number of tokens selected in attention_mask + unused_mask. indices: (total_nnz), the indices of masked tokens from the flattened input sequence. cu_seqlens: (batch + 1), the cumulative sequence lengths, used to index into hidden_states. max_seqlen_in_batch: int seqused: (batch), returns the number of tokens selected in attention_mask + unused_mask. """ all_masks = (attention_mask + unused_mask) if unused_mask is not None else attention_mask seqlens_in_batch = all_masks.sum(dim=-1, dtype=torch.int32) used_seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) indices = torch.nonzero(all_masks.flatten(), as_tuple=False).flatten() max_seqlen_in_batch = seqlens_in_batch.max().item() cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) return ( _index_first_axis(hidden_states, indices), indices, cu_seqlens, max_seqlen_in_batch, used_seqlens_in_batch, ) def _pad_input(hidden_states, indices, batch, seqlen): """ pad_input function for flash attention variants that do not have them within their pkg themselves, e.g. fa3. Arguments: hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask. indices: (total_nnz), the indices that represent the non-masked tokens of the original padded input sequence. batch: int, batch size for the padded sequence. seqlen: int, maximum sequence length for the padded sequence. Return: hidden_states: (batch, seqlen, ...) """ dim = hidden_states.shape[1:] output = torch.zeros((batch * seqlen), *dim, device=hidden_states.device, dtype=hidden_states.dtype) output[indices] = hidden_states return output.view(batch, seqlen, *dim) def _get_unpad_data(attention_mask: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, int]: """ Retrieves indexing data required to repad unpadded (ragged) tensors. Arguments: attention_mask (`torch.Tensor`): Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid. Return: indices (`torch.Tensor`): The indices of non-masked tokens from the flattened input sequence. cu_seqlens (`torch.Tensor`): The cumulative sequence lengths, used to index into ragged (unpadded) tensors. `cu_seqlens` shape is (batch_size + 1,). max_seqlen_in_batch (`int`): Maximum sequence length in batch. """ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() # NOTE: Similar to the `.item()` in prepare_fa2_from_position_ids, with torch compile, # this might cause a graph break max_seqlen_in_batch = seqlens_in_batch.max().item() cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) return ( indices, cu_seqlens, max_seqlen_in_batch, ) def _upad_input( query_layer: torch.Tensor, key_layer: torch.Tensor, value_layer: torch.Tensor, attention_mask: torch.Tensor, query_length: int, unpad_input_func, ): """ Unpads query, key, and values tensors, using a single dimension for all tokens even though they belong to different batches. This function is used instead of `flash_attn.bert_padding.unpad_input` in order to avoid the recomputation of the same intermediary tensors for query, key, value tensors. Arguments: query_layer (`torch.Tensor`): Query state with padding. Shape: (batch_size, query_length, num_heads, head_dim). key_layer (`torch.Tensor`): Key state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim). value_layer (`torch.Tensor`): Value state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim). attention_mask (`torch.Tensor`): Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid. query_length (`int`): Target length. unpad_input_func: The function to use for unpadding the input tensors. Return: query_layer (`torch.Tensor`): Query state without padding. Shape: (total_target_length, num_heads, head_dim). key_layer (`torch.Tensor`): Key state with padding. Shape: (total_source_length, num_key_value_heads, head_dim). value_layer (`torch.Tensor`): Value state with padding. Shape: (total_source_length, num_key_value_heads, head_dim). indices_q (`torch.Tensor`): The indices of non-masked tokens from the flattened input target sequence. (cu_seqlens_q, cu_seqlens_k) (`tuple[int]`): The cumulative sequence lengths for the target (query) and source (key, value), used to index into ragged (unpadded) tensors. `cu_seqlens` shape is (batch_size + 1,). (max_seqlen_in_batch_q, max_seqlen_in_batch_k) (`tuple[int]`): Maximum sequence length in batch (`max_seqlen_in_batch_q` for the target sequence i.e. query, `max_seqlen_in_batch_k` for the source sequence i.e. key/value). """ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) # With static caches, the k/v states may be larger than the mask -> we need to slice them to avoid generating garbage # It's a bit of an anti-pattern, but otherwise we silently compute wrong attentions scores if key_layer.shape[1] > (seq_len := attention_mask.shape[-1]): key_layer, value_layer = key_layer[:, :seq_len, :, :], value_layer[:, :seq_len, :, :] batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape key_layer = _index_first_axis(key_layer, indices_k) value_layer = _index_first_axis(value_layer, indices_k) if query_length == kv_seq_len: query_layer = _index_first_axis(query_layer, indices_k) cu_seqlens_q = cu_seqlens_k max_seqlen_in_batch_q = max_seqlen_in_batch_k indices_q = indices_k elif query_length == 1: max_seqlen_in_batch_q = 1 cu_seqlens_q = torch.arange( batch_size + 1, dtype=torch.int32, device=query_layer.device ) # There is a memcpy here, that is very bad. indices_q = cu_seqlens_q[:-1] query_layer = query_layer.squeeze(1) else: # The -q_len: slice assumes left padding. attention_mask = attention_mask[:, -query_length:] query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q, *_ = unpad_input_func(query_layer, attention_mask) return ( query_layer, key_layer, value_layer, indices_q, (cu_seqlens_q, cu_seqlens_k), (max_seqlen_in_batch_q, max_seqlen_in_batch_k), ) def prepare_fa_kwargs_from_position_ids(position_ids): """ This function returns all the necessary kwargs to call `flash_attn_varlen_func` extracted from position_ids. Arguments: position_ids (`torch.Tensor`): Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid. Return: (cu_seqlens_q, cu_seqlens_k) (`tuple[int]`): The cumulative sequence lengths for the target (query) and source (key, value), used to index into ragged (unpadded) tensors. `cu_seqlens` shape is (batch_size + 1,). (max_seqlen_in_batch_q, max_seqlen_in_batch_k) (`tuple[int]`): Maximum sequence length in batch (`max_seqlen_in_batch_q` for the target sequence i.e. query, `max_seqlen_in_batch_k` for the source sequence i.e. key/value). """ tensor_kwargs = {"dtype": torch.int32, "device": position_ids.device} position_ids = position_ids.view(-1) indices_q = (position_ids == 0).nonzero().view(-1) cu_seq_lens_q = torch.cat( ( indices_q.to(**tensor_kwargs), torch.tensor(position_ids.size(), **tensor_kwargs), ) ) cu_seq_lens_k = cu_seq_lens_q # https://github.com/Dao-AILab/flash-attention/blob/2dd8078adc1d9b74e315ee99718c0dea0de8eeb6/flash_attn/flash_attn_interface.py#L1423-L1424 # We should use cu_seq_lens instead of position_ids to get the max length since position_ids is not always increasing # for some models (e.g. qwen2-vl). max_length_q = cu_seq_lens_q.diff().max() # NOTE: With torch compile, this will cause a graph break if you don't set # `TORCHDYNAMO_CAPTURE_SCALAR_OUTPUTS=1` in the environment or call # `torch._dynamo.config.capture_scalar_outputs = True` before doing the forward pass. # This is a limitation of flash attention API, as the function `flash_attn_varlen_func` # requires `max_length_q`, `max_length_k` to be passed as `int` and not `torch.Tensor`. max_length_q = max_length_q.item() max_length_k = max_length_q return (cu_seq_lens_q, cu_seq_lens_k), (max_length_q, max_length_k) def _prepare_from_posids(query, key, value, position_ids): """ This function returns necessary arguments to call `flash_attn_varlen_func`. All three query, key, value states will be flattened. Cumulative lengths of each examples in the batch will be extracted from position_ids. NOTE: ideally cumulative lengths should be prepared at the data collator stage Arguments: query (`torch.Tensor`): Query state with padding. Shape: (batch_size, query_length, num_heads, head_dim). key (`torch.Tensor`): Key state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim). value (`torch.Tensor`): Value state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim). position_ids (`torch.Tensor`): Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid. Return: query (`torch.Tensor`): Query state without padding. Shape: (total_target_length, num_heads, head_dim). key (`torch.Tensor`): Key state with padding. Shape: (total_source_length, num_key_value_heads, head_dim). value (`torch.Tensor`): Value state with padding. Shape: (total_source_length, num_key_value_heads, head_dim). (cu_seqlens_q, cu_seqlens_k) (`tuple[int]`): The cumulative sequence lengths for the target (query) and source (key, value), used to index into ragged (unpadded) tensors. `cu_seqlens` shape is (batch_size + 1,). (max_seqlen_in_batch_q, max_seqlen_in_batch_k) (`tuple[int]`): Maximum sequence length in batch (`max_seqlen_in_batch_q` for the target sequence i.e. query, `max_seqlen_in_batch_k` for the source sequence i.e. key/value). """ query = query.contiguous().view(-1, query.size(-2), query.size(-1)) key = key.contiguous().view(-1, key.size(-2), key.size(-1)) value = value.contiguous().view(-1, value.size(-2), value.size(-1)) (cu_seq_lens_q, cu_seq_lens_k), (max_length_q, max_length_k) = prepare_fa_kwargs_from_position_ids(position_ids) return (query, key, value, (cu_seq_lens_q, cu_seq_lens_k), (max_length_q, max_length_k)) def _is_packed_sequence(position_ids, batch_size): """ Check the position ids whether packed sequences are indicated or not 1. Position ids exist 2. Flattened sequences only are supported 3. Compile-friendly `not (torch.diff(position_ids, dim=-1) >= 0).all()`, i.e. we have multiple increasing sequences """ if position_ids is None: return False increasing_position_sequences = ( torch.arange(position_ids.shape[1], device=position_ids.device) + position_ids.min() ) return batch_size == 1 and (increasing_position_sequences - position_ids).abs().sum().bool() def fa_peft_integration_check( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, target_dtype: Optional[torch.dtype] = None, ): """ PEFT usually casts the layer norms in float32 for training stability reasons therefore the input hidden states gets silently casted in float32. Hence, we need cast them back in float16 / bfloat16 just to be sure everything works as expected. This might slowdown training & inference so it is recommended to not cast the LayerNorms! """ if target_dtype and q.dtype == torch.float32: logger.warning_once(f"Casting fp32 inputs back to {target_dtype} for flash-attn compatibility.") q, k, v = q.to(target_dtype), k.to(target_dtype), v.to(target_dtype) return q, k, v class FlashAttentionKwargs(TypedDict, total=False): """ Keyword arguments for Flash Attention with Compile. Attributes: cu_seq_lens_q (`torch.LongTensor`, *optional*) Gets cumulative sequence length for query state. cu_seq_lens_k (`torch.LongTensor`, *optional*) Gets cumulative sequence length for key state. max_length_q (`int`, *optional*): Maximum sequence length for query state. max_length_k (`int`, *optional*): Maximum sequence length for key state. """ cu_seq_lens_q: Optional[torch.LongTensor] cu_seq_lens_k: Optional[torch.LongTensor] max_length_q: Optional[int] max_length_k: Optional[int] def _process_flash_attention_kwargs( query_length: int, key_length: int, is_causal: bool, dropout: float = 0.0, softmax_scale: Optional[float] = None, sliding_window: Optional[int] = None, use_top_left_mask: bool = False, softcap: Optional[float] = None, deterministic: Optional[bool] = None, s_aux: Optional[torch.Tensor] = None, supports_mapping: Optional[dict[str, bool]] = None, **kwargs, ): """ Returns a set of kwargs that are passed down to the according flash attention function based on requested features and whether it is supported - depends on the version and kernel implementation which is dynamically configured at `lazy_import_flash_attention`. The (un)supported features can be inspected in `supports_mapping`, see `_lazy_define_process_function` for more details. Args: query_length (`int`): Length of the query states key_length (`int`): Length of the key states is_causal (`bool`): Whether we perform causal (decoder) attention or full attention. dropout (`float`): Attention dropout. softmax_scale (`float`, *optional*): The scaling of QK^T before applying softmax. Default to `1 / sqrt(head_dim)`. sliding_window (`int`, *optional*): The size of the sliding window, i.e. we look at a max of `sliding_window` tokens back. use_top_left_mask (`bool`): Deprecated behavior of older versions of flash attention requiring different masking. softcap (`float`, *optional*): Softcap for the attention logits, used e.g. in gemma2. deterministic (`bool`, *optional*): Determines if the deterministic option introduced in flash_attn>=2.4.1 is enabled. s_aux (`torch.Tensor`, *optional*): Attention sink auxiliary that adds a `bias` to the attention calculation via an additional head. Return: flash_kwargs (`dict`): A dict of kwargs that are requested and supported. """ flash_kwargs = { "causal": is_causal and not (use_top_left_mask and query_length == 1), "softmax_scale": softmax_scale, } if supports_mapping["dropout_p"]: flash_kwargs["dropout_p"] = dropout if supports_mapping["window_size"] and sliding_window is not None and key_length > sliding_window: # The flash attention API sets inclusive boundaries, i.e. (4, 0) would take 4 tokens to the left # and the current token for a total size of 5. However, we usually define our window sizes by # their total window size (when causal). Encoder models as of now seldom use SWA and when they # do, they have a custom workaround (e.g. ModernBERT) which would align with this symmetric logic, i.e. # for a total of `2*sliding_window + 1`. flash_kwargs["window_size"] = (sliding_window - 1, sliding_window - 1) if supports_mapping["deterministic"]: flash_kwargs["deterministic"] = ( deterministic if deterministic is not None else os.getenv("FLASH_ATTENTION_DETERMINISTIC", "0") == "1" ) if supports_mapping["softcap"] and softcap is not None: flash_kwargs["softcap"] = softcap # Only within kernel implementation atm if supports_mapping["s_aux"] and s_aux is not None: flash_kwargs["s_aux"] = s_aux return flash_kwargs def _flash_attention_forward( query_states: torch.Tensor, key_states: torch.Tensor, value_states: torch.Tensor, attention_mask: Optional[torch.Tensor], query_length: int, is_causal: bool, dropout: float = 0.0, position_ids: Optional[torch.Tensor] = None, softmax_scale: Optional[float] = None, sliding_window: Optional[int] = None, use_top_left_mask: bool = False, softcap: Optional[float] = None, deterministic: Optional[bool] = None, cu_seq_lens_q: Optional[torch.LongTensor] = None, cu_seq_lens_k: Optional[torch.LongTensor] = None, max_length_q: Optional[int] = None, max_length_k: Optional[int] = None, target_dtype: Optional[torch.dtype] = None, attn_implementation: Optional[str] = None, **kwargs, ): """ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token first unpad the input, then computes the attention scores and pad the final attention scores. (Optional) kwargs are described further in `_process_flash_attention_kwargs` and `FlashAttentionKwargs`. Args: query_states (`torch.Tensor`): Input query states to be passed to Flash Attention API key_states (`torch.Tensor`): Input key states to be passed to Flash Attention API value_states (`torch.Tensor`): Input value states to be passed to Flash Attention API attention_mask (`torch.Tensor`, *optional*): The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the position of padding tokens and 1 for the position of non-padding tokens. attn_implementation (`str`, *optional*): The attention implementation to use. If None, will default to the one based on the environment. """ (flash_fn, flash_varlen_fn, pad_fn, unpad_fn), process_flash_kwargs_fn = lazy_import_flash_attention( attn_implementation ) # PEFT possibly silently casts tensors to fp32, this potentially reconverts to correct dtype or is a no op query_states, key_states, value_states = fa_peft_integration_check( query_states, key_states, value_states, target_dtype ) # Extract the flash attention kwargs that have been requested (and are supported by the implementation) flash_kwargs = process_flash_kwargs_fn( query_length=query_length, key_length=key_states.size(1), is_causal=is_causal, dropout=dropout, softmax_scale=softmax_scale, sliding_window=sliding_window, use_top_left_mask=use_top_left_mask, softcap=softcap, deterministic=deterministic, **kwargs, ) # We will use `flash_varlen_fn` to prevent cross-example attention and also allow padding free approach under two cases: # Case 1. If position ids is provided and the position ids indicate packed sequences, see `_is_packed_sequence`. # Case 2. Some models pass directly pre-computed `cu_seqlens` so we don't need to infer it from position ids. It is safe to # use `flash_varlen_fn` knowing we already have all necessary the kwargs. # # NOTE: it is user's responsibility to take care of flattening `position_ids` if that's needed by the model. # See #39121 for more information. is_fa_with_position_ids = _is_packed_sequence(position_ids, batch_size=query_states.size(0)) is_fa_with_varlen_kwargs = all( kwarg is not None for kwarg in (cu_seq_lens_q, cu_seq_lens_k, max_length_q, max_length_k) ) # Contains at least one padding token in the sequence if attention_mask is not None: q, k, v, indices_q, (cu_seq_lens_q, cu_seq_lens_k), (max_length_q, max_length_k) = _upad_input( query_states, key_states, value_states, attention_mask, query_length, unpad_fn ) # TODO for now this is required to work with # https://huggingface.co/kernels-community/metal-flash-sdpa/blob/main/torch-ext/metal_flash_sdpa/__init__.py if "mps" in str(q.device): cu_seq_lens_k = cu_seq_lens_k.clone() out_unpad = flash_varlen_fn( q, k, v, cu_seqlens_q=cu_seq_lens_q, cu_seqlens_k=cu_seq_lens_k, max_seqlen_q=max_length_q, max_seqlen_k=max_length_k, **flash_kwargs, ) if isinstance(out_unpad, tuple): out_unpad = out_unpad[0] out = pad_fn(out_unpad, indices_q, query_states.size(0), query_length) # Padding free, i.e. sequences flattened into one total sequence elif is_fa_with_varlen_kwargs or is_fa_with_position_ids: if cu_seq_lens_q is None or cu_seq_lens_k is None: q, k, v, (cu_seq_lens_q, cu_seq_lens_k), (max_length_q, max_length_k) = _prepare_from_posids( query_states, key_states, value_states, position_ids ) else: q = query_states.reshape(-1, query_states.size(-2), query_states.size(-1)) k = key_states.reshape(-1, key_states.size(-2), key_states.size(-1)) v = value_states.reshape(-1, value_states.size(-2), value_states.size(-1)) # TODO for now this is required to work with # https://huggingface.co/kernels-community/metal-flash-sdpa/blob/main/torch-ext/metal_flash_sdpa/__init__.py if "mps" in str(q.device): cu_seq_lens_k = cu_seq_lens_k.clone() out = flash_varlen_fn( q, k, v, cu_seqlens_q=cu_seq_lens_q, cu_seqlens_k=cu_seq_lens_k, max_seqlen_q=max_length_q, max_seqlen_k=max_length_k, **flash_kwargs, ) if isinstance(out, tuple): out = out[0] out = out.view(query_states.size(0), -1, out.size(-2), out.size(-1)) # No padding else: out = flash_fn(query_states, key_states, value_states, **flash_kwargs) if isinstance(out, tuple): out = out[0] return out
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/trainer_pt_utils.py
src/transformers/trainer_pt_utils.py
# Copyright 2020-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Torch utilities for the Trainer class. """ import copy import datetime import io import json import math import os import re import sys import warnings from collections.abc import Iterator, Mapping from contextlib import contextmanager from dataclasses import dataclass, field from itertools import chain from logging import StreamHandler from typing import Any import numpy as np import torch import torch.distributed as dist from torch import nn from torch.utils.data import Dataset, IterableDataset, RandomSampler, Sampler from torch.utils.data.distributed import DistributedSampler from .integrations.deepspeed import is_deepspeed_zero3_enabled from .tokenization_utils_base import BatchEncoding from .utils import ( is_sagemaker_mp_enabled, is_torch_available, is_torch_xla_available, is_training_run_on_sagemaker, logging, ) if is_training_run_on_sagemaker(): logging.add_handler(StreamHandler(sys.stdout)) if is_torch_xla_available(): import torch_xla.runtime as xr if is_torch_available(): from torch.optim.lr_scheduler import LRScheduler logger = logging.get_logger(__name__) def get_dataloader_sampler(dataloader): if hasattr(dataloader, "batch_sampler") and dataloader.batch_sampler is not None: return get_dataloader_sampler(dataloader.batch_sampler) elif hasattr(dataloader, "sampler"): return dataloader.sampler def atleast_1d(tensor_or_array: torch.Tensor | np.ndarray): if isinstance(tensor_or_array, torch.Tensor): if hasattr(torch, "atleast_1d"): tensor_or_array = torch.atleast_1d(tensor_or_array) elif tensor_or_array.ndim < 1: tensor_or_array = tensor_or_array[None] else: tensor_or_array = np.atleast_1d(tensor_or_array) return tensor_or_array def torch_pad_and_concatenate(tensor1, tensor2, padding_index=-100): """Concatenates `tensor1` and `tensor2` on first axis, applying padding on the second if necessary.""" tensor1 = atleast_1d(tensor1) tensor2 = atleast_1d(tensor2) if len(tensor1.shape) == 1 or tensor1.shape[1] == tensor2.shape[1]: return torch.cat((tensor1, tensor2), dim=0) # Let's figure out the new shape new_shape = (tensor1.shape[0] + tensor2.shape[0], max(tensor1.shape[1], tensor2.shape[1])) + tensor1.shape[2:] # Now let's fill the result tensor result = tensor1.new_full(new_shape, padding_index) result[: tensor1.shape[0], : tensor1.shape[1]] = tensor1 result[tensor1.shape[0] :, : tensor2.shape[1]] = tensor2 return result def numpy_pad_and_concatenate(array1, array2, padding_index=-100): """Concatenates `array1` and `array2` on first axis, applying padding on the second if necessary.""" array1 = atleast_1d(array1) array2 = atleast_1d(array2) if len(array1.shape) == 1 or array1.shape[1] == array2.shape[1]: return np.concatenate((array1, array2), axis=0) # Let's figure out the new shape new_shape = (array1.shape[0] + array2.shape[0], max(array1.shape[1], array2.shape[1])) + array1.shape[2:] # Now let's fill the result tensor result = np.full_like(array1, padding_index, shape=new_shape) result[: array1.shape[0], : array1.shape[1]] = array1 result[array1.shape[0] :, : array2.shape[1]] = array2 return result def nested_concat(tensors, new_tensors, padding_index=-100): """ Concat the `new_tensors` to `tensors` on the first dim and pad them on the second if needed. Works for tensors or nested list/tuples/dict of tensors. """ if not (isinstance(tensors, torch.Tensor) and isinstance(new_tensors, torch.Tensor)): assert type(tensors) is type(new_tensors), ( f"Expected `tensors` and `new_tensors` to have the same type but found {type(tensors)} and {type(new_tensors)}." ) if isinstance(tensors, (list, tuple)): return type(tensors)(nested_concat(t, n, padding_index=padding_index) for t, n in zip(tensors, new_tensors)) elif isinstance(tensors, torch.Tensor): return torch_pad_and_concatenate(tensors, new_tensors, padding_index=padding_index) elif isinstance(tensors, Mapping): return type(tensors)( {k: nested_concat(t, new_tensors[k], padding_index=padding_index) for k, t in tensors.items()} ) elif isinstance(tensors, np.ndarray): return numpy_pad_and_concatenate(tensors, new_tensors, padding_index=padding_index) else: raise TypeError(f"Unsupported type for concatenation: got {type(tensors)}") def find_batch_size(tensors): """ Find the first dimension of a tensor in a nested list/tuple/dict of tensors. """ if isinstance(tensors, (list, tuple)): for t in tensors: result = find_batch_size(t) if result is not None: return result elif isinstance(tensors, Mapping): for value in tensors.values(): result = find_batch_size(value) if result is not None: return result elif isinstance(tensors, (torch.Tensor, np.ndarray)): return tensors.shape[0] if len(tensors.shape) >= 1 else None def nested_numpify(tensors): "Numpify `tensors` (even if it's a nested list/tuple/dict of tensors)." if isinstance(tensors, (list, tuple)): return type(tensors)(nested_numpify(t) for t in tensors) if isinstance(tensors, Mapping): return type(tensors)({k: nested_numpify(t) for k, t in tensors.items()}) t = tensors.cpu() if t.dtype == torch.bfloat16: # As of Numpy 1.21.4, NumPy does not support bfloat16 (see # https://github.com/numpy/numpy/blob/a47ecdea856986cd60eabbd53265c2ca5916ad5d/doc/source/user/basics.types.rst ). # Until Numpy adds bfloat16, we must convert float32. t = t.to(torch.float32) return t.numpy() def nested_detach(tensors): "Detach `tensors` (even if it's a nested list/tuple/dict of tensors)." if isinstance(tensors, (list, tuple)): return type(tensors)(nested_detach(t) for t in tensors) elif isinstance(tensors, Mapping): return type(tensors)({k: nested_detach(t) for k, t in tensors.items()}) return tensors.detach() if isinstance(tensors, torch.Tensor) else tensors def nested_xla_mesh_reduce(tensors, name): if is_torch_xla_available(): import torch_xla.core.xla_model as xm if isinstance(tensors, (list, tuple)): return type(tensors)(nested_xla_mesh_reduce(t, f"{name}_{i}") for i, t in enumerate(tensors)) if isinstance(tensors, Mapping): return type(tensors)( {k: nested_xla_mesh_reduce(t, f"{name}_{i}") for i, (k, t) in enumerate(tensors.items())} ) tensors = atleast_1d(tensors) return xm.mesh_reduce(name, tensors, torch.cat) else: raise ImportError("Torch xla must be installed to use `nested_xla_mesh_reduce`") def distributed_concat(tensor: Any, num_total_examples: int | None = None) -> Any: try: if isinstance(tensor, (tuple, list)): return type(tensor)(distributed_concat(t, num_total_examples) for t in tensor) if isinstance(tensor, Mapping): return type(tensor)({k: distributed_concat(t, num_total_examples) for k, t in tensor.items()}) tensor = atleast_1d(tensor).contiguous() output_tensors = [tensor.clone() for _ in range(dist.get_world_size())] dist.all_gather(output_tensors, tensor) concat = torch.cat(output_tensors, dim=0) # truncate the dummy elements added by SequentialDistributedSampler if num_total_examples is not None: concat = concat[:num_total_examples] return concat except AssertionError: raise AssertionError("Not currently using distributed training") def distributed_broadcast_scalars( scalars: list[int | float], num_total_examples: int | None = None, device: torch.device | None = torch.device("cuda"), ) -> torch.Tensor: try: tensorized_scalar = torch.tensor(scalars, device=device) output_tensors = [tensorized_scalar.clone() for _ in range(dist.get_world_size())] dist.all_gather(output_tensors, tensorized_scalar) concat = torch.cat(output_tensors, dim=0) # truncate the dummy elements added by SequentialDistributedSampler if num_total_examples is not None: concat = concat[:num_total_examples] return concat except AssertionError: raise AssertionError("Not currently using distributed training") def reissue_pt_warnings(caught_warnings): # Reissue warnings if len(caught_warnings) > 1: for w in caught_warnings: if w.category is not UserWarning: warnings.warn(w.message, w.category) @contextmanager def torch_distributed_zero_first(local_rank: int): """ Decorator to make all processes in distributed training wait for each local_master to do something. Args: local_rank (`int`): The rank of the local process. """ if local_rank not in [-1, 0]: dist.barrier() yield if local_rank == 0: dist.barrier() class DistributedSamplerWithLoop(DistributedSampler): """ Like a torch.utils.data.distributed.DistributedSampler` but loops at the end back to the beginning of the shuffled samples to make each process have a round multiple of batch_size samples. Args: dataset (`torch.utils.data.Dataset`): Dataset used for sampling. batch_size (`int`): The batch size used with this sampler kwargs (`dict[str, Any]`, *optional*): All other keyword arguments passed to `DistributedSampler`. """ def __init__(self, dataset, batch_size, **kwargs): super().__init__(dataset, **kwargs) self.batch_size = batch_size def __iter__(self): indices = list(super().__iter__()) remainder = 0 if len(indices) % self.batch_size == 0 else self.batch_size - len(indices) % self.batch_size # DistributedSampler already added samples from the beginning to make the number of samples a round multiple # of the world size, so we skip those. start_remainder = 1 if self.rank < len(self.dataset) % self.num_replicas else 0 indices += indices[start_remainder : start_remainder + remainder] return iter(indices) class EvalLoopContainer: """ Container to store intermediate results of evaluation loop. Args: do_nested_concat (`bool`, *optional*, defaults to `True`): If set to `True`, each iteration will recursively concatenate a new object containing tensors to the existing stored tensors, provided that the structure of the existing object and the new one are identical. If set to `False`, all newly added tensors will be stored in a list. padding_index (`int`, *optional*, defaults to -100): Value used to pad tensors of different shapes when `do_nested_concat=True`. """ def __init__(self, do_nested_concat: bool = True, padding_index: int = -100): self.do_nested_concat = do_nested_concat self.padding_index = padding_index self.tensors = None self.arrays = None def add(self, tensors) -> None: """Add tensors to the stored objects. If `do_nested_concat=True`, the tensors will be concatenated recursively.""" if self.tensors is None: self.tensors = tensors if self.do_nested_concat else [tensors] elif self.do_nested_concat: self.tensors = nested_concat(self.tensors, tensors, padding_index=self.padding_index) else: self.tensors.append(tensors) def to_cpu_and_numpy(self) -> None: """Move tensors in stored objects to CPU and convert them to numpy arrays.""" # Check if we have something to add, if not just return if self.tensors is None: return new_arrays = nested_numpify(self.tensors) if self.arrays is None: self.arrays = new_arrays elif self.do_nested_concat: self.arrays = nested_concat(self.arrays, new_arrays, padding_index=self.padding_index) else: self.arrays.extend(new_arrays) # reset device tensors after adding to cpu self.tensors = None def get_arrays(self): """Returns the numpified and moved to CPU stored objects.""" self.to_cpu_and_numpy() return self.arrays def get_tpu_sampler(dataset: torch.utils.data.Dataset, batch_size: int): if xr.world_size() <= 1: return RandomSampler(dataset) return DistributedSampler(dataset, num_replicas=xr.world_size(), rank=xr.global_ordinal()) def nested_new_like(arrays, num_samples, padding_index=-100): """Create the same nested structure as `arrays` with a first dimension always at `num_samples`.""" if isinstance(arrays, (list, tuple)): return type(arrays)(nested_new_like(x, num_samples) for x in arrays) return np.full_like(arrays, padding_index, shape=(num_samples, *arrays.shape[1:])) def expand_like(arrays, new_seq_length, padding_index=-100): """Expand the `arrays` so that the second dimension grows to `new_seq_length`. Uses `padding_index` for padding.""" result = np.full_like(arrays, padding_index, shape=(arrays.shape[0], new_seq_length) + arrays.shape[2:]) result[:, : arrays.shape[1]] = arrays return result def nested_truncate(tensors, limit): "Truncate `tensors` at `limit` (even if it's a nested list/tuple/dict of tensors)." if isinstance(tensors, (list, tuple)): return type(tensors)(nested_truncate(t, limit) for t in tensors) if isinstance(tensors, Mapping): return type(tensors)({k: nested_truncate(t, limit) for k, t in tensors.items()}) return tensors[:limit] @dataclass class LabelSmoother: """ Adds label-smoothing on a pre-computed output from a Transformers model. Args: epsilon (`float`, *optional*, defaults to 0.1): The label smoothing factor. ignore_index (`int`, *optional*, defaults to -100): The index in the labels to ignore when computing the loss. """ epsilon: float = 0.1 ignore_index: int = -100 def __call__(self, model_output, labels, shift_labels=False): logits = model_output["logits"] if isinstance(model_output, dict) else model_output[0] if shift_labels: logits = logits[..., :-1, :].contiguous() labels = labels[..., 1:].contiguous() log_probs = -nn.functional.log_softmax(logits, dim=-1) if labels.dim() == log_probs.dim() - 1: labels = labels.unsqueeze(-1) padding_mask = labels.eq(self.ignore_index) # In case the ignore_index is -100, the gather will fail, so we replace labels by 0. The padding_mask # will ignore them in any case. labels = torch.clamp(labels, min=0) nll_loss = log_probs.gather(dim=-1, index=labels) # works for fp16 input tensor too, by internally upcasting it to fp32 smoothed_loss = log_probs.sum(dim=-1, keepdim=True, dtype=torch.float32) nll_loss.masked_fill_(padding_mask, 0.0) smoothed_loss.masked_fill_(padding_mask, 0.0) # Take the mean over the label dimensions, then divide by the number of active elements (i.e. not-padded): num_active_elements = padding_mask.numel() - padding_mask.long().sum() nll_loss = nll_loss.sum() / num_active_elements smoothed_loss = smoothed_loss.sum() / (num_active_elements * log_probs.shape[-1]) return (1 - self.epsilon) * nll_loss + self.epsilon * smoothed_loss def get_length_grouped_indices(lengths, batch_size, mega_batch_mult=None, generator=None): """ Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar lengths. To do this, the indices are: - randomly permuted - grouped in mega-batches of size `mega_batch_mult * batch_size` - sorted by length in each mega-batch The result is the concatenation of all mega-batches, with the batch of `batch_size` containing the element of maximum length placed first, so that an OOM happens sooner rather than later. """ # Default for mega_batch_mult: 50 or the number to get 4 megabatches, whichever is smaller. if mega_batch_mult is None: mega_batch_mult = min(len(lengths) // (batch_size * 4), 50) # Just in case, for tiny datasets if mega_batch_mult == 0: mega_batch_mult = 1 # We need to use torch for the random part as a distributed sampler will set the random seed for torch. indices = torch.randperm(len(lengths), generator=generator) megabatch_size = mega_batch_mult * batch_size megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)] megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches] # The rest is to get the biggest batch first. # Since each megabatch is sorted by descending length, the longest element is the first megabatch_maximums = [lengths[megabatch[0]] for megabatch in megabatches] max_idx = torch.argmax(torch.tensor(megabatch_maximums)).item() # Switch to put the longest element in first position megabatches[0][0], megabatches[max_idx][0] = megabatches[max_idx][0], megabatches[0][0] return [i for megabatch in megabatches for i in megabatch] class LengthGroupedSampler(Sampler): r""" Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while keeping a bit of randomness. """ def __init__( self, batch_size: int, dataset: Dataset | None = None, lengths: list[int] | None = None, model_input_name: str | None = None, generator=None, ): if dataset is None and lengths is None: raise ValueError("One of dataset and lengths must be provided.") self.batch_size = batch_size if lengths is None: model_input_name = model_input_name if model_input_name is not None else "input_ids" if not isinstance(dataset[0], (dict, BatchEncoding)) or model_input_name not in dataset[0]: raise ValueError( "Can only automatically infer lengths for datasets whose items are dictionaries with an " f"'{model_input_name}' key." ) lengths = [len(feature[model_input_name]) for feature in dataset] elif isinstance(lengths, torch.Tensor): logger.info( "If lengths is a torch.Tensor, LengthGroupedSampler will be slow. Converting lengths to list[int]..." ) lengths = lengths.tolist() self.lengths = lengths self.generator = generator def __len__(self): return len(self.lengths) def __iter__(self): indices = get_length_grouped_indices(self.lengths, self.batch_size, generator=self.generator) return iter(indices) class DistributedLengthGroupedSampler(DistributedSampler): r""" Distributed Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while keeping a bit of randomness. """ # Copied and adapted from PyTorch DistributedSampler. def __init__( self, batch_size: int, dataset: Dataset | None = None, num_replicas: int | None = None, rank: int | None = None, seed: int = 0, drop_last: bool = False, lengths: list[int] | None = None, model_input_name: str | None = None, ): if dataset is None and lengths is None: raise ValueError("One of dataset and lengths must be provided.") if num_replicas is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") num_replicas = dist.get_world_size() if rank is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") rank = dist.get_rank() self.batch_size = batch_size self.num_replicas = num_replicas self.rank = rank self.epoch = 0 self.drop_last = drop_last if lengths is None: model_input_name = model_input_name if model_input_name is not None else "input_ids" if not isinstance(dataset[0], (dict, BatchEncoding)) or model_input_name not in dataset[0]: raise ValueError( "Can only automatically infer lengths for datasets whose items are dictionaries with an " f"'{model_input_name}' key." ) lengths = [len(feature[model_input_name]) for feature in dataset] elif isinstance(lengths, torch.Tensor): logger.info( "If lengths is a torch.Tensor, DistributedLengthGroupedSampler will be slow. Converting lengths to" " list[int]..." ) lengths = lengths.tolist() self.lengths = lengths # If the dataset length is evenly divisible by # of replicas, then there # is no need to drop any data, since the dataset will be split equally. if self.drop_last and len(self.lengths) % self.num_replicas != 0: # Split to nearest available length that is evenly divisible. # This is to ensure each rank receives the same amount of data when # using this Sampler. self.num_samples = math.ceil((len(self.lengths) - self.num_replicas) / self.num_replicas) else: self.num_samples = math.ceil(len(self.lengths) / self.num_replicas) self.total_size = self.num_samples * self.num_replicas self.seed = seed def __iter__(self) -> Iterator: # Deterministically shuffle based on epoch and seed g = torch.Generator() g.manual_seed(self.seed + self.epoch) indices = get_length_grouped_indices(self.lengths, self.batch_size, generator=g) if not self.drop_last: # add extra samples to make it evenly divisible indices += indices[: (self.total_size - len(indices))] else: # remove tail of data to make it evenly divisible indices = indices[: self.total_size] assert len(indices) == self.total_size # subsample indices = indices[self.rank : self.total_size : self.num_replicas] assert len(indices) == self.num_samples return iter(indices) class ShardSampler(Sampler): """ Sampler that shards batches between several processes. Dispatches indices batch by batch: on 2 processes with batch size 4, the first two batches are `[0, 1, 2, 3, 4, 5, 6, 7]` and `[8, 9, 10, 11, 12, 13, 14, 15]`, which shard into `[0, 1, 2, 3]` and `[8, 9, 10, 11]` for GPU-0 and `[4, 5, 6, 7]` and `[12, 13, 14, 15]` for GPU-1. The sampler thus yields `[0, 1, 2, 3, 8, 9, 10, 11]` on GPU-0 and `[4, 5, 6, 7, 12, 13, 14, 15]` on GPU-1. """ def __init__( self, dataset: Dataset, batch_size: int = 1, drop_last: bool = False, num_processes: int = 1, process_index: int = 0, ): self.dataset = dataset self.batch_size = batch_size self.drop_last = drop_last self.num_processes = num_processes self.process_index = process_index self.total_batch_size = total_batch_size = batch_size * num_processes num_batches = len(dataset) // total_batch_size if drop_last else math.ceil(len(dataset) / total_batch_size) self.total_num_samples = num_batches * total_batch_size def __iter__(self): indices = list(range(len(self.dataset))) # Add extra samples to make it evenly divisible. While loop is there in the edge case we have a tiny dataset # and it needs to be done several times. while len(indices) < self.total_num_samples: indices += indices[: (self.total_num_samples - len(indices))] result = [] for batch_start in range(self.batch_size * self.process_index, self.total_num_samples, self.total_batch_size): result += indices[batch_start : batch_start + self.batch_size] return iter(result) def __len__(self): # Each shard only sees a fraction of total_num_samples. return self.total_num_samples // self.num_processes class IterableDatasetShard(IterableDataset): """ Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will always yield a number of samples that is a round multiple of the actual batch size (which is `batch_size x num_processes`). Depending on the value of the `drop_last` attribute, it will either stop the iteration at the first batch that would be too small or loop with indices from the beginning. On two processes with an iterable dataset yielding of `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]` with a batch size of 2: - the shard on process 0 will yield `[0, 1, 4, 5, 8, 9]` so will see batches `[0, 1]`, `[4, 5]`, `[8, 9]` - the shard on process 1 will yield `[2, 3, 6, 7, 10, 11]` so will see batches `[2, 3]`, `[6, 7]`, `[10, 11]` <Tip warning={true}> If your IterableDataset implements some randomization that needs to be applied the same way on all processes (for instance, a shuffling), you should use a `torch.Generator` in a `generator` attribute of the `dataset` to generate your random numbers and call the [`~trainer_pt_utils.IterableDatasetShard.set_epoch`] method of this object. It will set the seed of this `generator` to `seed + epoch` on all processes before starting the iteration. Alternatively, you can also implement a `set_epoch()` method in your iterable dataset to deal with this. </Tip> Args: dataset (`torch.utils.data.IterableDataset`): The batch sampler to split in several shards. batch_size (`int`, *optional*, defaults to 1): The size of the batches per shard. drop_last (`bool`, *optional*, defaults to `False`): Whether or not to drop the last incomplete batch or complete the last batches by using the samples from the beginning. num_processes (`int`, *optional*, defaults to 1): The number of processes running concurrently. process_index (`int`, *optional*, defaults to 0): The index of the current process. seed (`int`, *optional*, defaults to 0): A random seed that will be used for the random number generation in [`~trainer_pt_utils.IterableDatasetShard.set_epoch`]. """ def __init__( self, dataset: IterableDataset, batch_size: int = 1, drop_last: bool = False, num_processes: int = 1, process_index: int = 0, seed: int = 0, ): self.dataset = dataset self.batch_size = batch_size self.drop_last = drop_last self.num_processes = num_processes self.process_index = process_index self.seed = seed self.epoch = 0 self.num_examples = 0 def set_epoch(self, epoch): self.epoch = epoch if hasattr(self.dataset, "set_epoch"): self.dataset.set_epoch(epoch) def __iter__(self): self.num_examples = 0 if ( not hasattr(self.dataset, "set_epoch") and hasattr(self.dataset, "generator") and isinstance(self.dataset.generator, torch.Generator) ): self.dataset.generator.manual_seed(self.seed + self.epoch) real_batch_size = self.batch_size * self.num_processes process_slice = range(self.process_index * self.batch_size, (self.process_index + 1) * self.batch_size) first_batch = None current_batch = [] for element in self.dataset: self.num_examples += 1 current_batch.append(element) # Wait to have a full batch before yielding elements. if len(current_batch) == real_batch_size: for i in process_slice: yield current_batch[i] if first_batch is None: first_batch = current_batch.copy() current_batch = [] # Finished if drop_last is True, otherwise complete the last batch with elements from the beginning. if not self.drop_last and len(current_batch) > 0: if first_batch is None: first_batch = current_batch.copy() while len(current_batch) < real_batch_size: current_batch += first_batch for i in process_slice: yield current_batch[i] def __len__(self): # Will raise an error if the underlying dataset is not sized. if self.drop_last: return (len(self.dataset) // (self.batch_size * self.num_processes)) * self.batch_size else: return math.ceil(len(self.dataset) / (self.batch_size * self.num_processes)) * self.batch_size # In order to keep `trainer.py` compact and easy to understand, place any secondary PT Trainer # helper methods here def _get_learning_rate(self): if self.is_deepspeed_enabled: # with deepspeed's fp16 and dynamic loss scale enabled the optimizer/scheduler steps may # not run for the first few dozen steps while loss scale is too large, and thus during # that time `get_last_lr` will fail if called during that warm up stage, so work around it: try: last_lr = self.lr_scheduler.get_last_lr()[0] except AssertionError as e: if "need to call step" in str(e): logger.warning("tried to get lr value before scheduler/optimizer started stepping, returning lr=0") last_lr = 0 else: raise else: if isinstance(self.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau): last_lr = self.optimizer.param_groups[0]["lr"] else: last_lr = self.lr_scheduler.get_last_lr()[0] if torch.is_tensor(last_lr): last_lr = last_lr.item() return last_lr def _secs2timedelta(secs): """ Convert seconds to hh:mm:ss.msec, msecs rounded to 2 decimal places. """ msec = int(abs(secs - int(secs)) * 100) return f"{datetime.timedelta(seconds=int(secs))}.{msec:02d}" def metrics_format(metrics: dict[str, float]) -> dict[str, float]: """ Reformat Trainer metrics values to a human-readable format. Args: metrics (`dict[str, float]`): The metrics returned from train/evaluate/predict Returns: metrics (`dict[str, float]`): The reformatted metrics """ metrics_copy = metrics.copy() for k, v in metrics_copy.items(): if "_mem_" in k: metrics_copy[k] = f"{v >> 20}MB" elif "_runtime" in k: metrics_copy[k] = _secs2timedelta(v) elif k == "total_flos": metrics_copy[k] = f"{int(v) >> 30}GF" elif isinstance(metrics_copy[k], float): metrics_copy[k] = round(v, 4) return metrics_copy def log_metrics(self, split, metrics): """ Log metrics in a specially formatted way. Under distributed environment this is done only for a process with rank 0. Args: split (`str`): Mode/split name: one of `train`, `eval`, `test` metrics (`dict[str, float]`): The metrics returned from train/evaluate/predictmetrics: metrics dict Notes on memory reports: In order to get memory usage report you need to install `psutil`. You can do that with `pip install psutil`.
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/processing_utils.py
src/transformers/processing_utils.py
# Copyright 2022 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Processing saving/loading class for common processors. """ import bisect import copy import inspect import json import os import sys import typing from dataclasses import dataclass from pathlib import Path from typing import Annotated, Any, Literal, Optional, TypedDict, TypeVar, Union import numpy as np import typing_extensions from huggingface_hub import create_repo, is_offline_mode from huggingface_hub.dataclasses import validate_typed_dict from huggingface_hub.errors import EntryNotFoundError from .audio_utils import AudioInput, load_audio from .dynamic_module_utils import custom_object_save from .feature_extraction_utils import BatchFeature from .image_utils import ChannelDimension, ImageInput, is_vision_available from .tokenization_utils_base import ( PaddingStrategy, PreTokenizedInput, PreTrainedTokenizerBase, TextInput, TruncationStrategy, ) from .utils import ( AUDIO_TOKENIZER_NAME, CHAT_TEMPLATE_DIR, CHAT_TEMPLATE_FILE, LEGACY_PROCESSOR_CHAT_TEMPLATE_FILE, PROCESSOR_NAME, PushToHubMixin, TensorType, cached_file, copy_func, direct_transformers_import, is_torch_available, list_repo_templates, logging, ) from .utils.chat_template_utils import render_jinja_template from .utils.type_validators import ( device_validator, image_size_validator, padding_validator, positive_any_number, positive_int, resampling_validator, tensor_type_validator, truncation_validator, video_metadata_validator, ) from .video_utils import VideoInput, VideoMetadataType if is_torch_available(): import torch from .modeling_utils import PreTrainedAudioTokenizerBase if is_vision_available(): from .image_utils import PILImageResampling logger = logging.get_logger(__name__) # type hinting: specifying the type of processor class that inherits from ProcessorMixin SpecificProcessorType = TypeVar("SpecificProcessorType", bound="ProcessorMixin") # Dynamically import the Transformers module to grab the attribute classes of the processor from their names. transformers_module = direct_transformers_import(Path(__file__).parent) class _LazyAutoProcessorMapping(dict): """ Lazy dictionary to avoid circular imports. The mapping names are only imported when accessed. """ _MAPPING_NAMES = { "image_processor": ("transformers.models.auto.image_processing_auto", "AutoImageProcessor"), "video_processor": ("transformers.models.auto.video_processing_auto", "AutoVideoProcessor"), "feature_extractor": ("transformers.models.auto.feature_extraction_auto", "AutoFeatureExtractor"), "audio_processor": ("transformers.models.auto.feature_extraction_auto", "AutoFeatureExtractor"), "tokenizer": ("transformers.models.auto.tokenization_auto", "AutoTokenizer"), } def __getitem__(self, key): if key not in self._MAPPING_NAMES: raise KeyError(key) module_name, attr_name = self._MAPPING_NAMES[key] module = __import__(module_name, fromlist=[attr_name]) return getattr(module, attr_name) def __contains__(self, key): return key in self._MAPPING_NAMES def keys(self): return self._MAPPING_NAMES.keys() MODALITY_TO_AUTOPROCESSOR_MAPPING = _LazyAutoProcessorMapping() MODALITY_TO_BASE_CLASS_MAPPING = { "audio_tokenizer": "DacModel", "audio_processor": "FeatureExtractionMixin", "tokenizer": ("PreTrainedTokenizerBase", "MistralCommonBackend"), "feature_extractor": "FeatureExtractionMixin", "image_processor": "ImageProcessingMixin", "video_processor": "BaseVideoProcessor", } def _get_modality_for_attribute(attribute_name: str) -> str: """ Get the canonical modality type for a given attribute name. For example: - "image_processor" -> "image_processor" - "encoder_image_processor" -> "image_processor" - "text_tokenizer" -> "tokenizer" - "my_feature_extractor" -> "feature_extractor" """ for modality in MODALITY_TO_AUTOPROCESSOR_MAPPING.keys(): if modality in attribute_name: return modality raise ValueError( f"Cannot determine modality for attribute '{attribute_name}'. " f"Attribute name must contain one of: {list(MODALITY_TO_AUTOPROCESSOR_MAPPING.keys())}" ) if sys.version_info >= (3, 11): Unpack = typing.Unpack else: Unpack = typing_extensions.Unpack class TextKwargs(TypedDict, total=False): """ Keyword arguments for text processing. For extended documentation, check out tokenization_utils_base methods and docstrings associated. Attributes: add_special_tokens (`bool`, *optional*) Whether or not to add special tokens when encoding the sequences. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*) Activates and controls padding. truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*): Activates and controls truncation. max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. stride (`int`, *optional*): If set, the overflowing tokens will contain some tokens from the end of the truncated sequence. is_split_into_words (`bool`, *optional*): Whether or not the input is already pre-tokenized. pad_to_multiple_of (`int`, *optional*): If set, will pad the sequence to a multiple of the provided value. return_token_type_ids (`bool`, *optional*): Whether to return token type IDs. return_attention_mask (`bool`, *optional*): Whether to return the attention mask. return_overflowing_tokens (`bool`, *optional*): Whether or not to return overflowing token sequences. return_special_tokens_mask (`bool`, *optional*): Whether or not to return special tokens mask information. return_offsets_mapping (`bool`, *optional*): Whether or not to return `(char_start, char_end)` for each token. return_length (`bool`, *optional*): Whether or not to return the lengths of the encoded inputs. verbose (`bool`, *optional*): Whether or not to print more information and warnings. padding_side (`str`, *optional*): The side on which padding will be applied. return_mm_token_type_ids (`bool`, *optional*): Whether to return multimodal token type ids indicating mm placeholder token positions. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. """ text_pair: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] text_target: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] text_pair_target: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] add_special_tokens: Optional[bool] padding: Annotated[Optional[Union[bool, str, PaddingStrategy]], padding_validator()] truncation: Annotated[Optional[Union[bool, str, TruncationStrategy]], truncation_validator()] max_length: Annotated[Optional[int], positive_int()] stride: Annotated[Optional[int], positive_int()] is_split_into_words: Optional[bool] pad_to_multiple_of: Annotated[Optional[int], positive_int()] return_token_type_ids: Optional[bool] return_attention_mask: Optional[bool] return_overflowing_tokens: Optional[bool] return_special_tokens_mask: Optional[bool] return_offsets_mapping: Optional[bool] return_length: Optional[bool] verbose: Optional[bool] padding_side: Optional[Literal["left", "right"]] return_mm_token_type_ids: Optional[bool] return_tensors: Annotated[Optional[Union[str, TensorType]], tensor_type_validator()] class ImagesKwargs(TypedDict, total=False): """ Keyword arguments for image processing. For extended documentation, check the appropriate ImageProcessor class methods and docstrings. Attributes: do_convert_rgb (`bool`): Whether to convert the video to RGB format. do_resize (`bool`, *optional*): Whether to resize the image. size (`dict[str, int]`, *optional*): Resize the shorter side of the input to `size["shortest_edge"]`. crop_size (`dict[str, int]`, *optional*): Desired output size when applying center-cropping. do_convert_rgb (`bool`): Whether to convert the video to RGB format. resample (`PILImageResampling`, *optional*): Resampling filter to use if resizing the image. do_rescale (`bool`, *optional*): Whether to rescale the image by the specified scale `rescale_factor`. rescale_factor (`int` or `float`, *optional*): Scale factor to use if rescaling the image. do_normalize (`bool`, *optional*): Whether to normalize the image. image_mean (`float` or `list[float] or tuple[float, float, float]`, *optional*): Mean to use if normalizing the image. image_std (`float` or `list[float] or tuple[float, float, float]`, *optional*): Standard deviation to use if normalizing the image. do_pad (`bool`, *optional*): Whether to pad the images in the batch. pad_size (`dict[str, int]`, *optional*): The size `{"height": int, "width" int}` to pad the images to. do_center_crop (`bool`, *optional*): Whether to center crop the image. data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the output image. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. device (`Union[str, torch.Tensor]`, *optional*): The device to use for processing (e.g. "cpu", "cuda"), only relevant for fast image processing. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. disable_grouping (`bool`, *optional*): Whether to group images by shapes when processing or not, only relevant for fast image processing. image_seq_length (`int`, *optional*): The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. """ do_convert_rgb: Optional[bool] do_resize: Optional[bool] size: Annotated[Optional[Union[int, list[int], tuple[int, ...], dict[str, int]]], image_size_validator()] crop_size: Annotated[Optional[Union[int, list[int], tuple[int, ...], dict[str, int]]], image_size_validator()] resample: Annotated[Optional[Union["PILImageResampling", int]], resampling_validator()] do_rescale: Optional[bool] rescale_factor: Optional[float] do_normalize: Optional[bool] image_mean: Optional[Union[float, list[float], tuple[float, ...]]] image_std: Optional[Union[float, list[float], tuple[float, ...]]] do_pad: Optional[bool] pad_size: Annotated[Optional[Union[int, list[int], tuple[int, ...], dict[str, int]]], image_size_validator()] do_center_crop: Optional[bool] data_format: Optional[Union[str, ChannelDimension]] input_data_format: Optional[Union[str, ChannelDimension]] device: Annotated[Optional[Union[str, "torch.device"]], device_validator()] return_tensors: Annotated[Optional[Union[str, TensorType]], tensor_type_validator()] disable_grouping: Optional[bool] image_seq_length: Optional[int] class VideosKwargs(TypedDict, total=False): """ Keyword arguments for video processing. Attributes: do_convert_rgb (`bool`): Whether to convert the video to RGB format. do_resize (`bool`): Whether to resize the video. size (`dict[str, int]`, *optional*): Resize the shorter side of the input to `size["shortest_edge"]`. default_to_square (`bool`, *optional*, defaults to `self.default_to_square`): Whether to default to a square when resizing, if size is an int. resample (`PILImageResampling`, *optional*): Resampling filter to use if resizing the video. do_rescale (`bool`, *optional*): Whether to rescale the video by the specified scale `rescale_factor`. rescale_factor (`int` or `float`, *optional*): Scale factor to use if rescaling the video. do_normalize (`bool`, *optional*): Whether to normalize the video. image_mean (`float` or `list[float] or tuple[float, float, float]`, *optional*): Mean to use if normalizing the video. image_std (`float` or `list[float] or tuple[float, float, float]`, *optional*): Standard deviation to use if normalizing the video. do_center_crop (`bool`, *optional*): Whether to center crop the video. do_pad (`bool`, *optional*): Whether to pad the images in the batch. do_sample_frames (`bool`, *optional*): Whether to sample frames from the video before processing or to process the whole video. video_metadata (`Union[VideoMetadata, dict]`, *optional*): Metadata of the video containing information about total duration, fps and total number of frames. num_frames (`int`, *optional*): Maximum number of frames to sample when `do_sample_frames=True`. fps (`int` or `float`, *optional*): Target frames to sample per second when `do_sample_frames=True`. crop_size (`dict[str, int]`, *optional*): Desired output size when applying center-cropping. data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the output video. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input video. device (`Union[str, torch.Tensor]`, *optional*): The device to use for processing (e.g. "cpu", "cuda"), only relevant for fast image processing. return_metadata (`bool`, *optional*): Whether to return video metadata or not. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. """ do_convert_rgb: Optional[bool] do_resize: Optional[bool] size: Annotated[Optional[Union[int, list[int], tuple[int, ...], dict[str, int]]], image_size_validator()] default_to_square: Optional[bool] resample: Annotated[Optional[Union["PILImageResampling", int]], resampling_validator()] do_rescale: Optional[bool] rescale_factor: Optional[float] do_normalize: Optional[bool] image_mean: Optional[Union[float, list[float], tuple[float, ...]]] image_std: Optional[Union[float, list[float], tuple[float, ...]]] do_center_crop: Optional[bool] do_pad: Optional[bool] crop_size: Annotated[Optional[Union[int, list[int], tuple[int, ...], dict[str, int]]], image_size_validator()] data_format: Optional[Union[str, ChannelDimension]] input_data_format: Optional[Union[str, ChannelDimension]] device: Annotated[Optional[Union[str, "torch.device"]], device_validator()] do_sample_frames: Optional[bool] video_metadata: Annotated[Optional[VideoMetadataType], video_metadata_validator()] fps: Annotated[Optional[Union[int, float]], positive_any_number()] num_frames: Annotated[Optional[int], positive_int()] return_metadata: Optional[bool] return_tensors: Annotated[Optional[Union[str, TensorType]], tensor_type_validator()] class AudioKwargs(TypedDict, total=False): """ Keyword arguments for audio processing. Attributes: sampling_rate (`int`, *optional*): The sampling rate at which the `raw_speech` input was sampled. raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`): The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not stereo, i.e. single float per timestep. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*): Select a strategy to pad the returned sequences (according to the model's padding side and padding index) among: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` max_length (`int`, *optional*): Maximum length of the returned list and optionally padding length (see above). truncation (`bool`, *optional*): Activates truncation to cut input sequences longer than *max_length* to *max_length*. pad_to_multiple_of (`int`, *optional*): If set, will pad the sequence to a multiple of the provided value. return_attention_mask (`bool`, *optional*): Whether or not [`~ASTFeatureExtractor.__call__`] should return `attention_mask`. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. """ sampling_rate: Annotated[Optional[int], positive_int()] raw_speech: Optional[Union["np.ndarray", list[float], list["np.ndarray"], list[list[float]]]] padding: Annotated[Optional[Union[bool, str, PaddingStrategy]], padding_validator()] max_length: Annotated[Optional[int], positive_int()] truncation: Annotated[Optional[Union[bool, str, TruncationStrategy]], truncation_validator()] pad_to_multiple_of: Annotated[Optional[int], positive_int()] return_attention_mask: Optional[bool] return_tensors: Annotated[Optional[Union[str, TensorType]], tensor_type_validator()] class ProcessingKwargs(TypedDict, total=False): """ Base class for kwargs passing to processors. In case a model has specific kwargs that are not present in the base class or default values for existing keys, it should have its own `ModelProcessorKwargs` class that inherits from `ProcessingKwargs` to provide: 1) Additional typed keys and that this model requires to process inputs. 2) Default values for existing keys under a `_defaults` attribute. New keys have to be defined as follows to ensure type hinting is done correctly. ```python # adding a new image kwarg for this model class ModelImagesKwargs(ImagesKwargs, total=False): new_image_kwarg: Optional[bool] class ModelProcessorKwargs(ProcessingKwargs, total=False): images_kwargs: ModelImagesKwargs _defaults = { "images_kwargs: { "new_image_kwarg": False, } "text_kwargs": { "padding": "max_length", }, } ``` For Python 3.8 compatibility, when inheriting from this class and overriding one of the kwargs, you need to manually update the __annotations__ dictionary. This can be done as follows: ```python class CustomProcessorKwargs(ProcessingKwargs, total=False): images_kwargs: CustomImagesKwargs CustomProcessorKwargs.__annotations__["images_kwargs"] = CustomImagesKwargs # python 3.8 compatibility ```python """ _defaults = {} text_kwargs: TextKwargs = { **TextKwargs.__annotations__, } images_kwargs: ImagesKwargs = { **ImagesKwargs.__annotations__, } videos_kwargs: VideosKwargs = { **VideosKwargs.__annotations__, } audio_kwargs: AudioKwargs = { **AudioKwargs.__annotations__, } class TokenizerChatTemplateKwargs(TypedDict, total=False): """ Keyword arguments for tokenizer's `apply_chat_template`, when it is called from within a processor. tools (`list[Dict]`, *optional*): A list of tools (callable functions) that will be accessible to the model. If the template does not support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema, giving the name, description and argument types for the tool. See our [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use) for more information. documents (`list[dict[str, str]]`, *optional*): A list of dicts representing documents that will be accessible to the model if it is performing RAG (retrieval-augmented generation). If the template does not support RAG, this argument will have no effect. We recommend that each document should be a dict containing "title" and "text" keys. Please see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG) for examples of passing documents with chat templates. add_generation_prompt (bool, *optional*): If this is set, a prompt with the token(s) that indicate the start of an assistant message will be appended to the formatted output. This is useful when you want to generate a response from the model. Note that this argument will be passed to the chat template, and so it must be supported in the template for this argument to have any effect. continue_final_message (bool, *optional*): If this is set, the chat will be formatted so that the final message in the chat is open-ended, without any EOS tokens. The model will continue this message rather than starting a new one. This allows you to "prefill" part of the model's response for it. Cannot be used at the same time as `add_generation_prompt`. return_assistant_tokens_mask (`bool`, defaults to `False`): Whether to return a mask of the assistant generated tokens. For tokens generated by the assistant, the mask will contain 1. For user and system tokens, the mask will contain 0. This functionality is only available for chat templates that support it via the `{% generation %}` keyword. """ tools: Optional[list[dict]] = None documents: Optional[list[dict[str, str]]] = None add_generation_prompt: Optional[bool] = False continue_final_message: Optional[bool] = False return_assistant_tokens_mask: Optional[bool] = False class ChatTemplateLoadKwargs(TypedDict, total=False): """ Keyword arguments used to load multimodal data in processor chat templates. num_frames (`int`, *optional*): Number of frames to sample uniformly. If not passed, the whole video is loaded. load_audio_from_video (`bool`, *optional*): Whether to use the audio track of input video. If `True` the audio track will be loaded and passed to the processor. This flag has no effect if the model doesn't support audio modality. """ sampling_rate: Optional[int] = 16_000 load_audio_from_video: Optional[bool] = False class ProcessorChatTemplateKwargs(ChatTemplateLoadKwargs, TokenizerChatTemplateKwargs, total=False): """ Keyword arguments for processor's `apply_chat_template`. tokenize (`bool`, *optional*, defaults to `False`): Whether to tokenize the output or not. return_dict (`bool`, defaults to `False`): Whether to return a dictionary with named outputs. Has no effect if tokenize is `False`. """ tokenize: Optional[bool] = False return_dict: Optional[bool] = False class AllKwargsForChatTemplate(TypedDict, total=False): processor_kwargs: ProcessingKwargs mm_load_kwargs: ChatTemplateLoadKwargs template_kwargs: ProcessorChatTemplateKwargs @dataclass class MultiModalData: """ Dataclass that holds extra useful data for processing multimodal data. Processors currently cannot return keys, unless it is used in model's forward. Thus we have helper methods that calculate and return useful data from processing input multimodals (images/videos). Note that this dataclass is aimed to be used only in vLLM and we might change its API in the future. """ num_image_tokens: Optional[list[int]] = None num_video_tokens: Optional[list[int]] = None num_audio_tokens: Optional[list[int]] = None num_image_patches: Optional[list[int]] = None def __contains__(self, key): return hasattr(self, key) and getattr(self, key) is not None def __getitem__(self, key): if hasattr(self, key): return getattr(self, key) raise AttributeError(f"{self.__class__.__name__} has no attribute {key}") class ProcessorMixin(PushToHubMixin): """ This is a mixin used to provide saving/loading functionality for all processor classes. """ # Names need to be attr_class for attr in attributes _auto_class = None valid_processor_kwargs = ProcessingKwargs # args have to match the attributes class attribute def __init__(self, *args, **kwargs): # First, extract chat template from kwargs. It can never be a positional arg setattr(self, "chat_template", kwargs.pop("chat_template", None)) # Check audio tokenizer for its class but do not treat it as attr to avoid saving weights if (audio_tokenizer := kwargs.pop("audio_tokenizer", None)) is not None: proper_class = self.check_argument_for_proper_class("audio_tokenizer", audio_tokenizer) if not (is_torch_available() and isinstance(audio_tokenizer, PreTrainedAudioTokenizerBase)): raise ValueError( f"Tried to use `{proper_class}` for audio tokenization. However, this class is not" " registered for audio tokenization." ) setattr(self, "audio_tokenizer", audio_tokenizer) # Sanitize args and kwargs for key in kwargs: if key not in self.get_attributes(): raise TypeError(f"Unexpected keyword argument {key}.") for arg, attribute_name in zip(args, self.get_attributes()): if attribute_name in kwargs: raise TypeError(f"Got multiple values for argument {attribute_name}.") else: kwargs[attribute_name] = arg if len(kwargs) != len(self.get_attributes()): raise ValueError( f"This processor requires {len(self.get_attributes())} arguments: {', '.join(self.get_attributes())}. Got " f"{len(args)} arguments instead." ) # Check each arg is of the proper class (this will also catch a user initializing in the wrong order) for attribute_name, arg in kwargs.items(): self.check_argument_for_proper_class(attribute_name, arg) setattr(self, attribute_name, arg) def __call__( self, images: Optional[ImageInput] = None, text: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] = None, videos: Optional[VideoInput] = None, audio: Optional[AudioInput] = None, **kwargs: Unpack[ProcessingKwargs], ): """ Main method to prepare for model inputs. This method forwards the each modality argument to its own processor along with `kwargs`. Please refer to the docstring of the each processor attributes for more information. Args: images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`): The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch tensor. Both channels-first and channels-last formats are supported. text (`TextInput`, `PreTokenizedInput`, `list[TextInput]`, `list[PreTokenizedInput]`, *optional*): The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`): The video or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported. audio (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`): The audio or batch of audio to be prepared. Each audio can be a NumPy array or PyTorch tensor. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. Returns: [`BatchFeature`]: A [`BatchFeature`] object with processed inputs in a dict format. """ if "audios" in kwargs and audio is None: raise ValueError("You passed keyword argument `audios` which is deprecated. Please use `audio` instead.") if images is None and text is None and videos is None and audio is None: raise ValueError(f"You need to provide at least one input to call {self.__class__.__name__}") kwargs = self._merge_kwargs( self.valid_processor_kwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs if hasattr(self, "tokenizer") else {}, **kwargs, ) attribute_to_kwargs = { "tokenizer": (text, "text_kwargs"), "image_processor": (images, "images_kwargs"), "video_processor": (videos, "videos_kwargs"), "feature_extractor": (audio, "audio_kwargs"), } outputs = {} for attribute_name in self.get_attributes(): attribute = getattr(self, attribute_name, None) input_data, input_kwargs = attribute_to_kwargs[attribute_name] if input_data is not None and attribute is not None: attribute_output = attribute(input_data, **kwargs[input_kwargs]) outputs.update(attribute_output) return BatchFeature(outputs) def check_argument_for_proper_class(self, argument_name, argument): """ Checks the passed argument's class against the expected transformers class. In case of an unexpected mismatch between expected and actual class, an error is raise. Otherwise, the proper retrieved class is returned. """ # If the exact attribute name is not in the mapping, use its canonical modality # (e.g., "encoder_tokenizer" -> "tokenizer") if argument_name not in MODALITY_TO_BASE_CLASS_MAPPING:
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/image_processing_base.py
src/transformers/image_processing_base.py
# Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import json import os from typing import Any, Optional, TypeVar, Union import numpy as np from huggingface_hub import create_repo, is_offline_mode from .dynamic_module_utils import custom_object_save from .feature_extraction_utils import BatchFeature as BaseBatchFeature from .image_utils import is_valid_image, load_image from .utils import ( IMAGE_PROCESSOR_NAME, PROCESSOR_NAME, PushToHubMixin, copy_func, logging, safe_load_json_file, ) from .utils.hub import cached_file ImageProcessorType = TypeVar("ImageProcessorType", bound="ImageProcessingMixin") logger = logging.get_logger(__name__) # TODO: Move BatchFeature to be imported by both image_processing_utils and image_processing_utils_fast # We override the class string here, but logic is the same. class BatchFeature(BaseBatchFeature): r""" Holds the output of the image processor specific `__call__` methods. This class is derived from a python dictionary and can be used as a dictionary. Args: data (`dict`): Dictionary of lists/arrays/tensors returned by the __call__ method ('pixel_values', etc.). tensor_type (`Union[None, str, TensorType]`, *optional*): You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization. """ # TODO: (Amy) - factor out the common parts of this and the feature extractor class ImageProcessingMixin(PushToHubMixin): """ This is an image processor mixin used to provide saving/loading functionality for sequential and image feature extractors. """ _auto_class = None def __init__(self, **kwargs): """Set elements of `kwargs` as attributes.""" # This key was saved while we still used `XXXFeatureExtractor` for image processing. Now we use # `XXXImageProcessor`, this attribute and its value are misleading. kwargs.pop("feature_extractor_type", None) # Pop "processor_class", should not be saved with image processing config anymore kwargs.pop("processor_class", None) # Additional attributes without default values for key, value in kwargs.items(): try: setattr(self, key, value) except AttributeError as err: logger.error(f"Can't set {key} with value {value} for {self}") raise err @classmethod def from_pretrained( cls: type[ImageProcessorType], pretrained_model_name_or_path: Union[str, os.PathLike], cache_dir: Optional[Union[str, os.PathLike]] = None, force_download: bool = False, local_files_only: bool = False, token: Optional[Union[str, bool]] = None, revision: str = "main", **kwargs, ) -> ImageProcessorType: r""" Instantiate a type of [`~image_processing_utils.ImageProcessingMixin`] from an image processor. Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained image_processor hosted inside a model repo on huggingface.co. - a path to a *directory* containing a image processor file saved using the [`~image_processing_utils.ImageProcessingMixin.save_pretrained`] method, e.g., `./my_model_directory/`. - a path or url to a saved image processor JSON *file*, e.g., `./my_model_directory/preprocessor_config.json`. cache_dir (`str` or `os.PathLike`, *optional*): Path to a directory in which a downloaded pretrained model image processor should be cached if the standard cache should not be used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force to (re-)download the image processor files and override the cached versions if they exist. proxies (`dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. token (`str` or `bool`, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use the token generated when running `hf auth login` (stored in `~/.huggingface`). revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. <Tip> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`. </Tip> return_unused_kwargs (`bool`, *optional*, defaults to `False`): If `False`, then this function returns just the final image processor object. If `True`, then this functions returns a `Tuple(image_processor, unused_kwargs)` where *unused_kwargs* is a dictionary consisting of the key/value pairs whose keys are not image processor attributes: i.e., the part of `kwargs` which has not been used to update `image_processor` and is otherwise ignored. subfolder (`str`, *optional*, defaults to `""`): In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can specify the folder name here. kwargs (`dict[str, Any]`, *optional*): The values in kwargs of any keys which are image processor attributes will be used to override the loaded values. Behavior concerning key/value pairs whose keys are *not* image processor attributes is controlled by the `return_unused_kwargs` keyword parameter. Returns: A image processor of type [`~image_processing_utils.ImageProcessingMixin`]. Examples: ```python # We can't instantiate directly the base class *ImageProcessingMixin* so let's show the examples on a # derived class: *CLIPImageProcessor* image_processor = CLIPImageProcessor.from_pretrained( "openai/clip-vit-base-patch32" ) # Download image_processing_config from huggingface.co and cache. image_processor = CLIPImageProcessor.from_pretrained( "./test/saved_model/" ) # E.g. image processor (or model) was saved using *save_pretrained('./test/saved_model/')* image_processor = CLIPImageProcessor.from_pretrained("./test/saved_model/preprocessor_config.json") image_processor = CLIPImageProcessor.from_pretrained( "openai/clip-vit-base-patch32", do_normalize=False, foo=False ) assert image_processor.do_normalize is False image_processor, unused_kwargs = CLIPImageProcessor.from_pretrained( "openai/clip-vit-base-patch32", do_normalize=False, foo=False, return_unused_kwargs=True ) assert image_processor.do_normalize is False assert unused_kwargs == {"foo": False} ```""" kwargs["cache_dir"] = cache_dir kwargs["force_download"] = force_download kwargs["local_files_only"] = local_files_only kwargs["revision"] = revision if token is not None: kwargs["token"] = token image_processor_dict, kwargs = cls.get_image_processor_dict(pretrained_model_name_or_path, **kwargs) return cls.from_dict(image_processor_dict, **kwargs) def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs): """ Save an image processor object to the directory `save_directory`, so that it can be re-loaded using the [`~image_processing_utils.ImageProcessingMixin.from_pretrained`] class method. Args: save_directory (`str` or `os.PathLike`): Directory where the image processor JSON file will be saved (will be created if it does not exist). push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace). kwargs (`dict[str, Any]`, *optional*): Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method. """ if os.path.isfile(save_directory): raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file") os.makedirs(save_directory, exist_ok=True) if push_to_hub: commit_message = kwargs.pop("commit_message", None) repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1]) repo_id = create_repo(repo_id, exist_ok=True, **kwargs).repo_id files_timestamps = self._get_files_timestamps(save_directory) # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be # loaded from the Hub. if self._auto_class is not None: custom_object_save(self, save_directory, config=self) # If we save using the predefined names, we can load using `from_pretrained` output_image_processor_file = os.path.join(save_directory, IMAGE_PROCESSOR_NAME) self.to_json_file(output_image_processor_file) logger.info(f"Image processor saved in {output_image_processor_file}") if push_to_hub: self._upload_modified_files( save_directory, repo_id, files_timestamps, commit_message=commit_message, token=kwargs.get("token"), ) return [output_image_processor_file] @classmethod def get_image_processor_dict( cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs ) -> tuple[dict[str, Any], dict[str, Any]]: """ From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a image processor of type [`~image_processor_utils.ImageProcessingMixin`] using `from_dict`. Parameters: pretrained_model_name_or_path (`str` or `os.PathLike`): The identifier of the pre-trained checkpoint from which we want the dictionary of parameters. subfolder (`str`, *optional*, defaults to `""`): In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can specify the folder name here. image_processor_filename (`str`, *optional*, defaults to `"config.json"`): The name of the file in the model directory to use for the image processor config. Returns: `tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the image processor object. """ cache_dir = kwargs.pop("cache_dir", None) force_download = kwargs.pop("force_download", False) proxies = kwargs.pop("proxies", None) token = kwargs.pop("token", None) local_files_only = kwargs.pop("local_files_only", False) revision = kwargs.pop("revision", None) subfolder = kwargs.pop("subfolder", "") image_processor_filename = kwargs.pop("image_processor_filename", IMAGE_PROCESSOR_NAME) from_pipeline = kwargs.pop("_from_pipeline", None) from_auto_class = kwargs.pop("_from_auto", False) user_agent = {"file_type": "image processor", "from_auto_class": from_auto_class} if from_pipeline is not None: user_agent["using_pipeline"] = from_pipeline if is_offline_mode() and not local_files_only: logger.info("Offline mode: forcing local_files_only=True") local_files_only = True pretrained_model_name_or_path = str(pretrained_model_name_or_path) is_local = os.path.isdir(pretrained_model_name_or_path) if os.path.isdir(pretrained_model_name_or_path): image_processor_file = os.path.join(pretrained_model_name_or_path, image_processor_filename) if os.path.isfile(pretrained_model_name_or_path): resolved_image_processor_file = pretrained_model_name_or_path resolved_processor_file = None is_local = True else: image_processor_file = image_processor_filename try: resolved_processor_file = cached_file( pretrained_model_name_or_path, filename=PROCESSOR_NAME, cache_dir=cache_dir, force_download=force_download, proxies=proxies, local_files_only=local_files_only, token=token, user_agent=user_agent, revision=revision, subfolder=subfolder, _raise_exceptions_for_missing_entries=False, ) resolved_image_processor_file = cached_file( pretrained_model_name_or_path, filename=image_processor_file, cache_dir=cache_dir, force_download=force_download, proxies=proxies, local_files_only=local_files_only, token=token, user_agent=user_agent, revision=revision, subfolder=subfolder, _raise_exceptions_for_missing_entries=False, ) except OSError: # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to # the original exception. raise except Exception: # For any other exception, we throw a generic error. raise OSError( f"Can't load image processor for '{pretrained_model_name_or_path}'. If you were trying to load" " it from 'https://huggingface.co/models', make sure you don't have a local directory with the" f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a" f" directory containing a {image_processor_filename} file" ) # Load image_processor dict. Priority goes as (nested config if found -> image processor config) # We are downloading both configs because almost all models have a `processor_config.json` but # not all of these are nested. We need to check if it was saved recebtly as nested or if it is legacy style image_processor_dict = None if resolved_processor_file is not None: processor_dict = safe_load_json_file(resolved_processor_file) if "image_processor" in processor_dict: image_processor_dict = processor_dict["image_processor"] if resolved_image_processor_file is not None and image_processor_dict is None: image_processor_dict = safe_load_json_file(resolved_image_processor_file) if image_processor_dict is None: raise OSError( f"Can't load image processor for '{pretrained_model_name_or_path}'. If you were trying to load" " it from 'https://huggingface.co/models', make sure you don't have a local directory with the" f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a" f" directory containing a {image_processor_filename} file" ) if is_local: logger.info(f"loading configuration file {resolved_image_processor_file}") else: logger.info( f"loading configuration file {image_processor_file} from cache at {resolved_image_processor_file}" ) return image_processor_dict, kwargs @classmethod def from_dict(cls, image_processor_dict: dict[str, Any], **kwargs): """ Instantiates a type of [`~image_processing_utils.ImageProcessingMixin`] from a Python dictionary of parameters. Args: image_processor_dict (`dict[str, Any]`): Dictionary that will be used to instantiate the image processor object. Such a dictionary can be retrieved from a pretrained checkpoint by leveraging the [`~image_processing_utils.ImageProcessingMixin.to_dict`] method. kwargs (`dict[str, Any]`): Additional parameters from which to initialize the image processor object. Returns: [`~image_processing_utils.ImageProcessingMixin`]: The image processor object instantiated from those parameters. """ image_processor_dict = image_processor_dict.copy() return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) image_processor_dict.update({k: v for k, v in kwargs.items() if k in cls.valid_kwargs.__annotations__}) image_processor = cls(**image_processor_dict) # Remove kwargs that are used to initialize the image processor attributes for key in list(kwargs): if hasattr(image_processor, key): kwargs.pop(key) logger.info(f"Image processor {image_processor}") if return_unused_kwargs: return image_processor, kwargs else: return image_processor def to_dict(self) -> dict[str, Any]: """ Serializes this instance to a Python dictionary. Returns: `dict[str, Any]`: Dictionary of all the attributes that make up this image processor instance. """ output = copy.deepcopy(self.__dict__) output["image_processor_type"] = self.__class__.__name__ return output @classmethod def from_json_file(cls, json_file: Union[str, os.PathLike]): """ Instantiates a image processor of type [`~image_processing_utils.ImageProcessingMixin`] from the path to a JSON file of parameters. Args: json_file (`str` or `os.PathLike`): Path to the JSON file containing the parameters. Returns: A image processor of type [`~image_processing_utils.ImageProcessingMixin`]: The image_processor object instantiated from that JSON file. """ with open(json_file, encoding="utf-8") as reader: text = reader.read() image_processor_dict = json.loads(text) return cls(**image_processor_dict) def to_json_string(self) -> str: """ Serializes this instance to a JSON string. Returns: `str`: String containing all the attributes that make up this feature_extractor instance in JSON format. """ dictionary = self.to_dict() for key, value in dictionary.items(): if isinstance(value, np.ndarray): dictionary[key] = value.tolist() return json.dumps(dictionary, indent=2, sort_keys=True) + "\n" def to_json_file(self, json_file_path: Union[str, os.PathLike]): """ Save this instance to a JSON file. Args: json_file_path (`str` or `os.PathLike`): Path to the JSON file in which this image_processor instance's parameters will be saved. """ with open(json_file_path, "w", encoding="utf-8") as writer: writer.write(self.to_json_string()) def __repr__(self): return f"{self.__class__.__name__} {self.to_json_string()}" @classmethod def register_for_auto_class(cls, auto_class="AutoImageProcessor"): """ Register this class with a given auto class. This should only be used for custom image processors as the ones in the library are already mapped with `AutoImageProcessor `. Args: auto_class (`str` or `type`, *optional*, defaults to `"AutoImageProcessor "`): The auto class to register this new image processor with. """ if not isinstance(auto_class, str): auto_class = auto_class.__name__ import transformers.models.auto as auto_module if not hasattr(auto_module, auto_class): raise ValueError(f"{auto_class} is not a valid auto class.") cls._auto_class = auto_class def fetch_images(self, image_url_or_urls: Union[str, list[str], list[list[str]]]): """ Convert a single or a list of urls into the corresponding `PIL.Image` objects. If a single url is passed, the return value will be a single object. If a list is passed a list of objects is returned. """ if isinstance(image_url_or_urls, list): return [self.fetch_images(x) for x in image_url_or_urls] elif isinstance(image_url_or_urls, str): return load_image(image_url_or_urls) elif is_valid_image(image_url_or_urls): return image_url_or_urls else: raise TypeError(f"only a single or a list of entries is supported but got type={type(image_url_or_urls)}") ImageProcessingMixin.push_to_hub = copy_func(ImageProcessingMixin.push_to_hub) if ImageProcessingMixin.push_to_hub.__doc__ is not None: ImageProcessingMixin.push_to_hub.__doc__ = ImageProcessingMixin.push_to_hub.__doc__.format( object="image processor", object_class="AutoImageProcessor", object_files="image processor file" )
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/tokenization_mistral_common.py
src/transformers/tokenization_mistral_common.py
# Copyright 2025 Mistral AI and The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import re import shutil import warnings from collections.abc import Callable, Mapping, Sized from enum import Enum from pathlib import Path from typing import Any, Union, overload import numpy as np from huggingface_hub import create_repo from transformers.audio_utils import load_audio_as from transformers.tokenization_utils_base import ( LARGE_INTEGER, VERY_LARGE_INTEGER, BatchEncoding, EncodedInput, PreTokenizedInput, TextInput, TruncationStrategy, ) from transformers.utils import PaddingStrategy, TensorType, add_end_docstrings, logging, to_py_obj from transformers.utils.generic import is_torch_tensor from transformers.utils.hub import PushToHubMixin from transformers.utils.import_utils import is_mistral_common_available, is_torch_available, requires if is_mistral_common_available(): from mistral_common.protocol.instruct.request import ChatCompletionRequest from mistral_common.protocol.instruct.validator import ValidationMode from mistral_common.tokens.tokenizers.base import SpecialTokenPolicy, TokenizerVersion from mistral_common.tokens.tokenizers.image import MultiModalVersion from mistral_common.tokens.tokenizers.mistral import MistralTokenizer from mistral_common.tokens.tokenizers.tekken import Tekkenizer from mistral_common.tokens.tokenizers.utils import download_tokenizer_from_hf_hub if is_torch_available(): import torch logger = logging.get_logger(__name__) ENCODE_KWARGS_DOCSTRING = r""" add_special_tokens (`bool`, *optional*, defaults to `True`): Whether or not to add special tokens when encoding the sequences. This will use the underlying `PretrainedTokenizerBase.build_inputs_with_special_tokens` function, which defines which tokens are automatically added to the input ids. This is useful if you want to add `bos` or `eos` tokens automatically. When Tokenizer is loading with `finetuning` mode it adds both `bos` and `eos`. Else, for "test" mode it only adds `bos`. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence is provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. stride (`int`, *optional*, defaults to 0): If set to a number along with `max_length`, the overflowing tokens returned when `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence returned to provide some overlap between truncated and overflowing sequences. The value of this argument defines the number of overlapping tokens. pad_to_multiple_of (`int`, *optional*): If set will pad the sequence to a multiple of the provided value. Requires `padding` to be activated. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta). padding_side (`str`, *optional*): The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. """ ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r""" return_attention_mask (`bool`, *optional*): Whether to return the attention mask. If left to the default, will return the attention mask according to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) return_overflowing_tokens (`bool`, *optional*, defaults to `False`): Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead of returning overflowing tokens. return_special_tokens_mask (`bool`, *optional*, defaults to `False`): Whether or not to return special tokens mask information. return_length (`bool`, *optional*, defaults to `False`): Whether or not to return the lengths of the encoded inputs. verbose (`bool`, *optional*, defaults to `True`): Whether or not to print more information and warnings. **kwargs: passed to the `self.tokenize()` method Return: [`BatchEncoding`]: A [`BatchEncoding`] with the following fields: - **input_ids** -- List of token ids to be fed to a model. [What are input IDs?](../glossary#input-ids) - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names`). [What are attention masks?](../glossary#attention-mask) - **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and `return_overflowing_tokens=True`). - **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and `return_overflowing_tokens=True`). - **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`). - **length** -- The length of the inputs (when `return_length=True`) """ class MistralTokenizerType(str, Enum): """Enum for the different type of tokenizer.""" spm = "spm" tekken = "tekken" @requires(backends=("mistral-common",)) class MistralCommonBackend(PushToHubMixin): """ Class to wrap `mistral-common` tokenizers. `mistral-common` is the official tokenizer library for Mistral AI models. To use it, you need to install it with: ```bash pip install transformers[mistral-common] ``` Otherwise the tokenizer falls back to the Transformers implementation of the tokenizer. For more info on `mistral-common`, see [mistral-common](https://github.com/mistralai/mistral-common). This class is a wrapper around a `mistral_common.tokens.tokenizers.mistral.MistralTokenizer`. It provides a Hugging Face compatible interface to tokenize using the official mistral-common tokenizer. Supports the following methods from the `PreTrainedTokenizerBase` class: - [`~MistralCommonBackend.get_vocab`]: Returns the vocabulary as a dictionary of token to index. This is a lossy conversion for Tekkenizer as some decoding errors are collapsed into the same token. - [`~MistralCommonBackend.encode`]: Encode a string to a list of integers. - [`~MistralCommonBackend.decode`]: Decode a list of integers to a string. - [`~MistralCommonBackend.batch_decode`]: Decode a batch of list of integers to a list of strings. - [`~MistralCommonBackend.convert_tokens_to_ids`]: Convert a list of tokens to a list of integers. - [`~MistralCommonBackend.convert_ids_to_tokens`]: Convert a list of integers to a list of tokens. - [`~MistralCommonBackend.tokenize`]: Tokenize a string. - [`~MistralCommonBackend.get_special_tokens_mask`]: Get the special tokens mask for a list of tokens. - [`~MistralCommonBackend.prepare_for_model`]: Prepare a list of inputs for the model. - [`~MistralCommonBackend.pad`]: Pad a list of inputs to the same length. - [`~MistralCommonBackend.truncate_sequences`]: Truncate a list of sequences to the same length. - [`~MistralCommonBackend.apply_chat_template`]: Apply a chat template to a list of messages. - [`~MistralCommonBackend.__call__`]: Tokenize a string or a list of strings. - [`~MistralCommonBackend.from_pretrained`]: Download and cache a pretrained tokenizer from the Hugging Face model hub or local directory. - [`~MistralCommonBackend.save_pretrained`]: Save a tokenizer to a directory, so it can be reloaded using the `from_pretrained` class method. - [`~MistralCommonBackend.push_to_hub`]: Upload tokenizer to the Hugging Face model hub. Here are the key differences with the `PreTrainedTokenizerBase` class: - Pair of sequences are not supported. The signature have been kept for compatibility but all arguments related to pair of sequences are ignored. The return values of pairs are returned as `None`. - The `is_split_into_words` argument is not supported. - The `return_token_type_ids` argument is not supported. - It is not possible to add new tokens to the tokenizer. Also the special tokens are handled differently from Transformers. In `mistral-common`, special tokens are never encoded directly. This means that: `tokenizer.encode("<s>")` will not return the ID of the `<s>` token. Instead, it will return a list of IDs corresponding to the tokenization of the string `"<s>"`. For more information, see the [mistral-common documentation](https://mistralai.github.io/mistral-common/usage/tokenizers/#special-tokens). If you have suggestions to improve this class, please open an issue on the [mistral-common GitHub repository](https://github.com/mistralai/mistral-common/issues) if it is related to the tokenizer or on the [Transformers GitHub repository](https://github.com/huggingface/transformers/issues) if it is related to the Hugging Face interface. """ model_input_names: list[str] = ["input_ids", "attention_mask"] padding_side: str = "left" truncation_side: str = "right" def __init__( self, tokenizer_path: str | os.PathLike | Path, mode: ValidationMode = ValidationMode.test, model_max_length: int = VERY_LARGE_INTEGER, padding_side: str = "left", truncation_side: str = "right", model_input_names: list[str] | None = None, clean_up_tokenization_spaces: bool = False, **kwargs, ): """ Constructs a `MistralCommonBackend`. - **model_input_names** (`list[str]`) -- A list of inputs expected in the forward pass of the model. - **padding_side** (`str`) -- The default value for the side on which the model should have padding applied. Should be `'right'` or `'left'`. - **truncation_side** (`str`) -- The default value for the side on which the model should have truncation applied. Should be `'right'` or `'left'`. Args: tokenizer_path (`str` or `os.PathLike` or `Path`): Path to the tokenizer file to load the `MistralTokenizer`. mode (`Union[str, ValidationMode]`, *optional*, defaults to `ValidationMode.test`): The mode to use for the tokenizer. This will be passed to the `MistralTokenizer` constructor. Possible values are: - `"finetuning"` or `ValidationMode.finetuning`: The finetuning mode. - `"test"` or `ValidationMode.test`: The test mode. It changes how the tokenizer validates the input and prepares the request to the model. model_max_length (`int`, *optional*): The maximum length (in number of tokens) for the inputs to the transformer model. When the tokenizer is loaded with [`~tokenization_utils_base.PreTrainedTokenizerBase.from_pretrained`], this will be set to the value stored for the associated model in `max_model_input_sizes` (see above). If no value is provided, will default to VERY_LARGE_INTEGER (`int(1e30)`). padding_side (`str`, *optional*): The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name. truncation_side (`str`, *optional*): The side on which the model should have truncation applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name. model_input_names (`List[string]`, *optional*): The list of inputs accepted by the forward pass of the model (like `"token_type_ids"` or `"attention_mask"`). Default value is picked from the class attribute of the same name. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`): Whether or not the model should cleanup the spaces that were added when splitting the input text during the tokenization process. """ if kwargs: raise ValueError(f"Kwargs {list(kwargs.keys())} are not supported to init `MistralCommonBackend`.") self._tokenizer_path = Path(tokenizer_path) self._mode = self._get_validation_mode(mode) self.tokenizer: MistralTokenizer = MistralTokenizer.from_file(str(self._tokenizer_path), mode=self._mode) self._tokenizer_type = ( MistralTokenizerType.tekken if isinstance(self.tokenizer.instruct_tokenizer.tokenizer, Tekkenizer) else MistralTokenizerType.spm ) self.truncation_side = truncation_side self.padding_side = padding_side self.model_max_length = model_max_length self.cleanup_tokenization_spaces = clean_up_tokenization_spaces self.deprecation_warnings = {} # Use to store when we have already noticed a deprecation warning (avoid overlogging). self._all_special_tokens_ids = self._get_all_special_ids() if model_input_names is not None: if ( not isinstance(model_input_names, (list, tuple)) and len(model_input_names) == 0 and not all(isinstance(i, str) for i in model_input_names) ): raise ValueError( "`model_input_names` should be a non-empty list or tuple of str but got an empty value." ) self.model_input_names = model_input_names self._cache_get_vocab: dict[str, int] | None = None @staticmethod def clean_up_tokenization(text: str) -> str: """ Clean up a list of simple English tokenization artifacts like spaces before punctuation. """ return ( text.replace(" .", ".") .replace(" ?", "?") .replace(" !", "!") .replace(" ,", ",") .replace(" ' ", "'") .replace(" n't", "n't") .replace(" 'm", "'m") .replace(" 's", "'s") .replace(" 've", "'ve") .replace(" 're", "'re") ) @property def mode(self) -> ValidationMode: """ `ValidationMode`: The mode used by the tokenizer. Possible values are: - `"finetuning"` or `ValidationMode.finetuning`: The finetuning mode. - `"test"` or `ValidationMode.test`: The test mode. It changes how the tokenizer validates the input and prepares the request to the model. """ return self._mode @property def bos_token_id(self) -> int: """ Id of the beginning of sentence token in the vocabulary. """ return self.tokenizer.instruct_tokenizer.tokenizer.bos_id @property def eos_token_id(self) -> int: """ Id of the end of sentence token in the vocabulary. """ return self.tokenizer.instruct_tokenizer.tokenizer.eos_id @property def unk_token_id(self) -> int: """ Id of the unknown token in the vocabulary. """ return self.tokenizer.instruct_tokenizer.tokenizer.unk_id @property def pad_token_id(self) -> int: """ Id of the padding token in the vocabulary. """ return self.tokenizer.instruct_tokenizer.tokenizer.pad_id @property def bos_token(self) -> str: """ String associated to the beginning of sentence token in the vocabulary. """ return self.convert_ids_to_tokens(self.bos_token_id) @property def eos_token(self) -> str: """ String associated to the end of sentence token in the vocabulary. """ return self.convert_ids_to_tokens(self.eos_token_id) @property def unk_token(self) -> str: """ String associated to the unknown token in the vocabulary. """ return self.convert_ids_to_tokens(self.unk_token_id) @property def pad_token(self) -> str: """ String associated to the padding token in the vocabulary. """ return self.convert_ids_to_tokens(self.pad_token_id) @property def all_special_ids(self) -> list[int]: """ `list[int]`: List the ids of the special tokens(`'<unk>'`, `'<cls>'`, etc.). """ return sorted(self._all_special_tokens_ids) @property def all_special_tokens(self) -> list[str]: """ `list[str]`: A list of all unique special tokens. """ return self.convert_ids_to_tokens(self.all_special_ids) @property def vocab_size(self) -> int: """ Returns the size of the vocabulary. `int`: Size of the vocabulary. """ return self.tokenizer.instruct_tokenizer.tokenizer.n_words def get_vocab(self) -> dict[str, int]: """ Returns the vocabulary as a dictionary of token to index. This is a lossy conversion. There may be multiple token ids that decode to the same string due to partial UTF-8 byte sequences being converted to �. Returns: `Dict[str, int]`: The vocabulary. """ if self._cache_get_vocab is None: # We reverse the order to make sure that the first token is the one to be returned when there are multiple tokens with the same string representation. vocab = self.tokenizer.instruct_tokenizer.tokenizer.vocab() self._cache_get_vocab = {token: self._piece_to_id(token, False) for token in vocab} # Order the dict. self._cache_get_vocab = dict( sorted(((k, v) for k, v in self._cache_get_vocab.items()), key=lambda x: x[1]) ) return self._cache_get_vocab def __len__(self): """ Size of the full vocabulary with the added tokens. """ return self.vocab_size @add_end_docstrings( ENCODE_KWARGS_DOCSTRING, """ **kwargs: Not supported by `MistralCommonBackend.encode`. Will raise an error if used. """, """ Returns: `list[int]`, `torch.Tensor`: The tokenized ids of the text. """, ) def encode( self, text: TextInput | EncodedInput, text_pair: None = None, add_special_tokens: bool = True, padding: bool | str | PaddingStrategy = False, truncation: bool | str | TruncationStrategy | None = None, max_length: int | None = None, stride: int = 0, pad_to_multiple_of: int | None = None, padding_side: str | None = None, return_tensors: str | TensorType | None = None, verbose: bool = True, **kwargs, ) -> list[int]: """ Converts a string to a sequence of ids (integer), using the tokenizer and vocabulary. Args: text (`str` or `list[int]`): The first sequence to be encoded. This can be a string or a list of integers (tokenized string ids). text_pair (`None`, *optional*): Not supported by `MistralCommonBackend.encode`. Kept to match `PreTrainedTokenizerBase.encode` signature. """ if kwargs: raise ValueError(f"Kwargs {list(kwargs.keys())} are not supported by `MistralCommonBackend.encode`.") if text_pair: raise ValueError("`MistralCommonBackend.encode` does not support `text_pair`.") padding_strategy, truncation_strategy, max_length, _ = self._get_padding_truncation_strategies( padding=padding, truncation=truncation, max_length=max_length, pad_to_multiple_of=pad_to_multiple_of, verbose=verbose, ) encoded_inputs = self._encode_plus( text, add_special_tokens=add_special_tokens, padding_strategy=padding_strategy, truncation_strategy=truncation_strategy, max_length=max_length, stride=stride, pad_to_multiple_of=pad_to_multiple_of, padding_side=padding_side, return_tensors=return_tensors, return_attention_mask=False, return_overflowing_tokens=False, return_special_tokens_mask=False, return_length=False, verbose=verbose, ) return encoded_inputs["input_ids"] def decode( self, token_ids: Union[int, list[int], list[list[int]], np.ndarray, "torch.Tensor"], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool | None = None, **kwargs, ) -> Union[str, list[str]]: """ Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special tokens and clean up tokenization spaces. Args: token_ids (`Union[int, list[int], list[list[int]], np.ndarray, torch.Tensor]`): A single sequence or a batch (list of sequences) of tokenized input ids. Can be obtained using the `__call__` method. skip_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not to remove special tokens in the decoding. clean_up_tokenization_spaces (`bool`, *optional*): Whether or not to clean up the tokenization spaces. If `None`, will default to `self.clean_up_tokenization_spaces`. kwargs (additional keyword arguments, *optional*): Not supported by `MistralCommonBackend.decode`. Will raise an error if used. Returns: `Union[str, list[str]]`: The decoded string for a single sequence, or a list of decoded strings for a batch of sequences. """ if kwargs: raise ValueError(f"Kwargs {list(kwargs.keys())} are not supported by `MistralCommonBackend.decode`.") token_ids = to_py_obj(token_ids) if isinstance(token_ids, (list, tuple)) and len(token_ids) > 0 and isinstance(token_ids[0], (list, tuple)): return self._batch_decode( sequences=token_ids, skip_special_tokens=skip_special_tokens, clean_up_tokenization_spaces=clean_up_tokenization_spaces, ) return self._decode( token_ids=token_ids, skip_special_tokens=skip_special_tokens, clean_up_tokenization_spaces=clean_up_tokenization_spaces, ) def batch_decode( self, sequences: Union[list[int], list[list[int]], np.ndarray, "torch.Tensor"], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool | None = None, **kwargs, ) -> list[str]: """ Convert a list of lists of token ids into a list of strings by calling decode. This method is provided for backwards compatibility. The `decode` method now handles batched input natively, so you can use `decode` directly instead of `batch_decode`. Args: sequences (`Union[list[int], list[list[int]], np.ndarray, torch.Tensor]`): List of tokenized input ids. Can be obtained using the `__call__` method. skip_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not to remove special tokens in the decoding. clean_up_tokenization_spaces (`bool`, *optional*): Whether or not to clean up the tokenization spaces. If `None`, will default to `self.clean_up_tokenization_spaces`. kwargs (additional keyword arguments, *optional*): Not supported by `MistralCommonBackend.batch_decode`. Will raise an error if used. Returns: `list[str]`: The list of decoded sentences. """ if kwargs: raise ValueError(f"Kwargs {list(kwargs.keys())} are not supported by `MistralCommonBackend.batch_decode`.") return self._batch_decode( sequences=sequences, skip_special_tokens=skip_special_tokens, clean_up_tokenization_spaces=clean_up_tokenization_spaces, ) def _decode( self, token_ids: Union[int, list[int], list[list[int]], np.ndarray, "torch.Tensor"], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool | None = None, ) -> str: clean_up_tokenization_spaces = clean_up_tokenization_spaces or self.cleanup_tokenization_spaces # Convert inputs to python lists if isinstance(token_ids, int): token_ids = [token_ids] token_ids = to_py_obj(token_ids) special_token_policy = SpecialTokenPolicy.IGNORE if skip_special_tokens else SpecialTokenPolicy.KEEP decoded_string = self.tokenizer.decode(token_ids, special_token_policy=special_token_policy) if clean_up_tokenization_spaces: decoded_string = self.clean_up_tokenization(decoded_string) # in the specific case of Voxtral, the added f"lang:xx" (always a two char language code since it follows ISO 639-1 alpha-2 format) # is not considered as a special token by mistral-common and is encoded/ decoded as normal text. # Nevertheless we should remove it to ease users life. if skip_special_tokens: decoded_string = re.sub(r"^lang:[a-z]{2}", "", decoded_string) return decoded_string def _batch_decode( self, sequences: Union[list[int], list[list[int]], np.ndarray, "torch.Tensor"], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool | None = None, ) -> list[str]: return [ self._decode( seq, skip_special_tokens=skip_special_tokens, clean_up_tokenization_spaces=clean_up_tokenization_spaces, ) for seq in sequences ] def _is_control_token(self, token_id: int) -> bool: if self._tokenizer_type == MistralTokenizerType.spm: return token_id in self.tokenizer.instruct_tokenizer.tokenizer._control_tokens elif self._tokenizer_type == MistralTokenizerType.tekken: return token_id < self.tokenizer.instruct_tokenizer.tokenizer.num_special_tokens else: raise ValueError(f"Unknown tokenizer type: {self._tokenizer_type}") @overload def convert_ids_to_tokens(self, ids: int, skip_special_tokens: bool = False) -> str: ... @overload def convert_ids_to_tokens(self, ids: list[int], skip_special_tokens: bool = False) -> list[str]: ... def convert_ids_to_tokens(self, ids: int | list[int], skip_special_tokens: bool = False) -> str | list[str]: """ Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and added tokens. Args: ids (`int` or `list[int]`): The token id (or token ids) to convert to tokens. skip_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not to remove special tokens in the decoding. Returns: `str` or `list[str]`: The decoded token(s). """ if isinstance(ids, int): one_token = True ids = [ids] else: one_token = False tokens: list[str] = [] for token_id in ids: if self._is_control_token(token_id) and skip_special_tokens: continue tokens.append(self.tokenizer.instruct_tokenizer.tokenizer.id_to_piece(token_id)) if one_token: if tokens == []: raise ValueError(f"Invalid token id {ids}.") return tokens[0] return tokens def _tekken_piece_to_id(self, piece: str, warn: bool) -> int: tekken_tokenizer = self.tokenizer.instruct_tokenizer.tokenizer assert isinstance(tekken_tokenizer, Tekkenizer), type(tekken_tokenizer) piece_bytes = piece.encode("utf-8") shift = tekken_tokenizer.num_special_tokens try: return shift + tekken_tokenizer._tekken_token2id_nospecial[piece_bytes] except KeyError: piece_str = piece_bytes.decode("utf-8") if piece_str in tekken_tokenizer._special_tokens_reverse_vocab: return tekken_tokenizer._special_tokens_reverse_vocab[piece_str] if warn: logger.warning("Failed to convert token %s to id, replacing with <unk>", piece_bytes) return tekken_tokenizer.unk_id def _piece_to_id(self, piece: str, warn: bool) -> int: if self._tokenizer_type == MistralTokenizerType.spm: return self.tokenizer.instruct_tokenizer.tokenizer._model.piece_to_id(piece) elif self._tokenizer_type == MistralTokenizerType.tekken: return self._tekken_piece_to_id(piece, warn) else: raise ValueError(f"Unknown tokenizer type: {self._tokenizer_type}") def convert_tokens_to_ids(self, tokens: str | list[str]) -> int | list[int]: """ Converts a token string (or a sequence of tokens) in a single integer id (or a sequence of ids), using the vocabulary. Args: tokens (`str` or `list[str]`): One or several token(s) to convert to token id(s). Returns: `int` or `list[int]`: The token id or list of token ids. """ if isinstance(tokens, str): one_token = True tokens = [tokens] else:
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/initialization.py
src/transformers/initialization.py
# Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from collections import defaultdict from contextlib import contextmanager import torch # Record all the torch primitives in advance, so that we can use them without them being modified when we patch torch # in context managers TORCH_INIT_FUNCTIONS = { "uniform_": torch.nn.init.uniform_, "normal_": torch.nn.init.normal_, "constant_": torch.nn.init.constant_, "ones_": torch.nn.init.ones_, "zeros_": torch.nn.init.zeros_, "eye_": torch.nn.init.eye_, "dirac_": torch.nn.init.dirac_, "xavier_uniform_": torch.nn.init.xavier_uniform_, "xavier_normal_": torch.nn.init.xavier_normal_, "kaiming_uniform_": torch.nn.init.kaiming_uniform_, "kaiming_normal_": torch.nn.init.kaiming_normal_, "trunc_normal_": torch.nn.init.trunc_normal_, "orthogonal_": torch.nn.init.orthogonal_, "sparse_": torch.nn.init.sparse_, } def uniform_( tensor: torch.Tensor, a: float = 0.0, b: float = 1.0, generator: torch.Generator | None = None ) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["uniform_"](tensor, a=a, b=b, generator=generator) return tensor def normal_( tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, generator: torch.Generator | None = None ) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["normal_"](tensor, mean=mean, std=std, generator=generator) return tensor def constant_(tensor: torch.Tensor, val: float) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["constant_"](tensor, val=val) return tensor def ones_(tensor: torch.Tensor) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["ones_"](tensor) return tensor def zeros_(tensor: torch.Tensor) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["zeros_"](tensor) return tensor def eye_(tensor: torch.Tensor) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["eye_"](tensor) return tensor def dirac_(tensor: torch.Tensor, groups: int = 1) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["dirac_"](tensor, groups=groups) return tensor def xavier_uniform_(tensor: torch.Tensor, gain: float = 1.0, generator: torch.Generator | None = None) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["xavier_uniform_"](tensor, gain=gain, generator=generator) return tensor def xavier_normal_(tensor: torch.Tensor, gain: float = 1.0, generator: torch.Generator | None = None) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["xavier_normal_"](tensor, gain=gain, generator=generator) return tensor def kaiming_uniform_( tensor: torch.Tensor, a: float = 0, mode: str = "fan_in", nonlinearity: str = "leaky_relu", generator: torch.Generator | None = None, ) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["kaiming_uniform_"]( tensor, a=a, mode=mode, nonlinearity=nonlinearity, generator=generator ) return tensor def kaiming_normal_( tensor: torch.Tensor, a: float = 0, mode: str = "fan_in", nonlinearity: str = "leaky_relu", generator: torch.Generator | None = None, ) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["kaiming_normal_"]( tensor, a=a, mode=mode, nonlinearity=nonlinearity, generator=generator ) return tensor def trunc_normal_( tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0, generator: torch.Generator | None = None, ) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["trunc_normal_"](tensor, mean=mean, std=std, a=a, b=b, generator=generator) return tensor def orthogonal_( tensor: torch.Tensor, gain: float = 1, generator: torch.Generator | None = None, ) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["orthogonal_"](tensor, gain=gain, generator=generator) return tensor def sparse_( tensor: torch.Tensor, sparsity: float, std: float = 0.01, generator: torch.Generator | None = None ) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): return TORCH_INIT_FUNCTIONS["sparse_"](tensor, sparsity=sparsity, std=std, generator=generator) return tensor def copy_(tensor: torch.Tensor, other: torch.Tensor) -> torch.Tensor: if not getattr(tensor, "_is_hf_initialized", False): with torch.no_grad(): return tensor.copy_(other) return tensor # Here, we need to check several modules imported, and hot patch all of them, as sometimes torch does # something like `from torch.nn.init import xavier_uniform_` in their internals (e.g in torch.nn.modules.activations, # where MultiHeadAttention lives), so the function name is binded at import time and just doing # `setattr(torch.nn.init, name, globals()[name])` is thus not enough # The following list should be enough for all torch versions we work with TORCH_MODULES_TO_PATCH = ( "torch.nn.init", "torch.nn.modules.activation", "torch.nn.modules.transformer", "torch.nn.modules.linear", "torch.nn.modules.loss", "torch.nn.modules.batchnorm", "torch.nn.modules.conv", "torch.nn.modules.normalization", "torch.nn.modules.rnn", "torch.nn.modules.sparse", ) @contextmanager def guard_torch_init_functions(): """ Guard the `torch.nn.init` primitive functions to behave exactly like the functions in this file, i.e. be protected against the `_is_hf_initialized` flag to avoid re-init if the param was already loaded. Usually, all models are using the init from `transformers` which are already guarded, but just to make extra sure and for remote code, we also use this context manager. """ originals = defaultdict(dict) try: # Replace all torch funcs by the ones in this file for module_name in TORCH_MODULES_TO_PATCH: if module_name in sys.modules: module = sys.modules[module_name] for func_name in TORCH_INIT_FUNCTIONS.keys(): if hasattr(module, func_name): originals[module][func_name] = getattr(module, func_name) setattr(module, func_name, globals()[func_name]) yield finally: # Set back the original functions on all modules for module, functions in originals.items(): for func_name, func in functions.items(): setattr(module, func_name, func) @contextmanager def no_init_weights(): """ Disable weight initialization both at the torch-level, and at the transformers-level (`init_weights`). This is used to speed-up initializing an empty model with deepspeed, as we do not initialize the model on meta device with deepspeed, but we still don't need to run expensive weight initializations as we are loading params afterwards. """ from .modeling_utils import PreTrainedModel def empty_func(*args, **kwargs): pass originals = defaultdict(dict) try: # Replace all torch funcs by empty ones for module_name in TORCH_MODULES_TO_PATCH: if module_name in sys.modules: module = sys.modules[module_name] for func_name in TORCH_INIT_FUNCTIONS.keys(): if hasattr(module, func_name): originals[module][func_name] = getattr(module, func_name) setattr(module, func_name, empty_func) # Also patch our own `init_weights` original_init_weights = PreTrainedModel.init_weights PreTrainedModel.init_weights = empty_func yield finally: # Set back the original torch functions on all modules for module, functions in originals.items(): for func_name, func in functions.items(): setattr(module, func_name, func) # Set back `init_weights` PreTrainedModel.init_weights = original_init_weights
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/trainer_utils.py
src/transformers/trainer_utils.py
# Copyright 2020-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PyTorch-independent utilities for the Trainer class. """ import copy import functools import gc import inspect import json import os import random import re import threading import time from collections.abc import Callable from functools import partial from typing import Any, NamedTuple import numpy as np from .utils import ( SAFE_WEIGHTS_INDEX_NAME, WEIGHTS_INDEX_NAME, ExplicitEnum, check_torch_load_is_safe, is_psutil_available, is_torch_available, is_torch_cuda_available, is_torch_hpu_available, is_torch_mlu_available, is_torch_mps_available, is_torch_musa_available, is_torch_npu_available, is_torch_xla_available, is_torch_xpu_available, requires_backends, ) if is_torch_available(): import torch from safetensors.torch import load_file as safe_load_file def seed_worker(worker_id: int, num_workers: int, rank: int): """ Helper function to set worker seed during Dataloader initialization. """ init_seed = torch.initial_seed() % 2**32 worker_seed = num_workers * rank + init_seed set_seed(worker_seed) def enable_full_determinism(seed: int, warn_only: bool = False): """ Helper function for reproducible behavior during distributed training. See https://pytorch.org/docs/stable/notes/randomness.html for pytorch """ # set seed first set_seed(seed) if is_torch_available(): # Enable PyTorch deterministic mode. This potentially requires either the environment # variable 'CUDA_LAUNCH_BLOCKING' or 'CUBLAS_WORKSPACE_CONFIG' to be set, # depending on the CUDA version, so we set them both here os.environ["CUDA_LAUNCH_BLOCKING"] = "1" os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":16:8" # The environment variable required to enable deterministic mode on Ascend NPUs. os.environ["ASCEND_LAUNCH_BLOCKING"] = "1" os.environ["HCCL_DETERMINISTIC"] = "1" os.environ["FLASH_ATTENTION_DETERMINISTIC"] = "1" torch.use_deterministic_algorithms(True, warn_only=warn_only) # Enable CUDNN deterministic mode torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def set_seed(seed: int, deterministic: bool = False): """ Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch` (if installed). Args: seed (`int`): The seed to set. deterministic (`bool`, *optional*, defaults to `False`): Whether to use deterministic algorithms where available. Can slow down training. """ random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) # ^^ safe to call this function even if cuda is not available if deterministic: torch.use_deterministic_algorithms(True) if is_torch_mlu_available(): torch.mlu.manual_seed_all(seed) if is_torch_musa_available(): torch.musa.manual_seed_all(seed) if is_torch_npu_available(): torch.npu.manual_seed_all(seed) if is_torch_hpu_available(): torch.hpu.manual_seed_all(seed) if is_torch_xpu_available(): torch.xpu.manual_seed_all(seed) def neftune_post_forward_hook(module, input, output): """ Implements the NEFTune forward pass for the model using forward hooks. Note this works only for torch.nn.Embedding layers. This method is slightly adapted from the original source code that can be found here: https://github.com/neelsjain/NEFTune Simply add it to your model as follows: ```python model = ... model.embed_tokens.neftune_noise_alpha = 0.1 model.embed_tokens.register_forward_hook(neftune_post_forward_hook) ``` Args: module (`torch.nn.Module`): The embedding module where the hook is attached. Note that you need to set `module.neftune_noise_alpha` to the desired noise alpha value. input (`torch.Tensor`): The input tensor to the model. output (`torch.Tensor`): The output tensor of the model (i.e. the embeddings). """ if module.training: dims = torch.tensor(output.size(1) * output.size(2)) mag_norm = module.neftune_noise_alpha / torch.sqrt(dims) output = output + torch.zeros_like(output).uniform_(-mag_norm, mag_norm) return output class EvalPrediction: """ Evaluation output (always contains labels), to be used to compute metrics. Parameters: predictions (`np.ndarray`): Predictions of the model. label_ids (`np.ndarray`): Targets to be matched. inputs (`np.ndarray`, *optional*): Input data passed to the model. losses (`np.ndarray`, *optional*): Loss values computed during evaluation. """ def __init__( self, predictions: np.ndarray | tuple[np.ndarray], label_ids: np.ndarray | tuple[np.ndarray], inputs: np.ndarray | tuple[np.ndarray] | None = None, losses: np.ndarray | tuple[np.ndarray] | None = None, ): self.predictions = predictions self.label_ids = label_ids self.inputs = inputs self.losses = losses self.elements = (self.predictions, self.label_ids) if self.inputs is not None: self.elements += (self.inputs,) if self.losses is not None: self.elements += (self.losses,) def __iter__(self): return iter(self.elements) def __getitem__(self, idx): if idx < 0 or idx >= len(self.elements): raise IndexError("tuple index out of range") return self.elements[idx] class EvalLoopOutput(NamedTuple): predictions: np.ndarray | tuple[np.ndarray] label_ids: np.ndarray | tuple[np.ndarray] | None metrics: dict[str, float] | None num_samples: int | None class PredictionOutput(NamedTuple): predictions: np.ndarray | tuple[np.ndarray] label_ids: np.ndarray | tuple[np.ndarray] | None metrics: dict[str, float] | None class TrainOutput(NamedTuple): global_step: int training_loss: float metrics: dict[str, float] PREFIX_CHECKPOINT_DIR = "checkpoint" _re_checkpoint = re.compile(r"^" + PREFIX_CHECKPOINT_DIR + r"\-(\d+)$") def get_last_checkpoint(folder): content = os.listdir(folder) checkpoints = [ path for path in content if _re_checkpoint.search(path) is not None and os.path.isdir(os.path.join(folder, path)) ] if len(checkpoints) == 0: return return os.path.join(folder, max(checkpoints, key=lambda x: int(_re_checkpoint.search(x).groups()[0]))) class IntervalStrategy(ExplicitEnum): NO = "no" STEPS = "steps" EPOCH = "epoch" class SaveStrategy(ExplicitEnum): NO = "no" STEPS = "steps" EPOCH = "epoch" BEST = "best" class HubStrategy(ExplicitEnum): END = "end" EVERY_SAVE = "every_save" CHECKPOINT = "checkpoint" ALL_CHECKPOINTS = "all_checkpoints" class BestRun(NamedTuple): """ The best run found by a hyperparameter search (see [`~Trainer.hyperparameter_search`]). Parameters: run_id (`str`): The id of the best run (if models were saved, the corresponding checkpoint will be in the folder ending with run-{run_id}). objective (`float`): The objective that was obtained for this run. hyperparameters (`dict[str, Any]`): The hyperparameters picked to get this run. run_summary (`Optional[Any]`): A summary of tuning experiments. `ray.tune.ExperimentAnalysis` object for Ray backend. """ run_id: str objective: float | list[float] hyperparameters: dict[str, Any] run_summary: Any | None = None def default_compute_objective(metrics: dict[str, float]) -> float: """ The default objective to maximize/minimize when doing an hyperparameter search. It is the evaluation loss if no metrics are provided to the [`Trainer`], the sum of all metrics otherwise. Args: metrics (`dict[str, float]`): The metrics returned by the evaluate method. Return: `float`: The objective to minimize or maximize """ metrics = copy.deepcopy(metrics) loss = metrics.pop("eval_loss", None) _ = metrics.pop("epoch", None) # Remove speed metrics speed_metrics = [m for m in metrics if m.endswith("_runtime") or m.endswith("_per_second")] for sm in speed_metrics: _ = metrics.pop(sm, None) return loss if len(metrics) == 0 else sum(metrics.values()) def default_hp_space_optuna(trial) -> dict[str, float]: from .integrations import is_optuna_available assert is_optuna_available(), "This function needs Optuna installed: `pip install optuna`" return { "learning_rate": trial.suggest_float("learning_rate", 1e-6, 1e-4, log=True), "num_train_epochs": trial.suggest_int("num_train_epochs", 1, 5), "seed": trial.suggest_int("seed", 1, 40), "per_device_train_batch_size": trial.suggest_categorical("per_device_train_batch_size", [4, 8, 16, 32, 64]), } def default_hp_space_ray(trial) -> dict[str, Any]: from .integrations import is_ray_tune_available assert is_ray_tune_available(), "This function needs ray installed: `pip install ray[tune]`" from ray import tune return { "learning_rate": tune.loguniform(1e-6, 1e-4), "num_train_epochs": tune.choice(list(range(1, 6))), "seed": tune.uniform(1, 40), "per_device_train_batch_size": tune.choice([4, 8, 16, 32, 64]), } def default_hp_space_wandb(trial) -> dict[str, Any]: from .integrations import is_wandb_available if not is_wandb_available(): raise ImportError("This function needs wandb installed: `pip install wandb`") return { "method": "random", "metric": {"name": "objective", "goal": "minimize"}, "parameters": { "learning_rate": {"distribution": "uniform", "min": 1e-6, "max": 1e-4}, "num_train_epochs": {"distribution": "int_uniform", "min": 1, "max": 6}, "seed": {"distribution": "int_uniform", "min": 1, "max": 40}, "per_device_train_batch_size": {"values": [4, 8, 16, 32, 64]}, }, } class HPSearchBackend(ExplicitEnum): OPTUNA = "optuna" RAY = "ray" WANDB = "wandb" def is_main_process(local_rank): """ Whether or not the current process is the local process, based on `xr.global_ordinal()` (for TPUs) first, then on `local_rank`. """ if is_torch_xla_available(): import torch_xla.runtime as xr return xr.global_ordinal() == 0 return local_rank in [-1, 0] def total_processes_number(local_rank): """ Return the number of processes launched in parallel. Works with `torch.distributed` and TPUs. """ if is_torch_xla_available(): import torch_xla.runtime as xr return xr.world_size() elif local_rank != -1 and is_torch_available(): import torch return torch.distributed.get_world_size() return 1 def speed_metrics(split, start_time, num_samples=None, num_steps=None, num_tokens=None): """ Measure and return speed performance metrics. This function requires a time snapshot `start_time` before the operation to be measured starts and this function should be run immediately after the operation to be measured has completed. Args: - split: name to prefix metric (like train, eval, test...) - start_time: operation start time - num_samples: number of samples processed - num_steps: number of steps processed - num_tokens: number of tokens processed """ runtime = time.time() - start_time result = {f"{split}_runtime": round(runtime, 4)} if runtime == 0: return result if num_samples is not None: samples_per_second = num_samples / runtime result[f"{split}_samples_per_second"] = round(samples_per_second, 3) if num_steps is not None: steps_per_second = num_steps / runtime result[f"{split}_steps_per_second"] = round(steps_per_second, 3) if num_tokens is not None: tokens_per_second = num_tokens / runtime result[f"{split}_tokens_per_second"] = round(tokens_per_second, 3) return result class SchedulerType(ExplicitEnum): """ Scheduler names for the parameter `lr_scheduler_type` in [`TrainingArguments`]. By default, it uses "linear". Internally, this retrieves `get_linear_schedule_with_warmup` scheduler from [`Trainer`]. Scheduler types: - "linear" = [`get_linear_schedule_with_warmup`] - "cosine" = [`get_cosine_schedule_with_warmup`] - "cosine_with_restarts" = [`get_cosine_with_hard_restarts_schedule_with_warmup`] - "polynomial" = [`get_polynomial_decay_schedule_with_warmup`] - "constant" = [`get_constant_schedule`] - "constant_with_warmup" = [`get_constant_schedule_with_warmup`] - "inverse_sqrt" = [`get_inverse_sqrt_schedule`] - "reduce_lr_on_plateau" = [`get_reduce_on_plateau_schedule`] - "cosine_with_min_lr" = [`get_cosine_with_min_lr_schedule_with_warmup`] - "cosine_warmup_with_min_lr" = [`get_cosine_with_min_lr_schedule_with_warmup_lr_rate`] - "warmup_stable_decay" = [`get_wsd_schedule`] """ LINEAR = "linear" COSINE = "cosine" COSINE_WITH_RESTARTS = "cosine_with_restarts" POLYNOMIAL = "polynomial" CONSTANT = "constant" CONSTANT_WITH_WARMUP = "constant_with_warmup" INVERSE_SQRT = "inverse_sqrt" REDUCE_ON_PLATEAU = "reduce_lr_on_plateau" COSINE_WITH_MIN_LR = "cosine_with_min_lr" COSINE_WARMUP_WITH_MIN_LR = "cosine_warmup_with_min_lr" WARMUP_STABLE_DECAY = "warmup_stable_decay" class TrainerMemoryTracker: """ A helper class that tracks cpu and gpu memory. This class will silently skip unless `psutil` is available. Install with `pip install psutil`. When a stage completes, it can pass metrics dict to update with the memory metrics gathered during this stage. Example : ```python self._memory_tracker = TrainerMemoryTracker(self.args.skip_memory_metrics) self._memory_tracker.start() # code ... metrics = {"train_runtime": 10.5} self._memory_tracker.stop_and_update_metrics(metrics) ``` To understand this class' intricacies please read the documentation of [`~Trainer.log_metrics`]. """ # map trainer methods to metrics prefix stages = { "__init__": "init", "train": "train", "_inner_training_loop": "train", "evaluate": "eval", "predict": "test", } def __init__(self, skip_memory_metrics=False): self.skip_memory_metrics = skip_memory_metrics if not is_psutil_available(): # soft dependency on psutil self.skip_memory_metrics = True if self.skip_memory_metrics: return import psutil if is_torch_cuda_available() or is_torch_mlu_available() or is_torch_musa_available(): import torch self.torch = torch self.gpu = {} elif is_torch_mps_available(): import torch self.torch = torch self.gpu = {} elif is_torch_xpu_available(): import torch self.torch = torch self.gpu = {} elif is_torch_npu_available(): import torch self.torch = torch self.gpu = {} elif is_torch_hpu_available(): import torch self.torch = torch self.gpu = {} else: self.torch = None self.process = psutil.Process() self.cur_stage = None self.cpu = {} self.init_reported = False def derive_stage(self): """derives the stage/caller name automatically""" caller = inspect.currentframe().f_back.f_back.f_code.co_name if caller in self.stages: return self.stages[caller] else: raise ValueError( f"was called from {caller}, but only expect to be called from one of {self.stages.keys()}" ) def cpu_mem_used(self): """get resident set size memory for the current process""" return self.process.memory_info().rss def peak_monitor_func(self): self.cpu_mem_used_peak = -1 while True: self.cpu_mem_used_peak = max(self.cpu_mem_used(), self.cpu_mem_used_peak) # can't sleep or will not catch the peak right (this comment is here on purpose) # time.sleep(0.001) # 1msec if not self.peak_monitoring: break def start(self): """start tracking for the caller's stage""" if self.skip_memory_metrics: return stage = self.derive_stage() # deal with nested calls of eval during train - simply ignore those if self.cur_stage is not None and self.cur_stage != stage: return self.cur_stage = stage gc.collect() if self.torch is not None: if torch.cuda.is_available(): self.torch.cuda.reset_peak_memory_stats() self.torch.cuda.empty_cache() elif is_torch_mlu_available(): self.torch.mlu.reset_peak_memory_stats() self.torch.mlu.empty_cache() elif is_torch_musa_available(): self.torch.musa.reset_peak_memory_stats() self.torch.musa.empty_cache() elif is_torch_xpu_available(): self.torch.xpu.reset_peak_memory_stats() self.torch.xpu.empty_cache() elif is_torch_npu_available(): self.torch.npu.reset_peak_memory_stats() self.torch.npu.empty_cache() elif is_torch_hpu_available(): self.torch.hpu.reset_peak_memory_stats() # not available on hpu as it reserves all device memory for the current process # self.torch.hpu.empty_cache() elif is_torch_mps_available(): self.torch.mps.empty_cache() # gpu if self.torch is not None: if torch.cuda.is_available(): self.gpu_mem_used_at_start = self.torch.cuda.memory_allocated() elif is_torch_mlu_available(): self.gpu_mem_used_at_start = self.torch.mlu.memory_allocated() elif is_torch_musa_available(): self.gpu_mem_used_at_start = self.torch.musa.memory_allocated() elif is_torch_xpu_available(): self.gpu_mem_used_at_start = self.torch.xpu.memory_allocated() elif is_torch_npu_available(): self.gpu_mem_used_at_start = self.torch.npu.memory_allocated() elif is_torch_hpu_available(): self.gpu_mem_used_at_start = self.torch.hpu.memory_allocated() elif is_torch_mps_available(): self.gpu_mem_used_at_start = self.torch.mps.current_allocated_memory() # cpu self.cpu_mem_used_at_start = self.cpu_mem_used() self.peak_monitoring = True peak_monitor_thread = threading.Thread(target=self.peak_monitor_func) peak_monitor_thread.daemon = True peak_monitor_thread.start() def stop(self, stage): """stop tracking for the passed stage""" # deal with nested calls of eval during train - simply ignore those if self.cur_stage is not None and self.cur_stage != stage: return # this sends a signal to peak_monitor_func to complete its loop self.peak_monitoring = False # first ensure all objects get collected and their memory is freed gc.collect() if self.torch is not None: if torch.cuda.is_available(): self.torch.cuda.empty_cache() elif is_torch_mlu_available(): self.torch.mlu.empty_cache() elif is_torch_musa_available(): self.torch.musa.empty_cache() elif is_torch_xpu_available(): self.torch.xpu.empty_cache() elif is_torch_npu_available(): self.torch.npu.empty_cache() elif is_torch_hpu_available(): # not available on hpu as it reserves all device memory for the current process # self.torch.npu.empty_cache() pass elif is_torch_mps_available(): self.torch.mps.empty_cache() # concepts: # - alloc_delta: the difference of allocated memory between the end and the start # - peaked_delta: the difference between the peak memory and the current memory # in order to know how much memory the measured code consumed one needs to sum these two # gpu if self.torch is not None: if torch.cuda.is_available(): self.gpu_mem_used_now = self.torch.cuda.memory_allocated() self.gpu_mem_used_peak = self.torch.cuda.max_memory_allocated() elif is_torch_mlu_available(): self.gpu_mem_used_now = self.torch.mlu.memory_allocated() self.gpu_mem_used_peak = self.torch.mlu.max_memory_allocated() elif is_torch_musa_available(): self.gpu_mem_used_now = self.torch.musa.memory_allocated() self.gpu_mem_used_peak = self.torch.musa.max_memory_allocated() elif is_torch_xpu_available(): self.gpu_mem_used_now = self.torch.xpu.memory_allocated() self.gpu_mem_used_peak = self.torch.xpu.max_memory_allocated() elif is_torch_npu_available(): self.gpu_mem_used_now = self.torch.npu.memory_allocated() self.gpu_mem_used_peak = self.torch.npu.max_memory_allocated() elif is_torch_hpu_available(): self.gpu_mem_used_now = self.torch.hpu.memory_allocated() self.gpu_mem_used_peak = self.torch.hpu.max_memory_allocated() elif is_torch_mps_available(): self.gpu_mem_used_now = self.torch.mps.current_allocated_memory() # self.torch.mps.max_memory_allocated() does not exist yet self.gpu_mem_used_peak = None else: raise ValueError("No available GPU device found!") self.gpu[self.cur_stage] = { "begin": self.gpu_mem_used_at_start, "end": self.gpu_mem_used_now, "alloc": (self.gpu_mem_used_now - self.gpu_mem_used_at_start), } if self.gpu_mem_used_peak is not None: self.gpu[self.cur_stage]["peaked"] = max(0, self.gpu_mem_used_peak - self.gpu_mem_used_now) else: self.gpu[self.cur_stage]["peaked"] = "Not available" # cpu self.cpu_mem_used_now = self.cpu_mem_used() self.cpu[self.cur_stage] = { "begin": self.cpu_mem_used_at_start, "end": self.cpu_mem_used_now, "alloc": (self.cpu_mem_used_now - self.cpu_mem_used_at_start), "peaked": max(0, self.cpu_mem_used_peak - self.cpu_mem_used_now), } # reset - cycle finished self.cur_stage = None def update_metrics(self, stage, metrics): """updates the metrics""" if self.skip_memory_metrics: return # deal with nested calls of eval during train - simply ignore those if self.cur_stage is not None and self.cur_stage != stage: return # since we don't have a way to return init metrics, we push them into the first of train/val/predict stages = [stage] if not self.init_reported: stages.insert(0, "init") self.init_reported = True for stage in stages: for t in ["alloc", "peaked"]: if stage in self.cpu and t in self.cpu[stage]: metrics[f"{stage}_mem_cpu_{t}_delta"] = self.cpu[stage][t] if self.torch is not None and stage in self.gpu and t in self.gpu[stage]: metrics[f"{stage}_mem_gpu_{t}_delta"] = self.gpu[stage][t] # if we need additional debug info, enable the following # for t in ["begin", "end"]: # if stage in self.cpu and t in self.cpu[stage]: # metrics[f"{stage}_mem_cpu_{t}"] = self.cpu[stage][t] # if self.torch is not None and stage in self.gpu and t in self.gpu[stage]: # metrics[f"{stage}_mem_gpu_{t}"] = self.gpu[stage][t] # since memory can be allocated before init, and it might be difficult to track overall # memory usage, in particular for GPU, let's report memory usage at the point init was called if stages[0] == "init": metrics["before_init_mem_cpu"] = self.cpu["init"]["begin"] if self.torch is not None: metrics["before_init_mem_gpu"] = self.gpu["init"]["begin"] # if we also wanted to report any additional memory allocations in between init and # whatever the next stage was we could also report this: # if self.cpu["init"]["end"] != self.cpu[stage]["begin"]: # metrics[f"after_init_mem_cpu_delta"] = self.cpu[stage]["begin"] - self.cpu["init"]["end"] # if self.torch is not None and self.gpu["init"]["end"] != self.gpu[stage]["begin"]: # metrics[f"after_init_mem_gpu_delta"] = self.gpu[stage]["begin"] - self.gpu["init"]["end"] def stop_and_update_metrics(self, metrics=None): """combine stop and metrics update in one call for simpler code""" if self.skip_memory_metrics: return stage = self.derive_stage() self.stop(stage) # init doesn't have metrics to update so we just save that data for later stages to retrieve if metrics is not None: self.update_metrics(stage, metrics) def has_length(dataset): """ Checks if the dataset implements __len__() and it doesn't raise an error """ try: return len(dataset) is not None except TypeError: # TypeError: len() of unsized object return False except AttributeError: # Ray DataSets raises an AttributeError: https://github.com/ray-project/ray/blob/master/python/ray/data/dataset.py#L5616 return False def denumpify_detensorize(metrics): """ Recursively calls `.item()` on the element of the dictionary passed """ if isinstance(metrics, (list, tuple)): return type(metrics)(denumpify_detensorize(m) for m in metrics) elif isinstance(metrics, dict): return type(metrics)({k: denumpify_detensorize(v) for k, v in metrics.items()}) elif isinstance(metrics, np.generic): return metrics.item() elif is_torch_available() and isinstance(metrics, torch.Tensor) and metrics.numel() == 1: return metrics.item() return metrics def number_of_arguments(func): """ Return the number of arguments of the passed function, even if it's a partial function. """ if isinstance(func, functools.partial): total_args = len(inspect.signature(func.func).parameters) return total_args - len(func.args) - len(func.keywords) return len(inspect.signature(func).parameters) def find_executable_batch_size( function: Callable | None = None, starting_batch_size: int = 128, auto_find_batch_size: bool = False ): """ Args: A basic decorator that will try to execute `function`. If it fails from exceptions related to out-of-memory or CUDNN, the batch size is multiplied by 0.9 and passed to `function`. `function` must take in a `batch_size` parameter as its first argument. function (`Callable`, *optional*) A function to wrap starting_batch_size (`int`, *optional*) The batch size to try and fit into memory auto_find_batch_size (`bool`, *optional*) If False, will just execute `function` """ if function is None: return functools.partial( find_executable_batch_size, starting_batch_size=starting_batch_size, auto_find_batch_size=auto_find_batch_size, ) if auto_find_batch_size: requires_backends(find_executable_batch_size, "accelerate") from accelerate.utils import find_executable_batch_size as accelerate_find_executable_batch_size return accelerate_find_executable_batch_size(function=function, starting_batch_size=starting_batch_size) return functools.partial(function, batch_size=starting_batch_size) class FSDPOption(ExplicitEnum): FULL_SHARD = "full_shard" SHARD_GRAD_OP = "shard_grad_op" NO_SHARD = "no_shard" HYBRID_SHARD = "hybrid_shard" HYBRID_SHARD_ZERO2 = "hybrid_shard_zero2" OFFLOAD = "offload" AUTO_WRAP = "auto_wrap" class RemoveColumnsCollator: """Wrap the data collator to remove unused columns before they are passed to the collator.""" def __init__( self, data_collator, signature_columns, logger=None, model_name: str | None = None, description: str | None = None, ): self.data_collator = data_collator self.signature_columns = signature_columns self.logger = logger self.description = description self.model_name = model_name self.message_logged = False def _remove_columns(self, feature: dict) -> dict: if not isinstance(feature, dict): return feature if not self.message_logged and self.logger and self.model_name: ignored_columns = list(set(feature.keys()) - set(self.signature_columns)) if len(ignored_columns) > 0: dset_description = "" if self.description is None else f"in the {self.description} set" self.logger.info( f"The following columns {dset_description} don't have a corresponding argument in " f"`{self.model_name}.forward` and have been ignored: {', '.join(ignored_columns)}." f" If {', '.join(ignored_columns)} are not expected by `{self.model_name}.forward`, " " you can safely ignore this message." ) self.message_logged = True return {k: v for k, v in feature.items() if k in self.signature_columns} def __call__(self, features: list[dict]): features = [self._remove_columns(feature) for feature in features] return self.data_collator(features) def check_target_module_exists(optim_target_modules, key: str, return_is_regex: bool = False): """A helper method to check if the passed module's key name matches any of the target modules in the optim_target_modules. Args: optim_target_modules (`Union[str, list[str]]`): A list of strings to try to match. Can be also a full string. key (`str`): A key to search any matches in optim_target_modules return_is_regex (`bool`): If set to `True`, the method will return whether the passed `optim_target_modules` is a regex or not. Returns: `bool` : True of match object if key matches any target modules from config, False or None if no match found `bool` : If the matched target module is a regex to silence out the warnings in Trainer for extra modules being found (only if `target_module_found=True` for an array of regex). """ target_module_found = False is_regex = False if isinstance(optim_target_modules, str): target_module_found = bool(re.fullmatch(optim_target_modules, key)) is_regex = optim_target_modules != key elif key in optim_target_modules: # from here, target_module_found must be a list of str # this module is specified directly in target_modules
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/trainer_callback.py
src/transformers/trainer_callback.py
# Copyright 2020-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Callbacks to use with the Trainer class and customize the training loop. """ import dataclasses import json import math from dataclasses import dataclass import numpy as np from tqdm.auto import tqdm from .trainer_utils import IntervalStrategy, SaveStrategy, has_length from .training_args import TrainingArguments from .utils import logging logger = logging.get_logger(__name__) @dataclass class TrainerState: """ A class containing the [`Trainer`] inner state that will be saved along the model and optimizer when checkpointing and passed to the [`TrainerCallback`]. <Tip> In all this class, one step is to be understood as one update step. When using gradient accumulation, one update step may require several forward and backward passes: if you use `gradient_accumulation_steps=n`, then one update step requires going through *n* batches. </Tip> Args: epoch (`float`, *optional*): Only set during training, will represent the epoch the training is at (the decimal part being the percentage of the current epoch completed). global_step (`int`, *optional*, defaults to 0): During training, represents the number of update steps completed. max_steps (`int`, *optional*, defaults to 0): The number of update steps to do during the current training. logging_steps (`int`, *optional*, defaults to 500): Log every X updates steps eval_steps (`int`, *optional*): Run an evaluation every X steps. save_steps (`int`, *optional*, defaults to 500): Save checkpoint every X updates steps. train_batch_size (`int`, *optional*): The batch size for the training dataloader. Only needed when `auto_find_batch_size` has been used. num_input_tokens_seen (`int`, *optional*, defaults to 0): When tracking the inputs tokens, the number of tokens seen during training (number of input tokens, not the number of prediction tokens). total_flos (`float`, *optional*, defaults to 0): The total number of floating operations done by the model since the beginning of training (stored as floats to avoid overflow). log_history (`list[dict[str, float]]`, *optional*): The list of logs done since the beginning of training. best_metric (`float`, *optional*): When tracking the best model, the value of the best metric encountered so far. best_global_step (`int`, *optional*): When tracking the best model, the step at which the best metric was encountered. Used for setting `best_model_checkpoint`. best_model_checkpoint (`str`, *optional*): When tracking the best model, the value of the name of the checkpoint for the best model encountered so far. is_local_process_zero (`bool`, *optional*, defaults to `True`): Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several machines) main process. is_world_process_zero (`bool`, *optional*, defaults to `True`): Whether or not this process is the global main process (when training in a distributed fashion on several machines, this is only going to be `True` for one process). is_hyper_param_search (`bool`, *optional*, defaults to `False`): Whether we are in the process of a hyper parameter search using Trainer.hyperparameter_search. This will impact the way data will be logged in TensorBoard. stateful_callbacks (`list[StatefulTrainerCallback]`, *optional*): Callbacks attached to the `Trainer` that should have their states be saved or restored. Relevant callbacks should implement a `state` and `from_state` function. """ epoch: float | None = None global_step: int = 0 max_steps: int = 0 logging_steps: int = 500 eval_steps: int = 500 save_steps: int = 500 train_batch_size: int | None = None num_train_epochs: int = 0 num_input_tokens_seen: int = 0 total_flos: float = 0 log_history: list[dict[str, float]] = None best_metric: float | None = None best_global_step: int | None = None best_model_checkpoint: str | None = None is_local_process_zero: bool = True is_world_process_zero: bool = True is_hyper_param_search: bool = False trial_name: str | None = None trial_params: dict[str, str | float | int | bool] | None = None stateful_callbacks: list["TrainerCallback"] | None = None def __post_init__(self): if self.log_history is None: self.log_history = [] if self.stateful_callbacks is None: self.stateful_callbacks = {} elif isinstance(self.stateful_callbacks, dict): # We are loading the callbacks in from the state file, no need to process them pass else: # Saveable callbacks get stored as dict of kwargs stateful_callbacks = {} for callback in self.stateful_callbacks: if not isinstance(callback, (ExportableState)): raise TypeError( f"All callbacks passed to be saved must inherit `ExportableState`, but received {type(callback)}" ) name = callback.__class__.__name__ if name in stateful_callbacks: # We can have multiple versions of the same callback # if so, we store them as a list of states to restore if not isinstance(stateful_callbacks[name], list): stateful_callbacks[name] = [stateful_callbacks[name]] stateful_callbacks[name].append(callback.state()) else: stateful_callbacks[name] = callback.state() self.stateful_callbacks = stateful_callbacks def save_to_json(self, json_path: str): """Save the content of this instance in JSON format inside `json_path`.""" json_string = json.dumps(dataclasses.asdict(self), indent=2, sort_keys=True) + "\n" with open(json_path, "w", encoding="utf-8") as f: f.write(json_string) @classmethod def load_from_json(cls, json_path: str): """Create an instance from the content of `json_path`.""" with open(json_path, encoding="utf-8") as f: text = f.read() return cls(**json.loads(text)) def compute_steps(self, args, max_steps): """ Calculates and stores the absolute value for logging, eval, and save steps based on if it was a proportion or not. """ for step_kind in ("logging", "eval", "save"): num_steps = getattr(args, f"{step_kind}_steps") if num_steps is not None: if num_steps < 1: num_steps = math.ceil(max_steps * num_steps) setattr(self, f"{step_kind}_steps", num_steps) def init_training_references(self, trainer, max_steps, num_train_epochs, trial): """ Stores the initial training references needed in `self` """ if trainer.hp_name is not None and trainer._trial is not None: # use self._trial because the Optuna hpo only call `_hp_search_setup(trial)` instead of passing trial # parameter to Train when using DDP. self.trial_name = trainer.hp_name(trainer._trial) self.trial_params = None if trial is not None: from transformers.integrations import hp_params self.trial_params = hp_params(trial) self.max_steps = max_steps self.num_train_epochs = num_train_epochs self.is_local_process_zero = trainer.is_local_process_zero() self.is_world_process_zero = trainer.is_world_process_zero() class ExportableState: """ A class for objects that include the ability to have its state be saved during `Trainer._save_checkpoint` and loaded back in during `Trainer._load_from_checkpoint`. These must implement a `state` function that gets called during the respective Trainer function call. It should only include parameters and attributes needed to recreate the state at a particular time, to avoid utilizing pickle/maintain standard file IO writing. Example: ```python class EarlyStoppingCallback(TrainerCallback, ExportableState): def __init__(self, early_stopping_patience: int = 1, early_stopping_threshold: Optional[float] = 0.0): self.early_stopping_patience = early_stopping_patience self.early_stopping_threshold = early_stopping_threshold # early_stopping_patience_counter denotes the number of times validation metrics failed to improve. self.early_stopping_patience_counter = 0 def state(self) -> dict: return { "args": { "early_stopping_patience": self.early_stopping_patience, "early_stopping_threshold": self.early_stopping_threshold, }, "attributes": { "early_stopping_patience_counter": self.early_stopping_patience_counter, } } ```""" def state(self) -> dict: raise NotImplementedError("You must implement a `state` function to utilize this class.") @classmethod def from_state(cls, state): instance = cls(**state["args"]) for k, v in state["attributes"].items(): setattr(instance, k, v) return instance @dataclass class TrainerControl(ExportableState): """ A class that handles the [`Trainer`] control flow. This class is used by the [`TrainerCallback`] to activate some switches in the training loop. Args: should_training_stop (`bool`, *optional*, defaults to `False`): Whether or not the training should be interrupted. If `True`, this variable will not be set back to `False`. The training will just stop. should_epoch_stop (`bool`, *optional*, defaults to `False`): Whether or not the current epoch should be interrupted. If `True`, this variable will be set back to `False` at the beginning of the next epoch. should_save (`bool`, *optional*, defaults to `False`): Whether or not the model should be saved at this step. If `True`, this variable will be set back to `False` at the beginning of the next step. should_evaluate (`bool`, *optional*, defaults to `False`): Whether or not the model should be evaluated at this step. If `True`, this variable will be set back to `False` at the beginning of the next step. should_log (`bool`, *optional*, defaults to `False`): Whether or not the logs should be reported at this step. If `True`, this variable will be set back to `False` at the beginning of the next step. """ should_training_stop: bool = False should_epoch_stop: bool = False should_save: bool = False should_evaluate: bool = False should_log: bool = False def _new_training(self): """Internal method that resets the variable for a new training.""" self.should_training_stop = False def _new_epoch(self): """Internal method that resets the variable for a new epoch.""" self.should_epoch_stop = False def _new_step(self): """Internal method that resets the variable for a new step.""" self.should_save = False self.should_evaluate = False self.should_log = False def state(self) -> dict: return { "args": { "should_training_stop": self.should_training_stop, "should_epoch_stop": self.should_epoch_stop, "should_save": self.should_save, "should_evaluate": self.should_evaluate, "should_log": self.should_log, }, "attributes": {}, } class TrainerCallback: # no-format """ A class for objects that will inspect the state of the training loop at some events and take some decisions. At each of those events the following arguments are available: Args: args ([`TrainingArguments`]): The training arguments used to instantiate the [`Trainer`]. state ([`TrainerState`]): The current state of the [`Trainer`]. control ([`TrainerControl`]): The object that is returned to the [`Trainer`] and can be used to make some decisions. model ([`PreTrainedModel`] or `torch.nn.Module`): The model being trained. processing_class ([`PreTrainedTokenizer` or `BaseImageProcessor` or `ProcessorMixin` or `FeatureExtractionMixin`]): The processing class used for encoding the data. Can be a tokenizer, a processor, an image processor or a feature extractor. optimizer (`torch.optim.Optimizer`): The optimizer used for the training steps. lr_scheduler (`torch.optim.lr_scheduler.LambdaLR`): The scheduler used for setting the learning rate. train_dataloader (`torch.utils.data.DataLoader`, *optional*): The current dataloader used for training. eval_dataloader (`torch.utils.data.DataLoader`, *optional*): The current dataloader used for evaluation. metrics (`dict[str, float]`): The metrics computed by the last evaluation phase. Those are only accessible in the event `on_evaluate`. logs (`dict[str, float]`): The values to log. Those are only accessible in the event `on_log`. The `control` object is the only one that can be changed by the callback, in which case the event that changes it should return the modified version. The argument `args`, `state` and `control` are positionals for all events, all the others are grouped in `kwargs`. You can unpack the ones you need in the signature of the event using them. As an example, see the code of the simple [`~transformers.PrinterCallback`]. Example: ```python class PrinterCallback(TrainerCallback): def on_log(self, args, state, control, logs=None, **kwargs): _ = logs.pop("total_flos", None) if state.is_local_process_zero: print(logs) ```""" def on_init_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the end of the initialization of the [`Trainer`]. """ def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the beginning of training. """ def on_train_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the end of training. """ def on_epoch_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the beginning of an epoch. """ def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the end of an epoch. """ def on_step_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the beginning of a training step. If using gradient accumulation, one training step might take several inputs. """ def on_pre_optimizer_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called before the optimizer step but after gradient clipping. Useful for monitoring gradients. """ def on_optimizer_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called after the optimizer step but before gradients are zeroed out. Useful for monitoring gradients. """ def on_substep_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the end of an substep during gradient accumulation. """ def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the end of a training step. If using gradient accumulation, one training step might take several inputs. """ def on_evaluate(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called after an evaluation phase. """ def on_predict(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, metrics, **kwargs): """ Event called after a successful prediction. """ def on_save(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called after a checkpoint save. """ def on_log(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called after logging the last logs. """ def on_prediction_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called after a prediction step. """ def on_push_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called before pushing the model to the hub, at the beginning of Trainer.push_to_hub and Trainer._push_from_checkpoint. """ class CallbackHandler(TrainerCallback): """Internal class that just calls the list of callbacks in order.""" def __init__(self, callbacks, model, processing_class, optimizer, lr_scheduler): self.callbacks = [] for cb in callbacks: self.add_callback(cb) self.model = model self.processing_class = processing_class self.optimizer = optimizer self.lr_scheduler = lr_scheduler self.train_dataloader = None self.eval_dataloader = None if not any(isinstance(cb, DefaultFlowCallback) for cb in self.callbacks): logger.warning( "The Trainer will not work properly if you don't have a `DefaultFlowCallback` in its callbacks. You\n" + "should add one before training with `trainer.add_callback(DefaultFlowCallback). The current list of" + "callbacks is\n:" + self.callback_list ) def add_callback(self, callback): cb = callback() if isinstance(callback, type) else callback cb_class = callback if isinstance(callback, type) else callback.__class__ if cb_class in [c.__class__ for c in self.callbacks]: logger.warning( f"You are adding a {cb_class} to the callbacks of this Trainer, but there is already one. The current" + "list of callbacks is\n:" + self.callback_list ) self.callbacks.append(cb) def pop_callback(self, callback): if isinstance(callback, type): for cb in self.callbacks: if isinstance(cb, callback): self.callbacks.remove(cb) return cb else: for cb in self.callbacks: if cb == callback: self.callbacks.remove(cb) return cb def remove_callback(self, callback): if isinstance(callback, type): for cb in self.callbacks: if isinstance(cb, callback): self.callbacks.remove(cb) return else: self.callbacks.remove(callback) @property def callback_list(self): return "\n".join(cb.__class__.__name__ for cb in self.callbacks) def on_init_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_init_end", args, state, control) def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): control.should_training_stop = False return self.call_event("on_train_begin", args, state, control) def on_train_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_train_end", args, state, control) def on_epoch_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): control.should_epoch_stop = False return self.call_event("on_epoch_begin", args, state, control) def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_epoch_end", args, state, control) def on_step_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): control.should_log = False control.should_evaluate = False control.should_save = False return self.call_event("on_step_begin", args, state, control) def on_pre_optimizer_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_pre_optimizer_step", args, state, control) def on_optimizer_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_optimizer_step", args, state, control) def on_substep_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_substep_end", args, state, control) def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_step_end", args, state, control) def on_evaluate(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, metrics): control.should_evaluate = False return self.call_event("on_evaluate", args, state, control, metrics=metrics) def on_predict(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, metrics): return self.call_event("on_predict", args, state, control, metrics=metrics) def on_save(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): control.should_save = False return self.call_event("on_save", args, state, control) def on_log(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, logs): control.should_log = False return self.call_event("on_log", args, state, control, logs=logs) def on_prediction_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_prediction_step", args, state, control) def on_push_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): return self.call_event("on_push_begin", args, state, control, **kwargs) def call_event(self, event, args, state, control, **kwargs): for callback in self.callbacks: result = getattr(callback, event)( args, state, control, model=self.model, processing_class=self.processing_class, optimizer=self.optimizer, lr_scheduler=self.lr_scheduler, train_dataloader=self.train_dataloader, eval_dataloader=self.eval_dataloader, **kwargs, ) # A Callback can skip the return of `control` if it doesn't change it. if result is not None: control = result return control class DefaultFlowCallback(TrainerCallback): """ A [`TrainerCallback`] that handles the default flow of the training loop for logs, evaluation and checkpoints. """ def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): # Log if state.global_step == 1 and args.logging_first_step: control.should_log = True if args.logging_strategy == IntervalStrategy.STEPS and state.global_step % state.logging_steps == 0: control.should_log = True # Evaluate if ( args.eval_strategy == IntervalStrategy.STEPS and state.global_step % state.eval_steps == 0 and args.eval_delay <= state.global_step ): control.should_evaluate = True # Save if ( args.save_strategy == SaveStrategy.STEPS and state.save_steps > 0 and state.global_step % state.save_steps == 0 ): control.should_save = True # End training if state.global_step >= state.max_steps: control.should_training_stop = True # Save the model at the end if we have a save strategy if args.save_strategy == SaveStrategy.STEPS: control.should_save = True return control def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): # Log if args.logging_strategy == IntervalStrategy.EPOCH: control.should_log = True # Evaluate if args.eval_strategy == IntervalStrategy.EPOCH and args.eval_delay <= state.epoch: control.should_evaluate = True # Save if args.save_strategy == SaveStrategy.EPOCH: control.should_save = True return control class ProgressCallback(TrainerCallback): """ A [`TrainerCallback`] that displays the progress of training or evaluation. You can modify `max_str_len` to control how long strings are truncated when logging. """ def __init__(self, max_str_len: int = 100): """ Initialize the callback with optional max_str_len parameter to control string truncation length. Args: max_str_len (`int`): Maximum length of strings to display in logs. Longer strings will be truncated with a message. """ self.training_bar = None self.prediction_bar = None self.max_str_len = max_str_len def on_train_begin(self, args, state, control, **kwargs): if state.is_world_process_zero: self.training_bar = tqdm(total=state.max_steps, dynamic_ncols=True) self.current_step = 0 def on_step_end(self, args, state, control, **kwargs): if state.is_world_process_zero: self.training_bar.update(state.global_step - self.current_step) self.current_step = state.global_step def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs): if state.is_world_process_zero and has_length(eval_dataloader): if self.prediction_bar is None: self.prediction_bar = tqdm( total=len(eval_dataloader), leave=self.training_bar is None, dynamic_ncols=True ) self.prediction_bar.update(1) def on_evaluate(self, args, state, control, **kwargs): if state.is_world_process_zero: if self.prediction_bar is not None: self.prediction_bar.close() self.prediction_bar = None def on_predict(self, args, state, control, **kwargs): if state.is_world_process_zero: if self.prediction_bar is not None: self.prediction_bar.close() self.prediction_bar = None def on_log(self, args, state, control, logs=None, **kwargs): if state.is_world_process_zero and self.training_bar is not None: # make a shallow copy of logs so we can mutate the fields copied # but avoid doing any value pickling. shallow_logs = {} for k, v in logs.items(): if isinstance(v, str) and len(v) > self.max_str_len: shallow_logs[k] = ( f"[String too long to display, length: {len(v)} > {self.max_str_len}. " "Consider increasing `max_str_len` if needed.]" ) if isinstance(v, float): # Format floats for better readability shallow_logs[k] = f"{v:.4g}" else: shallow_logs[k] = v _ = shallow_logs.pop("total_flos", None) self.training_bar.write(str(shallow_logs)) def on_train_end(self, args, state, control, **kwargs): if state.is_world_process_zero: self.training_bar.close() self.training_bar = None class PrinterCallback(TrainerCallback): """ A bare [`TrainerCallback`] that just prints the logs. """ def on_log(self, args, state, control, logs=None, **kwargs): _ = logs.pop("total_flos", None) if state.is_local_process_zero: if logs is not None: logs = {k: (f"{v:.4g}" if isinstance(v, float) else v) for k, v in logs.items()} print(logs) class EarlyStoppingCallback(TrainerCallback, ExportableState): """ A [`TrainerCallback`] that handles early stopping. Args: early_stopping_patience (`int`): Use with `metric_for_best_model` to stop training when the specified metric worsens for `early_stopping_patience` evaluation calls. early_stopping_threshold(`float`, *optional*): Use with TrainingArguments `metric_for_best_model` and `early_stopping_patience` to denote how much the specified metric must improve to satisfy early stopping conditions. ` This callback depends on [`TrainingArguments`] argument *load_best_model_at_end* functionality to set best_metric in [`TrainerState`]. Note that if the [`TrainingArguments`] argument *save_steps* differs from *eval_steps*, the early stopping will not occur until the next save step. """ def __init__(self, early_stopping_patience: int = 1, early_stopping_threshold: float | None = 0.0): self.early_stopping_patience = early_stopping_patience self.early_stopping_threshold = early_stopping_threshold # early_stopping_patience_counter denotes the number of times validation metrics failed to improve. self.early_stopping_patience_counter = 0 def check_metric_value(self, args, state, control, metric_value): # best_metric is set by code for load_best_model operator = np.greater if args.greater_is_better else np.less if state.best_metric is None or ( operator(metric_value, state.best_metric) and abs(metric_value - state.best_metric) > self.early_stopping_threshold ): self.early_stopping_patience_counter = 0 else: self.early_stopping_patience_counter += 1 def on_train_begin(self, args, state, control, **kwargs): if not args.load_best_model_at_end: logger.warning( "Using EarlyStoppingCallback without load_best_model_at_end=True. " "Once training is finished, the best model will not be loaded automatically." ) assert args.metric_for_best_model is not None, ( "EarlyStoppingCallback requires metric_for_best_model to be defined" ) assert args.eval_strategy != IntervalStrategy.NO, ( "EarlyStoppingCallback requires IntervalStrategy of steps or epoch" ) def on_evaluate(self, args, state, control, metrics, **kwargs): metric_to_check = args.metric_for_best_model if not metric_to_check.startswith("eval_"):
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/modeling_attn_mask_utils.py
src/transformers/modeling_attn_mask_utils.py
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ IMPORTANT NOTICE: Every class and function in this file is deprecated in favor of using the much more general `masking_utils.py` primitives. New code should not rely on it, it is only kept for backward compatibility for now, and will be removed in the future. """ from dataclasses import dataclass from typing import Optional, Union import torch from .utils.import_utils import is_torchdynamo_compiling, is_tracing @dataclass class AttentionMaskConverter: """ A utility attention mask class that allows one to: - Create a causal 4d mask - Create a causal 4d mask with slided window - Convert a 2d attention mask (batch_size, query_length) to a 4d attention mask (batch_size, 1, query_length, key_value_length) that can be multiplied with attention scores Examples: ```python >>> import torch >>> from transformers.modeling_attn_mask_utils import AttentionMaskConverter >>> converter = AttentionMaskConverter(True) >>> converter.to_4d(torch.tensor([[0, 0, 0, 1, 1]]), 5, key_value_length=5, dtype=torch.float32) tensor([[[[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38], [-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38], [-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38], [-3.4028e+38, -3.4028e+38, -3.4028e+38, 0.0000e+00, -3.4028e+38], [-3.4028e+38, -3.4028e+38, -3.4028e+38, 0.0000e+00, 0.0000e+00]]]]) ``` Parameters: is_causal (`bool`): Whether the attention mask should be a uni-directional (causal) or bi-directional mask. sliding_window (`int`, *optional*): Optionally, the sliding window masks can be created if `sliding_window` is defined to a positive integer. """ is_causal: bool sliding_window: int def __init__(self, is_causal: bool, sliding_window: Optional[int] = None): self.is_causal = is_causal self.sliding_window = sliding_window if self.sliding_window is not None and self.sliding_window <= 0: raise ValueError( f"Make sure that when passing `sliding_window` that its value is a strictly positive integer, not `{self.sliding_window}`" ) def to_causal_4d( self, batch_size: int, query_length: int, key_value_length: int, dtype: torch.dtype, device: Union[torch.device, "str"] = "cpu", ) -> Optional[torch.Tensor]: """ Creates a causal 4D mask of (bsz, head_dim=1, query_length, key_value_length) shape and adds large negative bias to upper right hand triangular matrix (causal mask). """ if not self.is_causal: raise ValueError(f"Please use `to_causal_4d` only if {self.__class__} has `is_causal` set to True.") # If shape is not cached, create a new causal mask and cache it input_shape = (batch_size, query_length) past_key_values_length = key_value_length - query_length # create causal mask # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] causal_4d_mask = None if input_shape[-1] > 1 or self.sliding_window is not None: causal_4d_mask = self._make_causal_mask( input_shape, dtype, device=device, past_key_values_length=past_key_values_length, sliding_window=self.sliding_window, ) return causal_4d_mask def to_4d( self, attention_mask_2d: torch.Tensor, query_length: int, dtype: torch.dtype, key_value_length: Optional[int] = None, ) -> torch.Tensor: """ Converts 2D attention mask to 4D attention mask by expanding mask to (bsz, head_dim=1, query_length, key_value_length) shape and by adding a large negative bias to not-attended positions. If attention_mask is causal, a causal mask will be added. """ input_shape = (attention_mask_2d.shape[0], query_length) # create causal mask # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] causal_4d_mask = None if (input_shape[-1] > 1 or self.sliding_window is not None) and self.is_causal: if key_value_length is None: raise ValueError( "This attention mask converter is causal. Make sure to pass `key_value_length` to correctly create a causal mask." ) past_key_values_length = key_value_length - query_length causal_4d_mask = self._make_causal_mask( input_shape, dtype, device=attention_mask_2d.device, past_key_values_length=past_key_values_length, sliding_window=self.sliding_window, ) elif self.sliding_window is not None: raise NotImplementedError("Sliding window is currently only implemented for causal masking") # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] expanded_attn_mask = self._expand_mask(attention_mask_2d, dtype, tgt_len=input_shape[-1]).to( attention_mask_2d.device ) if causal_4d_mask is not None: expanded_attn_mask = causal_4d_mask.masked_fill(expanded_attn_mask.bool(), torch.finfo(dtype).min) # expanded_attn_mask + causal_4d_mask can cause some overflow expanded_4d_mask = expanded_attn_mask return expanded_4d_mask @staticmethod def _make_causal_mask( input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0, sliding_window: Optional[int] = None, ): """ Make causal mask used for bi-directional self-attention. """ bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device) mask_cond = torch.arange(mask.size(-1), device=device) mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) mask = mask.to(dtype) if past_key_values_length > 0: mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1) # add lower triangular sliding window mask if necessary if sliding_window is not None: diagonal = past_key_values_length - sliding_window - 1 context_mask = torch.tril(torch.ones_like(mask, dtype=torch.bool), diagonal=diagonal) # Recent changes in PyTorch prevent mutations on tensors converted with aten::_to_copy # See https://github.com/pytorch/pytorch/issues/127571 if is_torchdynamo_compiling(): mask = mask.clone() mask.masked_fill_(context_mask, torch.finfo(dtype).min) return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) @staticmethod def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. """ bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = torch.tensor(1.0, dtype=dtype) - expanded_mask return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) @staticmethod def _unmask_unattended( expanded_mask: torch.FloatTensor, min_dtype: float, ): # fmt: off """ Attend to all tokens in masked rows from the expanded attention mask, for example the relevant first rows when using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path. Details: https://github.com/pytorch/pytorch/issues/110213 `expanded_mask` is [bsz, num_masks, tgt_seq_len, src_seq_len] or [bsz, tgt_seq_len, src_seq_len]. `attention_mask` is [bsz, src_seq_len]. The dimension num_masks of `expanded_mask` is most often 1, but it can also be the number of heads in the case of alibi attention bias. For example, if `expanded_mask` is (e.g. here left-padding case) ``` [[[[0, 0, 0], [0, 0, 0], [0, 0, 1]]], [[[1, 0, 0], [1, 1, 0], [1, 1, 1]]], [[[0, 0, 0], [0, 1, 0], [0, 1, 1]]]] ``` then the modified `expanded_mask` will be ``` [[[[1, 1, 1], <-- modified [1, 1, 1], <-- modified [0, 0, 1]]], [[[1, 0, 0], [1, 1, 0], [1, 1, 1]]], [[[1, 1, 1], <-- modified [0, 1, 0], [0, 1, 1]]]] ``` """ # fmt: on if expanded_mask.dtype == torch.bool: raise ValueError( "AttentionMaskConverter._unmask_unattended expects a float `expanded_mask`, got a BoolTensor." ) return expanded_mask.mul(~torch.all(expanded_mask == min_dtype, dim=-1, keepdim=True)) @staticmethod def _ignore_causal_mask_sdpa( attention_mask: Optional[torch.Tensor], inputs_embeds: torch.Tensor, past_key_values_length: int, sliding_window: Optional[int] = None, is_training: bool = False, ) -> bool: """ Detects whether the optional user-specified attention_mask & the automatically created causal mask can be ignored in case PyTorch's SDPA is used, rather relying on SDPA's `is_causal` argument. In case no token is masked in the `attention_mask` argument, if `query_length == 1` or `key_value_length == query_length`, we rather rely on SDPA `is_causal` argument to use causal/non-causal masks, allowing to dispatch to the flash attention kernel (that can otherwise not be used if a custom `attn_mask` is passed). """ _, query_length = inputs_embeds.shape[0], inputs_embeds.shape[1] key_value_length = query_length + past_key_values_length is_tracing_ = is_tracing(inputs_embeds) ignore_causal_mask = False if attention_mask is None: # TODO: When tracing with TorchDynamo with fullgraph=True, the model is recompiled depending on the input # shape, thus SDPA's `is_causal` argument is rightfully updated # (see https://gist.github.com/fxmarty/1313f39037fc1c112508989628c57363). However, when using # `torch.export` or `torch.onnx.dynamo_export`, we must pass an example input, and `is_causal` behavior is # hard-coded. If a user exports a model with q_len > 1, the exported model will hard-code `is_causal=True` # which is in general wrong (see https://github.com/pytorch/pytorch/issues/108108). # Thus, we only set `ignore_causal_mask = True` if the model is set to training. # # Besides, jit.trace can not handle the `q_len > 1` condition for `is_causal` # ("TypeError: scaled_dot_product_attention(): argument 'is_causal' must be bool, not Tensor"). if ( (is_training or not is_tracing_) and (query_length == 1 or key_value_length == query_length) and (sliding_window is None or key_value_length < sliding_window) ): ignore_causal_mask = True elif sliding_window is None or key_value_length < sliding_window: if len(attention_mask.shape) == 4: return False elif not is_tracing_ and torch.all(attention_mask == 1): if query_length == 1 or key_value_length == query_length: # For query_length == 1, causal attention and bi-directional attention are the same. ignore_causal_mask = True # Unfortunately, for query_length > 1 and key_value_length != query_length, we cannot generally ignore # the attention mask, as SDPA causal mask generation may be wrong. We will set `is_causal=False` in # SDPA and rely on Transformers attention_mask instead, hence not setting it to None here. # Reference: https://github.com/pytorch/pytorch/issues/108108 # TODO: maybe revisit this with https://github.com/pytorch/pytorch/pull/114823 in PyTorch 2.3. return ignore_causal_mask def _prepare_4d_causal_attention_mask( attention_mask: Optional[torch.Tensor], input_shape: Union[torch.Size, tuple, list], inputs_embeds: torch.Tensor, past_key_values_length: int, sliding_window: Optional[int] = None, ): """ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape `(batch_size, key_value_length)` Args: attention_mask (`torch.Tensor` or `None`): A 2D attention mask of shape `(batch_size, key_value_length)` input_shape (`tuple(int)` or `list(int)` or `torch.Size`): The input shape should be a tuple that defines `(batch_size, query_length)`. inputs_embeds (`torch.Tensor`): The embedded inputs as a torch Tensor. past_key_values_length (`int`): The length of the key value cache. sliding_window (`int`, *optional*): If the model uses windowed attention, a sliding window should be passed. """ attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window) key_value_length = input_shape[-1] + past_key_values_length # 4d mask is passed through the layers if attention_mask is not None and len(attention_mask.shape) == 2: attention_mask = attn_mask_converter.to_4d( attention_mask, input_shape[-1], key_value_length=key_value_length, dtype=inputs_embeds.dtype ) elif attention_mask is not None and len(attention_mask.shape) == 4: expected_shape = (input_shape[0], 1, input_shape[1], key_value_length) if tuple(attention_mask.shape) != expected_shape: raise ValueError( f"Incorrect 4D attention_mask shape: {tuple(attention_mask.shape)}; expected: {expected_shape}." ) else: # if the 4D mask has correct shape - invert it and fill with negative infinity inverted_mask = 1.0 - attention_mask attention_mask = inverted_mask.masked_fill( inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min ) else: attention_mask = attn_mask_converter.to_causal_4d( input_shape[0], input_shape[-1], key_value_length, dtype=inputs_embeds.dtype, device=inputs_embeds.device ) return attention_mask # Adapted from _prepare_4d_causal_attention_mask def _prepare_4d_causal_attention_mask_for_sdpa( attention_mask: Optional[torch.Tensor], input_shape: Union[torch.Size, tuple, list], inputs_embeds: torch.Tensor, past_key_values_length: int, sliding_window: Optional[int] = None, ): """ Prepares the correct `attn_mask` argument to be used by `torch.nn.functional.scaled_dot_product_attention`. In case no token is masked in the `attention_mask` argument, we simply set it to `None` for the cases `query_length == 1` and `key_value_length == query_length`, and rely instead on SDPA `is_causal` argument to use causal/non-causal masks, allowing to dispatch to the flash attention kernel (that can otherwise not be used if a custom `attn_mask` is passed). """ attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window) key_value_length = input_shape[-1] + past_key_values_length # torch.jit.trace, symbolic_trace and torchdynamo with fullgraph=True are unable to capture the controlflow `is_causal=attention_mask is None and q_len > 1` # used as an SDPA argument. We keep compatibility with these tracing tools by always using SDPA's `attn_mask` argument in case we are tracing. # TODO: For dynamo, rather use a check on fullgraph=True once this is possible (https://github.com/pytorch/pytorch/pull/120400). is_tracing_ = is_tracing(inputs_embeds) ignore_causal_mask = AttentionMaskConverter._ignore_causal_mask_sdpa( attention_mask=attention_mask, inputs_embeds=inputs_embeds, past_key_values_length=past_key_values_length, sliding_window=sliding_window, ) if ignore_causal_mask: expanded_4d_mask = None elif attention_mask is None: expanded_4d_mask = attn_mask_converter.to_causal_4d( input_shape[0], input_shape[-1], key_value_length, dtype=inputs_embeds.dtype, device=inputs_embeds.device ) else: if attention_mask.dim() == 4: expanded_4d_mask = attention_mask else: expanded_4d_mask = attn_mask_converter.to_4d( attention_mask, input_shape[-1], dtype=inputs_embeds.dtype, key_value_length=key_value_length, ) # Attend to all tokens in masked rows from the causal_mask, for example the relevant first rows when # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path. # Details: https://github.com/pytorch/pytorch/issues/110213 if not is_tracing_ and expanded_4d_mask.device.type in ["cuda", "xpu"]: expanded_4d_mask = AttentionMaskConverter._unmask_unattended( expanded_4d_mask, min_dtype=torch.finfo(inputs_embeds.dtype).min ) return expanded_4d_mask def _prepare_4d_attention_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """ Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape `(batch_size, key_value_length)` Args: mask (`torch.Tensor`): A 2D attention mask of shape `(batch_size, key_value_length)` dtype (`torch.dtype`): The torch dtype the created mask shall have. tgt_len (`int`): The target length or query length the created mask shall have. """ return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len) def _prepare_4d_attention_mask_for_sdpa(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """ Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape `(batch_size, key_value_length)` Args: mask (`torch.Tensor`): A 2D attention mask of shape `(batch_size, key_value_length)` dtype (`torch.dtype`): The torch dtype the created mask shall have. tgt_len (`int`): The target length or query length the created mask shall have. """ _, key_value_length = mask.shape tgt_len = tgt_len if tgt_len is not None else key_value_length # torch.jit.trace, symbolic_trace and torchdynamo with fullgraph=True are unable to capture data-dependent controlflows. if not is_tracing(mask) and torch.all(mask == 1): return None else: return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len) def _create_4d_causal_attention_mask( input_shape: Union[torch.Size, tuple, list], dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0, sliding_window: Optional[int] = None, ) -> Optional[torch.Tensor]: """ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` Args: input_shape (`tuple(int)` or `list(int)` or `torch.Size`): The input shape should be a tuple that defines `(batch_size, query_length)`. dtype (`torch.dtype`): The torch dtype the created mask shall have. device (`int`): The torch device the created mask shall have. sliding_window (`int`, *optional*): If the model uses windowed attention, a sliding window should be passed. """ attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window) key_value_length = past_key_values_length + input_shape[-1] attention_mask = attn_mask_converter.to_causal_4d( input_shape[0], input_shape[-1], key_value_length, dtype=dtype, device=device ) return attention_mask
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/hyperparameter_search.py
src/transformers/hyperparameter_search.py
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional from .integrations import ( is_optuna_available, is_ray_tune_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_wandb, ) from .utils import logging logger = logging.get_logger(__name__) class HyperParamSearchBackendBase: name: str pip_package: Optional[str] = None @staticmethod def is_available(): raise NotImplementedError def run(self, trainer, n_trials: int, direction: str, **kwargs): raise NotImplementedError def default_hp_space(self, trial): raise NotImplementedError def ensure_available(self): if not self.is_available(): raise RuntimeError( f"You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}." ) @classmethod def pip_install(cls): return f"`pip install {cls.pip_package or cls.name}`" class OptunaBackend(HyperParamSearchBackendBase): name = "optuna" @staticmethod def is_available(): return is_optuna_available() def run(self, trainer, n_trials: int, direction: str, **kwargs): return run_hp_search_optuna(trainer, n_trials, direction, **kwargs) def default_hp_space(self, trial): return default_hp_space_optuna(trial) class RayTuneBackend(HyperParamSearchBackendBase): name = "ray" pip_package = "'ray[tune]'" @staticmethod def is_available(): return is_ray_tune_available() def run(self, trainer, n_trials: int, direction: str, **kwargs): return run_hp_search_ray(trainer, n_trials, direction, **kwargs) def default_hp_space(self, trial): return default_hp_space_ray(trial) class WandbBackend(HyperParamSearchBackendBase): name = "wandb" @staticmethod def is_available(): return is_wandb_available() def run(self, trainer, n_trials: int, direction: str, **kwargs): return run_hp_search_wandb(trainer, n_trials, direction, **kwargs) def default_hp_space(self, trial): return default_hp_space_wandb(trial) ALL_HYPERPARAMETER_SEARCH_BACKENDS = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, WandbBackend] } def default_hp_search_backend() -> str: available_backends = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(available_backends) > 0: name = available_backends[0].name if len(available_backends) > 1: logger.info( f"{len(available_backends)} hyperparameter search backends available. Using {name} as the default." ) return name raise RuntimeError( "No hyperparameter search backend available.\n" + "\n".join( f" - To install {backend.name} run {backend.pip_install()}" for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/feature_extraction_utils.py
src/transformers/feature_extraction_utils.py
# Copyright 2021 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Feature extraction saving/loading class for common feature extractors. """ import copy import json import os from collections import UserDict from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union import numpy as np from huggingface_hub import create_repo, is_offline_mode from .dynamic_module_utils import custom_object_save from .utils import ( FEATURE_EXTRACTOR_NAME, PROCESSOR_NAME, PushToHubMixin, TensorType, _is_tensor_or_array_like, copy_func, is_numpy_array, is_torch_available, is_torch_device, is_torch_dtype, logging, requires_backends, safe_load_json_file, ) from .utils.hub import cached_file if TYPE_CHECKING: from .feature_extraction_sequence_utils import SequenceFeatureExtractor logger = logging.get_logger(__name__) PreTrainedFeatureExtractor = Union["SequenceFeatureExtractor"] # type hinting: specifying the type of feature extractor class that inherits from FeatureExtractionMixin SpecificFeatureExtractorType = TypeVar("SpecificFeatureExtractorType", bound="FeatureExtractionMixin") class BatchFeature(UserDict): r""" Holds the output of the [`~SequenceFeatureExtractor.pad`] and feature extractor specific `__call__` methods. This class is derived from a python dictionary and can be used as a dictionary. Args: data (`dict`, *optional*): Dictionary of lists/arrays/tensors returned by the __call__/pad methods ('input_values', 'attention_mask', etc.). tensor_type (`Union[None, str, TensorType]`, *optional*): You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization. skip_tensor_conversion (`list[str]` or `set[str]`, *optional*): List or set of keys that should NOT be converted to tensors, even when `tensor_type` is specified. """ def __init__( self, data: Optional[dict[str, Any]] = None, tensor_type: Union[None, str, TensorType] = None, skip_tensor_conversion: Optional[Union[list[str], set[str]]] = None, ): super().__init__(data) self.convert_to_tensors(tensor_type=tensor_type, skip_tensor_conversion=skip_tensor_conversion) def __getitem__(self, item: str) -> Any: """ If the key is a string, returns the value of the dict associated to `key` ('input_values', 'attention_mask', etc.). """ if isinstance(item, str): return self.data[item] else: raise KeyError("Indexing with integers is not available when using Python based feature extractors") def __getattr__(self, item: str): try: return self.data[item] except KeyError: raise AttributeError def __getstate__(self): return {"data": self.data} def __setstate__(self, state): if "data" in state: self.data = state["data"] def _get_is_as_tensor_fns(self, tensor_type: Optional[Union[str, TensorType]] = None): if tensor_type is None: return None, None # Convert to TensorType if not isinstance(tensor_type, TensorType): tensor_type = TensorType(tensor_type) if tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed.") import torch def as_tensor(value): if torch.is_tensor(value): return value # stack list of tensors if tensor_type is PyTorch (# torch.tensor() does not support list of tensors) if isinstance(value, (list, tuple)) and len(value) > 0 and torch.is_tensor(value[0]): return torch.stack(value) # convert list of numpy arrays to numpy array (stack) if tensor_type is Numpy if isinstance(value, (list, tuple)) and len(value) > 0: if isinstance(value[0], np.ndarray): value = np.array(value) elif ( isinstance(value[0], (list, tuple)) and len(value[0]) > 0 and isinstance(value[0][0], np.ndarray) ): value = np.array(value) if isinstance(value, np.ndarray): return torch.from_numpy(value) else: return torch.tensor(value) is_tensor = torch.is_tensor else: def as_tensor(value, dtype=None): if isinstance(value, (list, tuple)) and isinstance(value[0], (list, tuple, np.ndarray)): value_lens = [len(val) for val in value] if len(set(value_lens)) > 1 and dtype is None: # we have a ragged list so handle explicitly value = as_tensor([np.asarray(val) for val in value], dtype=object) return np.asarray(value, dtype=dtype) is_tensor = is_numpy_array return is_tensor, as_tensor def convert_to_tensors( self, tensor_type: Optional[Union[str, TensorType]] = None, skip_tensor_conversion: Optional[Union[list[str], set[str]]] = None, ): """ Convert the inner content to tensors. Args: tensor_type (`str` or [`~utils.TensorType`], *optional*): The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If `None`, no modification is done. skip_tensor_conversion (`list[str]` or `set[str]`, *optional*): List or set of keys that should NOT be converted to tensors, even when `tensor_type` is specified. Note: Values that don't have an array-like structure (e.g., strings, dicts, lists of strings) are automatically skipped and won't be converted to tensors. Ragged arrays (lists of arrays with different lengths) are still attempted, though they may raise errors during conversion. """ if tensor_type is None: return self is_tensor, as_tensor = self._get_is_as_tensor_fns(tensor_type) # Do the tensor conversion in batch for key, value in self.items(): # Skip keys explicitly marked for no conversion if skip_tensor_conversion and key in skip_tensor_conversion: continue # Skip values that are not array-like if not _is_tensor_or_array_like(value): continue try: if not is_tensor(value): tensor = as_tensor(value) self[key] = tensor except Exception as e: if key == "overflowing_values": raise ValueError( f"Unable to create tensor for '{key}' with overflowing values of different lengths. " f"Original error: {str(e)}" ) from e raise ValueError( f"Unable to convert output '{key}' (type: {type(value).__name__}) to tensor: {str(e)}\n" f"You can try:\n" f" 1. Use padding=True to ensure all outputs have the same shape\n" f" 2. Set return_tensors=None to return Python objects instead of tensors" ) from e return self def to(self, *args, **kwargs) -> "BatchFeature": """ Send all values to device by calling `v.to(*args, **kwargs)` (PyTorch only). This should support casting in different `dtypes` and sending the `BatchFeature` to a different `device`. Args: args (`Tuple`): Will be passed to the `to(...)` function of the tensors. kwargs (`Dict`, *optional*): Will be passed to the `to(...)` function of the tensors. To enable asynchronous data transfer, set the `non_blocking` flag in `kwargs` (defaults to `False`). Returns: [`BatchFeature`]: The same instance after modification. """ requires_backends(self, ["torch"]) import torch device = kwargs.get("device") non_blocking = kwargs.get("non_blocking", False) # Check if the args are a device or a dtype if device is None and len(args) > 0: # device should be always the first argument arg = args[0] if is_torch_dtype(arg): # The first argument is a dtype pass elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int): device = arg else: # it's something else raise ValueError(f"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.") # We cast only floating point tensors to avoid issues with tokenizers casting `LongTensor` to `FloatTensor` def maybe_to(v): # check if v is a floating point tensor if isinstance(v, torch.Tensor) and torch.is_floating_point(v): # cast and send to device return v.to(*args, **kwargs) elif isinstance(v, torch.Tensor) and device is not None: return v.to(device=device, non_blocking=non_blocking) # recursively handle lists and tuples elif isinstance(v, (list, tuple)): return type(v)(maybe_to(item) for item in v) else: return v self.data = {k: maybe_to(v) for k, v in self.items()} return self class FeatureExtractionMixin(PushToHubMixin): """ This is a feature extraction mixin used to provide saving/loading functionality for sequential and audio feature extractors. """ _auto_class = None def __init__(self, **kwargs): """Set elements of `kwargs` as attributes.""" # Pop "processor_class", it should not be saved in feature extractor config kwargs.pop("processor_class", None) # Additional attributes without default values for key, value in kwargs.items(): try: setattr(self, key, value) except AttributeError as err: logger.error(f"Can't set {key} with value {value} for {self}") raise err @classmethod def from_pretrained( cls: type[SpecificFeatureExtractorType], pretrained_model_name_or_path: Union[str, os.PathLike], cache_dir: Optional[Union[str, os.PathLike]] = None, force_download: bool = False, local_files_only: bool = False, token: Optional[Union[str, bool]] = None, revision: str = "main", **kwargs, ) -> SpecificFeatureExtractorType: r""" Instantiate a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a feature extractor, *e.g.* a derived class of [`SequenceFeatureExtractor`]. Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on huggingface.co. - a path to a *directory* containing a feature extractor file saved using the [`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] method, e.g., `./my_model_directory/`. - a path or url to a saved feature extractor JSON *file*, e.g., `./my_model_directory/preprocessor_config.json`. cache_dir (`str` or `os.PathLike`, *optional*): Path to a directory in which a downloaded pretrained model feature extractor should be cached if the standard cache should not be used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force to (re-)download the feature extractor files and override the cached versions if they exist. proxies (`dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. token (`str` or `bool`, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use the token generated when running `hf auth login` (stored in `~/.huggingface`). revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. <Tip> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`. </Tip> return_unused_kwargs (`bool`, *optional*, defaults to `False`): If `False`, then this function returns just the final feature extractor object. If `True`, then this functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of `kwargs` which has not been used to update `feature_extractor` and is otherwise ignored. kwargs (`dict[str, Any]`, *optional*): The values in kwargs of any keys which are feature extractor attributes will be used to override the loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is controlled by the `return_unused_kwargs` keyword parameter. Returns: A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`]. Examples: ```python # We can't instantiate directly the base class *FeatureExtractionMixin* nor *SequenceFeatureExtractor* so let's show the examples on a # derived class: *Wav2Vec2FeatureExtractor* feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( "facebook/wav2vec2-base-960h" ) # Download feature_extraction_config from huggingface.co and cache. feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( "./test/saved_model/" ) # E.g. feature_extractor (or model) was saved using *save_pretrained('./test/saved_model/')* feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("./test/saved_model/preprocessor_config.json") feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( "facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False ) assert feature_extractor.return_attention_mask is False feature_extractor, unused_kwargs = Wav2Vec2FeatureExtractor.from_pretrained( "facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False, return_unused_kwargs=True ) assert feature_extractor.return_attention_mask is False assert unused_kwargs == {"foo": False} ```""" kwargs["cache_dir"] = cache_dir kwargs["force_download"] = force_download kwargs["local_files_only"] = local_files_only kwargs["revision"] = revision if token is not None: kwargs["token"] = token feature_extractor_dict, kwargs = cls.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs) return cls.from_dict(feature_extractor_dict, **kwargs) def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs): """ Save a feature_extractor object to the directory `save_directory`, so that it can be re-loaded using the [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`] class method. Args: save_directory (`str` or `os.PathLike`): Directory where the feature extractor JSON file will be saved (will be created if it does not exist). push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace). kwargs (`dict[str, Any]`, *optional*): Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method. """ if os.path.isfile(save_directory): raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file") os.makedirs(save_directory, exist_ok=True) if push_to_hub: commit_message = kwargs.pop("commit_message", None) repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1]) repo_id = create_repo(repo_id, exist_ok=True, **kwargs).repo_id files_timestamps = self._get_files_timestamps(save_directory) # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be # loaded from the Hub. if self._auto_class is not None: custom_object_save(self, save_directory, config=self) # If we save using the predefined names, we can load using `from_pretrained` output_feature_extractor_file = os.path.join(save_directory, FEATURE_EXTRACTOR_NAME) self.to_json_file(output_feature_extractor_file) logger.info(f"Feature extractor saved in {output_feature_extractor_file}") if push_to_hub: self._upload_modified_files( save_directory, repo_id, files_timestamps, commit_message=commit_message, token=kwargs.get("token"), ) return [output_feature_extractor_file] @classmethod def get_feature_extractor_dict( cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs ) -> tuple[dict[str, Any], dict[str, Any]]: """ From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`] using `from_dict`. Parameters: pretrained_model_name_or_path (`str` or `os.PathLike`): The identifier of the pre-trained checkpoint from which we want the dictionary of parameters. Returns: `tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the feature extractor object. """ cache_dir = kwargs.pop("cache_dir", None) force_download = kwargs.pop("force_download", False) proxies = kwargs.pop("proxies", None) subfolder = kwargs.pop("subfolder", None) token = kwargs.pop("token", None) local_files_only = kwargs.pop("local_files_only", False) revision = kwargs.pop("revision", None) from_pipeline = kwargs.pop("_from_pipeline", None) from_auto_class = kwargs.pop("_from_auto", False) user_agent = {"file_type": "feature extractor", "from_auto_class": from_auto_class} if from_pipeline is not None: user_agent["using_pipeline"] = from_pipeline if is_offline_mode() and not local_files_only: logger.info("Offline mode: forcing local_files_only=True") local_files_only = True pretrained_model_name_or_path = str(pretrained_model_name_or_path) is_local = os.path.isdir(pretrained_model_name_or_path) if os.path.isdir(pretrained_model_name_or_path): feature_extractor_file = os.path.join(pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME) if os.path.isfile(pretrained_model_name_or_path): resolved_feature_extractor_file = pretrained_model_name_or_path resolved_processor_file = None is_local = True else: feature_extractor_file = FEATURE_EXTRACTOR_NAME try: # Load from local folder or from cache or download from model Hub and cache resolved_processor_file = cached_file( pretrained_model_name_or_path, filename=PROCESSOR_NAME, cache_dir=cache_dir, force_download=force_download, proxies=proxies, local_files_only=local_files_only, token=token, user_agent=user_agent, revision=revision, subfolder=subfolder, _raise_exceptions_for_missing_entries=False, ) resolved_feature_extractor_file = cached_file( pretrained_model_name_or_path, filename=feature_extractor_file, cache_dir=cache_dir, force_download=force_download, proxies=proxies, local_files_only=local_files_only, token=token, user_agent=user_agent, revision=revision, subfolder=subfolder, _raise_exceptions_for_missing_entries=False, ) except OSError: # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to # the original exception. raise except Exception: # For any other exception, we throw a generic error. raise OSError( f"Can't load feature extractor for '{pretrained_model_name_or_path}'. If you were trying to load" " it from 'https://huggingface.co/models', make sure you don't have a local directory with the" f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a" f" directory containing a {FEATURE_EXTRACTOR_NAME} file" ) # Load feature_extractor dict. Priority goes as (nested config if found -> image processor config) # We are downloading both configs because almost all models have a `processor_config.json` but # not all of these are nested. We need to check if it was saved recebtly as nested or if it is legacy style feature_extractor_dict = None if resolved_processor_file is not None: processor_dict = safe_load_json_file(resolved_processor_file) if "feature_extractor" in processor_dict or "audio_processor" in processor_dict: feature_extractor_dict = processor_dict.get("feature_extractor", processor_dict.get("audio_processor")) if resolved_feature_extractor_file is not None and feature_extractor_dict is None: feature_extractor_dict = safe_load_json_file(resolved_feature_extractor_file) if feature_extractor_dict is None: raise OSError( f"Can't load feature extractor for '{pretrained_model_name_or_path}'. If you were trying to load" " it from 'https://huggingface.co/models', make sure you don't have a local directory with the" f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a" f" directory containing a {feature_extractor_file} file" ) if is_local: logger.info(f"loading configuration file {resolved_feature_extractor_file}") else: logger.info( f"loading configuration file {feature_extractor_file} from cache at {resolved_feature_extractor_file}" ) return feature_extractor_dict, kwargs @classmethod def from_dict( cls, feature_extractor_dict: dict[str, Any], **kwargs ) -> Union["FeatureExtractionMixin", tuple["FeatureExtractionMixin", dict[str, Any]]]: """ Instantiates a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a Python dictionary of parameters. Args: feature_extractor_dict (`dict[str, Any]`): Dictionary that will be used to instantiate the feature extractor object. Such a dictionary can be retrieved from a pretrained checkpoint by leveraging the [`~feature_extraction_utils.FeatureExtractionMixin.to_dict`] method. kwargs (`dict[str, Any]`): Additional parameters from which to initialize the feature extractor object. Returns: [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature extractor object instantiated from those parameters. """ return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) # Update feature_extractor with kwargs if needed to_remove = [] for key, value in kwargs.items(): if key in feature_extractor_dict: feature_extractor_dict[key] = value to_remove.append(key) for key in to_remove: kwargs.pop(key, None) feature_extractor = cls(**feature_extractor_dict) logger.info(f"Feature extractor {feature_extractor}") if return_unused_kwargs: return feature_extractor, kwargs else: return feature_extractor def to_dict(self) -> dict[str, Any]: """ Serializes this instance to a Python dictionary. Returns: `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance. """ output = copy.deepcopy(self.__dict__) output["feature_extractor_type"] = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "window" in output: del output["window"] return output @classmethod def from_json_file(cls, json_file: Union[str, os.PathLike]) -> "FeatureExtractionMixin": """ Instantiates a feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`] from the path to a JSON file of parameters. Args: json_file (`str` or `os.PathLike`): Path to the JSON file containing the parameters. Returns: A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature_extractor object instantiated from that JSON file. """ with open(json_file, encoding="utf-8") as reader: text = reader.read() feature_extractor_dict = json.loads(text) return cls(**feature_extractor_dict) def to_json_string(self) -> str: """ Serializes this instance to a JSON string. Returns: `str`: String containing all the attributes that make up this feature_extractor instance in JSON format. """ dictionary = self.to_dict() for key, value in dictionary.items(): if isinstance(value, np.ndarray): dictionary[key] = value.tolist() return json.dumps(dictionary, indent=2, sort_keys=True) + "\n" def to_json_file(self, json_file_path: Union[str, os.PathLike]): """ Save this instance to a JSON file. Args: json_file_path (`str` or `os.PathLike`): Path to the JSON file in which this feature_extractor instance's parameters will be saved. """ with open(json_file_path, "w", encoding="utf-8") as writer: writer.write(self.to_json_string()) def __repr__(self): return f"{self.__class__.__name__} {self.to_json_string()}" @classmethod def register_for_auto_class(cls, auto_class="AutoFeatureExtractor"): """ Register this class with a given auto class. This should only be used for custom feature extractors as the ones in the library are already mapped with `AutoFeatureExtractor`. Args: auto_class (`str` or `type`, *optional*, defaults to `"AutoFeatureExtractor"`): The auto class to register this new feature extractor with. """ if not isinstance(auto_class, str): auto_class = auto_class.__name__ import transformers.models.auto as auto_module if not hasattr(auto_module, auto_class): raise ValueError(f"{auto_class} is not a valid auto class.") cls._auto_class = auto_class FeatureExtractionMixin.push_to_hub = copy_func(FeatureExtractionMixin.push_to_hub) if FeatureExtractionMixin.push_to_hub.__doc__ is not None: FeatureExtractionMixin.push_to_hub.__doc__ = FeatureExtractionMixin.push_to_hub.__doc__.format( object="feature extractor", object_class="AutoFeatureExtractor", object_files="feature extractor file" )
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/dynamic_module_utils.py
src/transformers/dynamic_module_utils.py
# Copyright 2021 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities to dynamically load objects from the Hub.""" import ast import filecmp import hashlib import importlib import importlib.metadata import importlib.util import keyword import os import re import shutil import signal import sys import threading from pathlib import Path from types import ModuleType from typing import Any, Optional, Union from huggingface_hub import is_offline_mode, try_to_load_from_cache from packaging import version from .utils import ( HF_MODULES_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, cached_file, extract_commit_hash, logging, ) from .utils.import_utils import VersionComparison, split_package_version logger = logging.get_logger(__name__) # pylint: disable=invalid-name def _sanitize_module_name(name: str) -> str: r""" Tries to sanitize a module name so that it can be used as a Python module. The following transformations are applied: 1. Replace `.` in module names with `_dot_`. 2. Replace `-` in module names with `_hyphen_`. 3. If the module name starts with a digit, prepend it with `_`. 4. Warn if the sanitized name is a Python reserved keyword or not a valid identifier. If the input name is already a valid identifier, it is returned unchanged. """ # We not replacing `\W` characters with `_` to avoid collisions. Because `_` is a very common # separator used in module names, replacing `\W` with `_` would create too many collisions. # Once a module is imported, it is cached in `sys.modules` and the second import would return # the first module, which might not be the expected behavior if name collisions happen. new_name = name.replace(".", "_dot_").replace("-", "_hyphen_") if new_name and new_name[0].isdigit(): new_name = f"_{new_name}" if keyword.iskeyword(new_name): logger.warning( f"The module name {new_name} (originally {name}) is a reserved keyword in Python. " "Please rename the original module to avoid import issues." ) elif not new_name.isidentifier(): logger.warning( f"The module name {new_name} (originally {name}) is not a valid Python identifier. " "Please rename the original module to avoid import issues." ) return new_name _HF_REMOTE_CODE_LOCK = threading.Lock() def init_hf_modules(): """ Creates the cache directory for modules with an init, and adds it to the Python path. """ # This function has already been executed if HF_MODULES_CACHE already is in the Python path. if HF_MODULES_CACHE in sys.path: return sys.path.append(HF_MODULES_CACHE) os.makedirs(HF_MODULES_CACHE, exist_ok=True) init_path = Path(HF_MODULES_CACHE) / "__init__.py" if not init_path.exists(): init_path.touch() importlib.invalidate_caches() def create_dynamic_module(name: Union[str, os.PathLike]) -> None: """ Creates a dynamic module in the cache directory for modules. Args: name (`str` or `os.PathLike`): The name of the dynamic module to create. """ init_hf_modules() dynamic_module_path = (Path(HF_MODULES_CACHE) / name).resolve() # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent) os.makedirs(dynamic_module_path, exist_ok=True) init_path = dynamic_module_path / "__init__.py" if not init_path.exists(): init_path.touch() # It is extremely important to invalidate the cache when we change stuff in those modules, or users end up # with errors about module that do not exist. Same for all other `invalidate_caches` in this file. importlib.invalidate_caches() def get_relative_imports(module_file: Union[str, os.PathLike]) -> list[str]: """ Get the list of modules that are relatively imported in a module file. Args: module_file (`str` or `os.PathLike`): The module file to inspect. Returns: `list[str]`: The list of relative imports in the module. """ with open(module_file, encoding="utf-8") as f: content = f.read() # Imports of the form `import .xxx` relative_imports = re.findall(r"^\s*import\s+\.(\S+)\s*$", content, flags=re.MULTILINE) # Imports of the form `from .xxx import yyy` relative_imports += re.findall(r"^\s*from\s+\.(\S+)\s+import", content, flags=re.MULTILINE) # Unique-ify return list(set(relative_imports)) def get_relative_import_files(module_file: Union[str, os.PathLike]) -> list[str]: """ Get the list of all files that are needed for a given module. Note that this function recurses through the relative imports (if a imports b and b imports c, it will return module files for b and c). Args: module_file (`str` or `os.PathLike`): The module file to inspect. Returns: `list[str]`: The list of all relative imports a given module needs (recursively), which will give us the list of module files a given module needs. """ no_change = False files_to_check = [module_file] all_relative_imports = [] # Let's recurse through all relative imports while not no_change: new_imports = [] for f in files_to_check: new_imports.extend(get_relative_imports(f)) module_path = Path(module_file).parent new_import_files = [f"{str(module_path / m)}.py" for m in new_imports] files_to_check = [f for f in new_import_files if f not in all_relative_imports] no_change = len(files_to_check) == 0 all_relative_imports.extend(files_to_check) return all_relative_imports def get_imports(filename: Union[str, os.PathLike]) -> list[str]: """ Extracts all the libraries (not relative imports this time) that are imported in a file. Args: filename (`str` or `os.PathLike`): The module file to inspect. Returns: `list[str]`: The list of all packages required to use the input module. """ with open(filename, encoding="utf-8") as f: content = f.read() imported_modules = set() import transformers.utils def recursive_look_for_imports(node): if isinstance(node, ast.Try): return # Don't recurse into Try blocks and ignore imports in them elif isinstance(node, ast.If): test = node.test for condition_node in ast.walk(test): if isinstance(condition_node, ast.Call): check_function = getattr(condition_node.func, "id", "") if ( check_function.endswith("available") and check_function.startswith("is_flash_attn") or hasattr(transformers.utils.import_utils, check_function) ): # Don't recurse into "if flash_attn_available()" or any "if library_available" blocks # that appears in `transformers.utils.import_utils` and ignore imports in them return elif isinstance(node, ast.Import): # Handle 'import x' statements for alias in node.names: top_module = alias.name.split(".")[0] if top_module: imported_modules.add(top_module) elif isinstance(node, ast.ImportFrom): # Handle 'from x import y' statements, ignoring relative imports if node.level == 0 and node.module: top_module = node.module.split(".")[0] if top_module: imported_modules.add(top_module) # Recursively visit all children for child in ast.iter_child_nodes(node): recursive_look_for_imports(child) tree = ast.parse(content) recursive_look_for_imports(tree) return sorted(imported_modules) def check_imports(filename: Union[str, os.PathLike]) -> list[str]: """ Check if the current Python environment contains all the libraries that are imported in a file. Will raise if a library is missing. Args: filename (`str` or `os.PathLike`): The module file to check. Returns: `list[str]`: The list of relative imports in the file. """ imports = get_imports(filename) missing_packages = [] for imp in imports: try: importlib.import_module(imp) except ImportError as exception: logger.warning(f"Encountered exception while importing {imp}: {exception}") # Some packages can fail with an ImportError because of a dependency issue. # This check avoids hiding such errors. # See https://github.com/huggingface/transformers/issues/33604 if "No module named" in str(exception): missing_packages.append(imp) else: raise if len(missing_packages) > 0: raise ImportError( "This modeling file requires the following packages that were not found in your environment: " f"{', '.join(missing_packages)}. Run `pip install {' '.join(missing_packages)}`" ) return get_relative_imports(filename) def get_class_in_module( class_name: str, module_path: Union[str, os.PathLike], *, force_reload: bool = False, ) -> type: """ Import a module on the cache directory for modules and extract a class from it. Args: class_name (`str`): The name of the class to import. module_path (`str` or `os.PathLike`): The path to the module to import. force_reload (`bool`, *optional*, defaults to `False`): Whether to reload the dynamic module from file if it already exists in `sys.modules`. Otherwise, the module is only reloaded if the file has changed. Returns: `typing.Type`: The class looked for. """ name = os.path.normpath(module_path) name = name.removesuffix(".py") name = name.replace(os.path.sep, ".") module_file: Path = Path(HF_MODULES_CACHE) / module_path with _HF_REMOTE_CODE_LOCK: if force_reload: sys.modules.pop(name, None) importlib.invalidate_caches() cached_module: Optional[ModuleType] = sys.modules.get(name) module_spec = importlib.util.spec_from_file_location(name, location=module_file) # Hash the module file and all its relative imports to check if we need to reload it module_files: list[Path] = [module_file] + sorted(map(Path, get_relative_import_files(module_file))) module_hash: str = hashlib.sha256(b"".join(bytes(f) + f.read_bytes() for f in module_files)).hexdigest() module: ModuleType if cached_module is None: module = importlib.util.module_from_spec(module_spec) # insert it into sys.modules before any loading begins sys.modules[name] = module else: module = cached_module # reload in both cases, unless the module is already imported and the hash hits if getattr(module, "__transformers_module_hash__", "") != module_hash: module_spec.loader.exec_module(module) module.__transformers_module_hash__ = module_hash return getattr(module, class_name) def get_cached_module_file( pretrained_model_name_or_path: Union[str, os.PathLike], module_file: str, cache_dir: Optional[Union[str, os.PathLike]] = None, force_download: bool = False, proxies: Optional[dict[str, str]] = None, token: Optional[Union[bool, str]] = None, revision: Optional[str] = None, local_files_only: bool = False, repo_type: Optional[str] = None, _commit_hash: Optional[str] = None, **deprecated_kwargs, ) -> str: """ Prepares Downloads a module from a local folder or a distant repo and returns its path inside the cached Transformers module. Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained model configuration hosted inside a model repo on huggingface.co. - a path to a *directory* containing a configuration file saved using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`. module_file (`str`): The name of the module file containing the class to look for. cache_dir (`str` or `os.PathLike`, *optional*): Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force to (re-)download the configuration files and override the cached versions if they exist. proxies (`dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. token (`str` or *bool*, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated when running `hf auth login` (stored in `~/.huggingface`). revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. local_files_only (`bool`, *optional*, defaults to `False`): If `True`, will only try to load the tokenizer configuration from local files. repo_type (`str`, *optional*): Specify the repo type (useful when downloading from a space for instance). <Tip> Passing `token=True` is required when you want to use a private model. </Tip> Returns: `str`: The path to the module inside the cache. """ if is_offline_mode() and not local_files_only: logger.info("Offline mode: forcing local_files_only=True") local_files_only = True # Download and cache module_file from the repo `pretrained_model_name_or_path` of grab it if it's a local file. pretrained_model_name_or_path = str(pretrained_model_name_or_path) is_local = os.path.isdir(pretrained_model_name_or_path) if is_local: submodule = _sanitize_module_name(os.path.basename(pretrained_model_name_or_path)) else: submodule = os.path.sep.join(map(_sanitize_module_name, pretrained_model_name_or_path.split("/"))) cached_module = try_to_load_from_cache( pretrained_model_name_or_path, module_file, cache_dir=cache_dir, revision=_commit_hash, repo_type=repo_type ) new_files = [] try: # Load from URL or cache if already cached resolved_module_file = cached_file( pretrained_model_name_or_path, module_file, cache_dir=cache_dir, force_download=force_download, proxies=proxies, local_files_only=local_files_only, token=token, revision=revision, repo_type=repo_type, _commit_hash=_commit_hash, ) if not is_local and cached_module != resolved_module_file: new_files.append(module_file) except OSError: logger.info(f"Could not locate the {module_file} inside {pretrained_model_name_or_path}.") raise # Check we have all the requirements in our environment modules_needed = check_imports(resolved_module_file) # Now we move the module inside our cached dynamic modules. full_submodule = TRANSFORMERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(full_submodule) submodule_path = Path(HF_MODULES_CACHE) / full_submodule if submodule == _sanitize_module_name(os.path.basename(pretrained_model_name_or_path)): # We copy local files to avoid putting too many folders in sys.path. This copy is done when the file is new or # has changed since last copy. if not (submodule_path / module_file).exists() or not filecmp.cmp( resolved_module_file, str(submodule_path / module_file) ): (submodule_path / module_file).parent.mkdir(parents=True, exist_ok=True) shutil.copy(resolved_module_file, submodule_path / module_file) importlib.invalidate_caches() for module_needed in modules_needed: module_needed = Path(module_file).parent / f"{module_needed}.py" module_needed_file = os.path.join(pretrained_model_name_or_path, module_needed) if not (submodule_path / module_needed).exists() or not filecmp.cmp( module_needed_file, str(submodule_path / module_needed) ): shutil.copy(module_needed_file, submodule_path / module_needed) importlib.invalidate_caches() else: # Get the commit hash commit_hash = extract_commit_hash(resolved_module_file, _commit_hash) # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. submodule_path = submodule_path / commit_hash full_submodule = full_submodule + os.path.sep + commit_hash full_submodule_module_file_path = os.path.join(full_submodule, module_file) create_dynamic_module(Path(full_submodule_module_file_path).parent) if not (submodule_path / module_file).exists(): shutil.copy(resolved_module_file, submodule_path / module_file) importlib.invalidate_caches() # Make sure we also have every file with relative for module_needed in modules_needed: if not ((submodule_path / module_file).parent / f"{module_needed}.py").exists(): get_cached_module_file( pretrained_model_name_or_path, f"{Path(module_file).parent / module_needed}.py", cache_dir=cache_dir, force_download=force_download, proxies=proxies, token=token, revision=revision, local_files_only=local_files_only, _commit_hash=commit_hash, ) new_files.append(f"{module_needed}.py") if len(new_files) > 0 and revision is None: new_files = "\n".join([f"- {f}" for f in new_files]) repo_type_str = "" if repo_type is None else f"{repo_type}s/" url = f"https://huggingface.co/{repo_type_str}{pretrained_model_name_or_path}" logger.warning( f"A new version of the following files was downloaded from {url}:\n{new_files}" "\n. Make sure to double-check they do not contain any added malicious code. To avoid downloading new " "versions of the code file, you can pin a revision." ) return os.path.join(full_submodule, module_file) def get_class_from_dynamic_module( class_reference: str, pretrained_model_name_or_path: Union[str, os.PathLike], cache_dir: Optional[Union[str, os.PathLike]] = None, force_download: bool = False, proxies: Optional[dict[str, str]] = None, token: Optional[Union[bool, str]] = None, revision: Optional[str] = None, local_files_only: bool = False, repo_type: Optional[str] = None, code_revision: Optional[str] = None, **kwargs, ) -> type: """ Extracts a class from a module file, present in the local folder or repository of a model. <Tip warning={true}> Calling this function will execute the code in the module file found locally or downloaded from the Hub. It should therefore only be called on trusted repos. </Tip> Args: class_reference (`str`): The full name of the class to load, including its module and optionally its repo. pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained model configuration hosted inside a model repo on huggingface.co. - a path to a *directory* containing a configuration file saved using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`. This is used when `class_reference` does not specify another repo. module_file (`str`): The name of the module file containing the class to look for. class_name (`str`): The name of the class to import in the module. cache_dir (`str` or `os.PathLike`, *optional*): Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force to (re-)download the configuration files and override the cached versions if they exist. proxies (`dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. token (`str` or `bool`, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated when running `hf auth login` (stored in `~/.huggingface`). revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. local_files_only (`bool`, *optional*, defaults to `False`): If `True`, will only try to load the tokenizer configuration from local files. repo_type (`str`, *optional*): Specify the repo type (useful when downloading from a space for instance). code_revision (`str`, *optional*, defaults to `"main"`): The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. <Tip> Passing `token=True` is required when you want to use a private model. </Tip> Returns: `typing.Type`: The class, dynamically imported from the module. Examples: ```python # Download module `modeling.py` from huggingface.co and cache then extract the class `MyBertModel` from this # module. cls = get_class_from_dynamic_module("modeling.MyBertModel", "sgugger/my-bert-model") # Download module `modeling.py` from a given repo and cache then extract the class `MyBertModel` from this # module. cls = get_class_from_dynamic_module("sgugger/my-bert-model--modeling.MyBertModel", "sgugger/another-bert-model") ```""" # Catch the name of the repo if it's specified in `class_reference` if "--" in class_reference: repo_id, class_reference = class_reference.split("--") else: repo_id = pretrained_model_name_or_path module_file, class_name = class_reference.split(".") if code_revision is None and pretrained_model_name_or_path == repo_id: code_revision = revision # And lastly we get the class inside our newly created module final_module = get_cached_module_file( repo_id, module_file + ".py", cache_dir=cache_dir, force_download=force_download, proxies=proxies, token=token, revision=code_revision, local_files_only=local_files_only, repo_type=repo_type, ) return get_class_in_module(class_name, final_module, force_reload=force_download) def custom_object_save(obj: Any, folder: Union[str, os.PathLike], config: Optional[dict] = None) -> list[str]: """ Save the modeling files corresponding to a custom model/configuration/tokenizer etc. in a given folder. Optionally adds the proper fields in a config. Args: obj (`Any`): The object for which to save the module files. folder (`str` or `os.PathLike`): The folder where to save. config (`PreTrainedConfig` or dictionary, `optional`): A config in which to register the auto_map corresponding to this custom object. Returns: `list[str]`: The list of files saved. """ if obj.__module__ == "__main__": logger.warning( f"We can't save the code defining {obj} in {folder} as it's been defined in __main__. You should put " "this code in a separate module so we can include it in the saved folder and make it easier to share via " "the Hub." ) return def _set_auto_map_in_config(_config): module_name = obj.__class__.__module__ last_module = module_name.split(".")[-1] full_name = f"{last_module}.{obj.__class__.__name__}" # Special handling for tokenizers if "Tokenizer" in full_name: slow_tokenizer_class = None fast_tokenizer_class = None if obj.__class__.__name__.endswith("Fast"): # Fast tokenizer: we have the fast tokenizer class and we may have the slow one has an attribute. fast_tokenizer_class = f"{last_module}.{obj.__class__.__name__}" if getattr(obj, "slow_tokenizer_class", None) is not None: slow_tokenizer = getattr(obj, "slow_tokenizer_class") slow_tok_module_name = slow_tokenizer.__module__ last_slow_tok_module = slow_tok_module_name.split(".")[-1] slow_tokenizer_class = f"{last_slow_tok_module}.{slow_tokenizer.__name__}" else: # Slow tokenizer: no way to have the fast class slow_tokenizer_class = f"{last_module}.{obj.__class__.__name__}" full_name = (slow_tokenizer_class, fast_tokenizer_class) if isinstance(_config, dict): auto_map = _config.get("auto_map", {}) auto_map[obj._auto_class] = full_name _config["auto_map"] = auto_map elif getattr(_config, "auto_map", None) is not None: _config.auto_map[obj._auto_class] = full_name else: _config.auto_map = {obj._auto_class: full_name} # Add object class to the config auto_map if isinstance(config, (list, tuple)): for cfg in config: _set_auto_map_in_config(cfg) elif config is not None: _set_auto_map_in_config(config) result = [] # Copy module file to the output folder. object_file = sys.modules[obj.__module__].__file__ dest_file = Path(folder) / (Path(object_file).name) shutil.copy(object_file, dest_file) result.append(dest_file) # Gather all relative imports recursively and make sure they are copied as well. for needed_file in get_relative_import_files(object_file): dest_file = Path(folder) / (Path(needed_file).name) shutil.copy(needed_file, dest_file) result.append(dest_file) return result def _raise_timeout_error(signum, frame): raise ValueError( "Loading this model requires you to execute custom code contained in the model repository on your local " "machine. Please set the option `trust_remote_code=True` to permit loading of this model." ) TIME_OUT_REMOTE_CODE = 15 def resolve_trust_remote_code( trust_remote_code, model_name, has_local_code, has_remote_code, error_message=None, upstream_repo=None ): """ Resolves the `trust_remote_code` argument. If there is remote code to be loaded, the user must opt-in to loading it. Args: trust_remote_code (`bool` or `None`): User-defined `trust_remote_code` value. model_name (`str`): The name of the model repository in huggingface.co. has_local_code (`bool`): Whether the model has local code. has_remote_code (`bool`): Whether the model has remote code. error_message (`str`, *optional*): Custom error message to display if there is remote code to load and the user didn't opt-in. If unset, the error message will be regarding loading a model with custom code. Returns: The resolved `trust_remote_code` value. """ if error_message is None: if upstream_repo is not None: error_message = ( f"The repository {model_name} references custom code contained in {upstream_repo} which " f"must be executed to correctly load the model. You can inspect the repository " f"content at https://hf.co/{upstream_repo} .\n" ) elif os.path.isdir(model_name): error_message = ( f"The repository {model_name} contains custom code which must be executed " f"to correctly load the model. You can inspect the repository " f"content at {os.path.abspath(model_name)} .\n" ) else: error_message = ( f"The repository {model_name} contains custom code which must be executed " f"to correctly load the model. You can inspect the repository " f"content at https://hf.co/{model_name} .\n" ) if trust_remote_code is None: if has_local_code: trust_remote_code = False elif has_remote_code and TIME_OUT_REMOTE_CODE > 0: prev_sig_handler = None try: prev_sig_handler = signal.signal(signal.SIGALRM, _raise_timeout_error) signal.alarm(TIME_OUT_REMOTE_CODE) while trust_remote_code is None: answer = input( f"{error_message} You can inspect the repository content at https://hf.co/{model_name}.\n" f"You can avoid this prompt in future by passing the argument `trust_remote_code=True`.\n\n" f"Do you wish to run the custom code? [y/N] " ) if answer.lower() in ["yes", "y", "1"]: trust_remote_code = True elif answer.lower() in ["no", "n", "0", ""]: trust_remote_code = False signal.alarm(0) except Exception: # OS which does not support signal.SIGALRM raise ValueError( f"{error_message} You can inspect the repository content at https://hf.co/{model_name}.\n" f"Please pass the argument `trust_remote_code=True` to allow custom code to be run." ) finally: if prev_sig_handler is not None: signal.signal(signal.SIGALRM, prev_sig_handler) signal.alarm(0) elif has_remote_code: # For the CI which puts the timeout at 0 _raise_timeout_error(None, None) if has_remote_code and not has_local_code and not trust_remote_code: raise ValueError( f"{error_message} You can inspect the repository content at https://hf.co/{model_name}.\n" f"Please pass the argument `trust_remote_code=True` to allow custom code to be run." ) return trust_remote_code def check_python_requirements(path_or_repo_id, requirements_file="requirements.txt", **kwargs): """
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/training_args.py
src/transformers/training_args.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import contextlib import json import math import os import warnings from dataclasses import asdict, dataclass, field, fields from datetime import timedelta from enum import Enum from functools import cached_property from typing import Any from .debug_utils import DebugOption from .trainer_utils import ( FSDPOption, HubStrategy, IntervalStrategy, SaveStrategy, SchedulerType, ) from .utils import ( ACCELERATE_MIN_VERSION, ExplicitEnum, is_accelerate_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_torch_available, is_torch_bf16_gpu_available, is_torch_cuda_available, is_torch_hpu_available, is_torch_mlu_available, is_torch_mps_available, is_torch_musa_available, is_torch_neuroncore_available, is_torch_npu_available, is_torch_tf32_available, is_torch_xla_available, is_torch_xpu_available, logging, requires_backends, ) from .utils.generic import strtobool from .utils.import_utils import enable_tf32, is_optimum_neuron_available logger = logging.get_logger(__name__) log_levels = logging.get_log_levels_dict().copy() trainer_log_levels = dict(**log_levels, passive=-1) if is_torch_available(): import torch import torch.distributed as dist if is_accelerate_available(): from accelerate.state import AcceleratorState, PartialState from accelerate.utils import DistributedType from .trainer_pt_utils import AcceleratorConfig if is_accelerate_available("1.10.1"): from accelerate.parallelism_config import ParallelismConfig else: ParallelismConfig = Any if is_torch_xla_available(): import torch_xla.core.xla_model as xm if is_torch_neuroncore_available(check_device=False): # torchrun support # https://github.com/pytorch/xla/pull/3609 if os.environ.get("TORCHELASTIC_RUN_ID"): if is_optimum_neuron_available(): logger.info( "Make sure that you are performing the training with the NeuronTrainer from optimum[neuron], this " "will fail otherwise." ) else: logger.warning( "Please use the NeuronTrainer from optimum[neuron] instead of the Transformers library to perform " "training on AWS Trainium instances. More information here: " "https://github.com/huggingface/optimum-neuron" ) import torch_xla.distributed.xla_backend as xbn if not isinstance(dist.group.WORLD, xbn.ProcessGroupXla): dist.init_process_group(backend="xla") if not isinstance(dist.group.WORLD, xbn.ProcessGroupXla): raise AssertionError("Failed to initialize torch.distributed process group using XLA backend.") if is_sagemaker_mp_enabled(): import smdistributed.modelparallel.torch as smp smp.init() def get_int_from_env(env_keys, default): """Returns the first positive env value found in the `env_keys` list or the default.""" for e in env_keys: val = int(os.environ.get(e, "-1")) if val >= 0: return val return default def get_xla_device_type(device: "torch.device") -> str | None: """ Returns the xla device type (CPU|GPU|TPU) or None if the device is a non-xla device. """ if is_torch_xla_available(): if device.type == "cpu": return "CPU" return xm.xla_real_devices([device])[0].split(":")[0] return None class OptimizerNames(ExplicitEnum): """ Stores the acceptable string identifiers for optimizers. """ ADAMW_TORCH = "adamw_torch" ADAMW_TORCH_FUSED = "adamw_torch_fused" ADAMW_TORCH_XLA = "adamw_torch_xla" ADAMW_TORCH_NPU_FUSED = "adamw_torch_npu_fused" ADAMW_APEX_FUSED = "adamw_apex_fused" ADAFACTOR = "adafactor" ADAMW_ANYPRECISION = "adamw_anyprecision" ADAMW_TORCH_4BIT = "adamw_torch_4bit" ADAMW_TORCH_8BIT = "adamw_torch_8bit" ADEMAMIX = "ademamix" SGD = "sgd" ADAGRAD = "adagrad" ADAMW_BNB = "adamw_bnb_8bit" ADAMW_8BIT = "adamw_8bit" # just an alias for adamw_bnb_8bit ADEMAMIX_8BIT = "ademamix_8bit" LION_8BIT = "lion_8bit" LION = "lion_32bit" PAGED_ADAMW = "paged_adamw_32bit" PAGED_ADAMW_8BIT = "paged_adamw_8bit" PAGED_ADEMAMIX = "paged_ademamix_32bit" PAGED_ADEMAMIX_8BIT = "paged_ademamix_8bit" PAGED_LION = "paged_lion_32bit" PAGED_LION_8BIT = "paged_lion_8bit" RMSPROP = "rmsprop" RMSPROP_BNB = "rmsprop_bnb" RMSPROP_8BIT = "rmsprop_bnb_8bit" RMSPROP_32BIT = "rmsprop_bnb_32bit" GALORE_ADAMW = "galore_adamw" GALORE_ADAMW_8BIT = "galore_adamw_8bit" GALORE_ADAFACTOR = "galore_adafactor" GALORE_ADAMW_LAYERWISE = "galore_adamw_layerwise" GALORE_ADAMW_8BIT_LAYERWISE = "galore_adamw_8bit_layerwise" GALORE_ADAFACTOR_LAYERWISE = "galore_adafactor_layerwise" LOMO = "lomo" ADALOMO = "adalomo" GROKADAMW = "grokadamw" SCHEDULE_FREE_RADAM = "schedule_free_radam" SCHEDULE_FREE_ADAMW = "schedule_free_adamw" SCHEDULE_FREE_SGD = "schedule_free_sgd" APOLLO_ADAMW = "apollo_adamw" APOLLO_ADAMW_LAYERWISE = "apollo_adamw_layerwise" STABLE_ADAMW = "stable_adamw" def _convert_str_dict(passed_value: dict): "Safely checks that a passed value is a dictionary and converts any string values to their appropriate types." for key, value in passed_value.items(): if isinstance(value, dict): passed_value[key] = _convert_str_dict(value) elif isinstance(value, str): # First check for bool and convert if value.lower() in ("true", "false"): passed_value[key] = value.lower() == "true" # Check for digit elif value.isdigit(): passed_value[key] = int(value) elif value.replace(".", "", 1).isdigit(): passed_value[key] = float(value) return passed_value # TODO: `TrainingArguments` users rely on it being fully mutable. In the future see if we can narrow this to a few keys: https://github.com/huggingface/transformers/pull/25903 @dataclass class TrainingArguments: """ TrainingArguments is the subset of the arguments we use in our example scripts **which relate to the training loop itself**. Using [`HfArgumentParser`] we can turn this class into [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the command line. Parameters: output_dir (`str`, *optional*, defaults to `"trainer_output"`): The output directory where the model predictions and checkpoints will be written. do_train (`bool`, *optional*, defaults to `False`): Whether to run training or not. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. do_eval (`bool`, *optional*): Whether to run evaluation on the validation set or not. Will be set to `True` if `eval_strategy` is different from `"no"`. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. do_predict (`bool`, *optional*, defaults to `False`): Whether to run predictions on the test set or not. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. eval_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`): The evaluation strategy to adopt during training. Possible values are: - `"no"`: No evaluation is done during training. - `"steps"`: Evaluation is done (and logged) every `eval_steps`. - `"epoch"`: Evaluation is done at the end of each epoch. prediction_loss_only (`bool`, *optional*, defaults to `False`): When performing evaluation and generating predictions, only returns the loss. per_device_train_batch_size (`int`, *optional*, defaults to 8): The batch size *per device*. The **global batch size** is computed as: `per_device_train_batch_size * number_of_devices` in multi-GPU or distributed setups. per_device_eval_batch_size (`int`, *optional*, defaults to 8): The batch size per device accelerator core/CPU for evaluation. gradient_accumulation_steps (`int`, *optional*, defaults to 1): Number of updates steps to accumulate the gradients for, before performing a backward/update pass. <Tip warning={true}> When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every `gradient_accumulation_steps * xxx_step` training examples. </Tip> eval_accumulation_steps (`int`, *optional*): Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If left unset, the whole predictions are accumulated on the device accelerator before being moved to the CPU (faster but requires more memory). eval_delay (`float`, *optional*): Number of epochs or steps to wait for before the first evaluation can be performed, depending on the eval_strategy. torch_empty_cache_steps (`int`, *optional*): Number of steps to wait before calling `torch.<device>.empty_cache()`. If left unset or set to None, cache will not be emptied. <Tip> This can help avoid CUDA out-of-memory errors by lowering peak VRAM usage at a cost of about [10% slower performance](https://github.com/huggingface/transformers/issues/31372). </Tip> learning_rate (`float`, *optional*, defaults to 5e-5): The initial learning rate for [`AdamW`] optimizer. weight_decay (`float`, *optional*, defaults to 0): The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in [`AdamW`] optimizer. adam_beta1 (`float`, *optional*, defaults to 0.9): The beta1 hyperparameter for the [`AdamW`] optimizer. adam_beta2 (`float`, *optional*, defaults to 0.999): The beta2 hyperparameter for the [`AdamW`] optimizer. adam_epsilon (`float`, *optional*, defaults to 1e-8): The epsilon hyperparameter for the [`AdamW`] optimizer. max_grad_norm (`float`, *optional*, defaults to 1.0): Maximum gradient norm (for gradient clipping). num_train_epochs(`float`, *optional*, defaults to 3.0): Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training). max_steps (`int`, *optional*, defaults to -1): If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until `max_steps` is reached. lr_scheduler_type (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`): The scheduler type to use. See the documentation of [`SchedulerType`] for all possible values. lr_scheduler_kwargs (`dict` or `str`, *optional*, defaults to `None`): The extra arguments for the lr_scheduler. See the documentation of each scheduler for possible values. warmup_steps (`int` or `float`, *optional*, defaults to 0): Number of steps used for a linear warmup from 0 to `learning_rate`. Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of steps used for a linear warmup from 0 to `learning_rate`. log_level (`str`, *optional*, defaults to `passive`): Logger log level to use on the main process. Possible choices are the log levels as strings: 'debug', 'info', 'warning', 'error' and 'critical', plus a 'passive' level which doesn't set anything and keeps the current log level for the Transformers library (which will be `"warning"` by default). log_level_replica (`str`, *optional*, defaults to `"warning"`): Logger log level to use on replicas. Same choices as `log_level`" log_on_each_node (`bool`, *optional*, defaults to `True`): In multinode distributed training, whether to log using `log_level` once per node, or only on the main node. logging_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`): The logging strategy to adopt during training. Possible values are: - `"no"`: No logging is done during training. - `"epoch"`: Logging is done at the end of each epoch. - `"steps"`: Logging is done every `logging_steps`. logging_first_step (`bool`, *optional*, defaults to `False`): Whether to log the first `global_step` or not. logging_steps (`int` or `float`, *optional*, defaults to 500): Number of update steps between two logs if `logging_strategy="steps"`. Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps. logging_nan_inf_filter (`bool`, *optional*, defaults to `True`): Whether to filter `nan` and `inf` losses for logging. If set to `True` the loss of every step that is `nan` or `inf` is filtered and the average loss of the current logging window is taken instead. <Tip> `logging_nan_inf_filter` only influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model. </Tip> save_strategy (`str` or [`~trainer_utils.SaveStrategy`], *optional*, defaults to `"steps"`): The checkpoint save strategy to adopt during training. Possible values are: - `"no"`: No save is done during training. - `"epoch"`: Save is done at the end of each epoch. - `"steps"`: Save is done every `save_steps`. - `"best"`: Save is done whenever a new `best_metric` is achieved. If `"epoch"` or `"steps"` is chosen, saving will also be performed at the very end of training, always. save_steps (`int` or `float`, *optional*, defaults to 500): Number of updates steps before two checkpoint saves if `save_strategy="steps"`. Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps. save_total_limit (`int`, *optional*): If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in `output_dir`. When `load_best_model_at_end` is enabled, the "best" checkpoint according to `metric_for_best_model` will always be retained in addition to the most recent ones. For example, for `save_total_limit=5` and `load_best_model_at_end`, the four last checkpoints will always be retained alongside the best model. When `save_total_limit=1` and `load_best_model_at_end`, it is possible that two checkpoints are saved: the last one and the best one (if they are different). enable_jit_checkpoint (`bool`, *optional*, defaults to `False`): Whether to enable Just-In-Time (JIT) checkpointing on SIGTERM signal. When enabled, training will checkpoint upon receiving SIGTERM, allowing for graceful termination without losing progress. This is particularly useful for shared clusters with preemptible workloads (e.g., Kueue). **Important**: You must configure your orchestrator's graceful shutdown period to allow sufficient time for checkpoint completion. For Kubernetes, set `terminationGracePeriodSeconds` in your job definition (method varies by cloud-native trainer: Kubeflow, Ray, etc.). Note: the default is only 30 seconds, which is typically insufficient. For Slurm, use `--signal=USR1@<seconds>` in your sbatch script to send SIGTERM with adequate time before the job time limit. Calculate the required grace period as: longest possible iteration time + checkpoint saving time. For example, if an iteration takes 2 minutes and checkpoint saving takes 2 minutes, set at least 4 minutes (240 seconds) of grace time. save_on_each_node (`bool`, *optional*, defaults to `False`): When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one. This should not be activated when the different nodes use the same storage as the files will be saved with the same names for each node. save_only_model (`bool`, *optional*, defaults to `False`): When checkpointing, whether to only save the model, or also the optimizer, scheduler & rng state. Note that when this is true, you won't be able to resume training from checkpoint. This enables you to save storage by not storing the optimizer, scheduler & rng state. You can only load the model using `from_pretrained` with this option set to `True`. restore_callback_states_from_checkpoint (`bool`, *optional*, defaults to `False`): Whether to restore the callback states from the checkpoint. If `True`, will override callbacks passed to the `Trainer` if they exist in the checkpoint." use_cpu (`bool`, *optional*, defaults to `False`): Whether or not to use cpu. If set to False, we will use the available torch device/backend. seed (`int`, *optional*, defaults to 42): Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the [`~Trainer.model_init`] function to instantiate the model if it has some randomly initialized parameters. data_seed (`int`, *optional*): Random seed to be used with data samplers. If not set, random generators for data sampling will use the same seed as `seed`. This can be used to ensure reproducibility of data sampling, independent of the model seed. bf16 (`bool`, *optional*, defaults to `False`): Whether to use bf16 16-bit (mixed) precision training instead of 32-bit training. Requires Ampere or higher NVIDIA architecture or Intel XPU or using CPU (use_cpu) or Ascend NPU. fp16 (`bool`, *optional*, defaults to `False`): Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training. bf16_full_eval (`bool`, *optional*, defaults to `False`): Whether to use full bfloat16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values. fp16_full_eval (`bool`, *optional*, defaults to `False`): Whether to use full float16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values. tf32 (`bool`, *optional*): Whether to enable the TF32 mode, available in Ampere and newer GPU architectures. The default value depends on PyTorch's version default of `torch.backends.cuda.matmul.allow_tf32` and For PyTorch 2.9+ torch.backends.cuda.matmul.fp32_precision. For more details please refer to the [TF32](https://huggingface.co/docs/transformers/perf_train_gpu_one#tf32) documentation. This is an experimental API and it may change. ddp_backend (`str`, *optional*): The backend to use for distributed training. Must be one of `"nccl"`, `"mpi"`, `"ccl"`, `"gloo"`, `"hccl"`. dataloader_drop_last (`bool`, *optional*, defaults to `False`): Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not. eval_steps (`int` or `float`, *optional*): Number of update steps between two evaluations if `eval_strategy="steps"`. Will default to the same value as `logging_steps` if not set. Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps. dataloader_num_workers (`int`, *optional*, defaults to 0): Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process. run_name (`str`, *optional*): A descriptor for the run. Typically used for [trackio](https://github.com/gradio-app/trackio), [wandb](https://www.wandb.com/), [mlflow](https://www.mlflow.org/), [comet](https://www.comet.com/site) and [swanlab](https://swanlab.cn) logging. disable_tqdm (`bool`, *optional*): Whether or not to disable the tqdm progress bars and table of metrics produced by [`~notebook.NotebookTrainingTracker`] in Jupyter Notebooks. Will default to `True` if the logging level is set to warn or lower (default), `False` otherwise. remove_unused_columns (`bool`, *optional*, defaults to `True`): Whether or not to automatically remove the columns unused by the model forward method. label_names (`list[str]`, *optional*): The list of keys in your dictionary of inputs that correspond to the labels. Will eventually default to the list of argument names accepted by the model that contain the word "label", except if the model used is one of the `XxxForQuestionAnswering` in which case it will also include the `["start_positions", "end_positions"]` keys. You should only specify `label_names` if you're using custom label names or if your model's `forward` consumes multiple label tensors (e.g., extractive QA). load_best_model_at_end (`bool`, *optional*, defaults to `False`): Whether or not to load the best model found during training at the end of training. When this option is enabled, the best checkpoint will always be saved. See [`save_total_limit`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.save_total_limit) for more. <Tip> When set to `True`, the parameters `save_strategy` needs to be the same as `eval_strategy`, and in the case it is "steps", `save_steps` must be a round multiple of `eval_steps`. </Tip> metric_for_best_model (`str`, *optional*): Use in conjunction with `load_best_model_at_end` to specify the metric to use to compare two different models. Must be the name of a metric returned by the evaluation with or without the prefix `"eval_"`. If not specified, this will default to `"loss"` when either `load_best_model_at_end == True` or `lr_scheduler_type == SchedulerType.REDUCE_ON_PLATEAU` (to use the evaluation loss). If you set this value, `greater_is_better` will default to `True` unless the name ends with "loss". Don't forget to set it to `False` if your metric is better when lower. greater_is_better (`bool`, *optional*): Use in conjunction with `load_best_model_at_end` and `metric_for_best_model` to specify if better models should have a greater metric or not. Will default to: - `True` if `metric_for_best_model` is set to a value that doesn't end in `"loss"`. - `False` if `metric_for_best_model` is not set, or set to a value that ends in `"loss"`. ignore_data_skip (`bool`, *optional*, defaults to `False`): When resuming training, whether or not to skip the epochs and batches to get the data loading at the same stage as in the previous training. If set to `True`, the training will begin faster (as that skipping step can take a long time) but will not yield the same results as the interrupted training would have. fsdp (`bool`, `str` or list of [`~trainer_utils.FSDPOption`], *optional*, defaults to `None`): Use PyTorch Distributed Parallel Training (in distributed training only). A list of options along the following: - `"full_shard"`: Shard parameters, gradients and optimizer states. - `"shard_grad_op"`: Shard optimizer states and gradients. - `"hybrid_shard"`: Apply `FULL_SHARD` within a node, and replicate parameters across nodes. - `"hybrid_shard_zero2"`: Apply `SHARD_GRAD_OP` within a node, and replicate parameters across nodes. - `"offload"`: Offload parameters and gradients to CPUs (only compatible with `"full_shard"` and `"shard_grad_op"`). - `"auto_wrap"`: Automatically recursively wrap layers with FSDP using `default_auto_wrap_policy`. fsdp_config (`str` or `dict`, *optional*): Config to be used with fsdp (Pytorch Distributed Parallel Training). The value is either a location of fsdp json config file (e.g., `fsdp_config.json`) or an already loaded json file as `dict`. A List of config and its options: - fsdp_version (`int`, *optional*, defaults to `1`): The version of FSDP to use. Defaults to 1. - min_num_params (`int`, *optional*, defaults to `0`): FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `fsdp` field is passed). - transformer_layer_cls_to_wrap (`list[str]`, *optional*): List of transformer layer class names (case-sensitive) to wrap, e.g, `BertLayer`, `GPTJBlock`, `T5Block` .... (useful only when `fsdp` flag is passed). - backward_prefetch (`str`, *optional*) FSDP's backward prefetch mode. Controls when to prefetch next set of parameters (useful only when `fsdp` field is passed). A list of options along the following: - `"backward_pre"` : Prefetches the next set of parameters before the current set of parameter's gradient computation. - `"backward_post"` : This prefetches the next set of parameters after the current set of parameter's gradient computation. - forward_prefetch (`bool`, *optional*, defaults to `False`) FSDP's forward prefetch mode (useful only when `fsdp` field is passed). If `"True"`, then FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass. - limit_all_gathers (`bool`, *optional*, defaults to `False`) FSDP's limit_all_gathers (useful only when `fsdp` field is passed). If `"True"`, FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers. - use_orig_params (`bool`, *optional*, defaults to `True`) If `"True"`, allows non-uniform `requires_grad` during init, which means support for interspersed frozen and trainable parameters. Useful in cases such as parameter-efficient fine-tuning. Please refer this [blog](https://dev-discuss.pytorch.org/t/rethinking-pytorch-fully-sharded-data-parallel-fsdp-from-first-principles/1019 - sync_module_states (`bool`, *optional*, defaults to `True`) If `"True"`, each individually wrapped FSDP unit will broadcast module parameters from rank 0 to ensure they are the same across all ranks after initialization - cpu_ram_efficient_loading (`bool`, *optional*, defaults to `False`) If `"True"`, only the first process loads the pretrained model checkpoint while all other processes have empty weights. When this setting as `"True"`, `sync_module_states` also must to be `"True"`, otherwise all the processes except the main process would have random weights leading to unexpected behaviour during training. - activation_checkpointing (`bool`, *optional*, defaults to `False`): If `"True"`, activation checkpointing is a technique to reduce memory usage by clearing activations of certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time for reduced memory usage. - xla (`bool`, *optional*, defaults to `False`): Whether to use PyTorch/XLA Fully Sharded Data Parallel Training. This is an experimental feature and its API may evolve in the future. - xla_fsdp_settings (`dict`, *optional*) The value is a dictionary which stores the XLA FSDP wrapping parameters. For a complete list of options, please see [here]( https://github.com/pytorch/xla/blob/master/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py). - xla_fsdp_grad_ckpt (`bool`, *optional*, defaults to `False`): Will use gradient checkpointing over each nested XLA FSDP wrapped layer. This setting can only be used when the xla flag is set to true, and an auto wrapping policy is specified through fsdp_min_num_params or fsdp_transformer_layer_cls_to_wrap. deepspeed (`str` or `dict`, *optional*): Use [Deepspeed](https://github.com/deepspeedai/DeepSpeed). This is an experimental feature and its API may evolve in the future. The value is either the location of DeepSpeed json config file (e.g., `ds_config.json`) or an already loaded json file as a `dict`" <Tip warning={true}> If enabling any Zero-init, make sure that your model is not initialized until *after* initializing the `TrainingArguments`, else it will not be applied. </Tip> accelerator_config (`str`, `dict`, or `AcceleratorConfig`, *optional*): Config to be used with the internal `Accelerator` implementation. The value is either a location of accelerator json config file (e.g., `accelerator_config.json`), an already loaded json file as `dict`, or an instance of [`~trainer_pt_utils.AcceleratorConfig`]. A list of config and its options: - split_batches (`bool`, *optional*, defaults to `False`): Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set in your script multiplied by the number of processes. - dispatch_batches (`bool`, *optional*):
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/convert_slow_tokenizers_checkpoints_to_fast.py
src/transformers/convert_slow_tokenizers_checkpoints_to_fast.py
# Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Convert slow tokenizers checkpoints in fast (serialization format of the `tokenizers` library)""" import argparse import os from pathlib import Path import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() logger = logging.get_logger(__name__) TOKENIZER_CLASSES = {} for name in SLOW_TO_FAST_CONVERTERS: # Special cases for tokenizers that don't have their own Fast tokenizer if name == "Phi3Tokenizer": tokenizer_class_name = "LlamaTokenizerFast" elif name == "ElectraTokenizer": tokenizer_class_name = "BertTokenizerFast" else: tokenizer_class_name = name + "Fast" try: TOKENIZER_CLASSES[name] = getattr(transformers, tokenizer_class_name) except AttributeError: # Skip tokenizers that don't have a Fast version pass def convert_slow_checkpoint_to_fast(tokenizer_name, checkpoint_name, dump_path, force_download): if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f"Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys())}.") if tokenizer_name is None: tokenizer_names = TOKENIZER_CLASSES else: tokenizer_names = {tokenizer_name: getattr(transformers, tokenizer_name + "Fast")} logger.info(f"Loading tokenizer classes: {tokenizer_names}") for tokenizer_name in tokenizer_names: tokenizer_class = TOKENIZER_CLASSES[tokenizer_name] add_prefix = True if checkpoint_name is None: checkpoint_names = list(tokenizer_class.max_model_input_sizes.keys()) else: checkpoint_names = [checkpoint_name] logger.info(f"For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}") for checkpoint in checkpoint_names: logger.info(f"Loading {tokenizer_class.__class__.__name__} {checkpoint}") # Load tokenizer tokenizer = tokenizer_class.from_pretrained(checkpoint, force_download=force_download) # Save fast tokenizer logger.info(f"Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}") # For organization names we create sub-directories if "/" in checkpoint: checkpoint_directory, checkpoint_prefix_name = checkpoint.split("/") dump_path_full = os.path.join(dump_path, checkpoint_directory) # Security check try: Path(dump_path_full).resolve().relative_to(Path(dump_path).resolve()) except ValueError: raise ValueError( f"Invalid checkpoint path: '{checkpoint}' attempts to escape `dump_path`: {dump_path}" ) elif add_prefix: checkpoint_prefix_name = checkpoint dump_path_full = dump_path else: checkpoint_prefix_name = None dump_path_full = dump_path logger.info(f"=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}") if checkpoint in list(tokenizer.pretrained_vocab_files_map.values())[0]: file_path = list(tokenizer.pretrained_vocab_files_map.values())[0][checkpoint] next_char = file_path.split(checkpoint)[-1][0] if next_char == "/": dump_path_full = os.path.join(dump_path_full, checkpoint_prefix_name) checkpoint_prefix_name = None logger.info(f"=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}") file_names = tokenizer.save_pretrained( dump_path_full, legacy_format=False, filename_prefix=checkpoint_prefix_name ) logger.info(f"=> File names {file_names}") for file_name in file_names: if not file_name.endswith("tokenizer.json"): os.remove(file_name) logger.info(f"=> removing {file_name}") if __name__ == "__main__": parser = argparse.ArgumentParser() # Required parameters parser.add_argument( "--dump_path", default=None, type=str, required=True, help="Path to output generated fast tokenizer files." ) parser.add_argument( "--tokenizer_name", default=None, type=str, help=( f"Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will " "download and convert all the checkpoints from AWS." ), ) parser.add_argument( "--checkpoint_name", default=None, type=str, help="Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.", ) parser.add_argument( "--force_download", action="store_true", help="Re-download checkpoints.", ) args = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/image_processing_utils_fast.py
src/transformers/image_processing_utils_fast.py
# Copyright 2024 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections.abc import Iterable from copy import deepcopy from functools import lru_cache, partial from typing import Any, Optional, Union import numpy as np from huggingface_hub.dataclasses import validate_typed_dict from .image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from .image_transforms import ( convert_to_rgb, get_resize_output_image_size, get_size_with_aspect_ratio, group_images_by_shape, reorder_images, ) from .image_utils import ( ChannelDimension, ImageInput, ImageType, SizeDict, get_image_size, get_image_size_for_max_height_width, get_image_type, infer_channel_dimension_format, make_flat_list_of_images, validate_kwargs, validate_preprocess_arguments, ) from .processing_utils import ImagesKwargs, Unpack from .utils import ( TensorType, auto_docstring, is_torch_available, is_torchvision_available, is_vision_available, logging, ) from .utils.import_utils import is_rocm_platform, is_torchdynamo_compiling if is_vision_available(): from .image_utils import PILImageResampling if is_torch_available(): import torch if is_torchvision_available(): from torchvision.transforms.v2 import functional as F from .image_utils import pil_torch_interpolation_mapping else: pil_torch_interpolation_mapping = None logger = logging.get_logger(__name__) @lru_cache(maxsize=10) def validate_fast_preprocess_arguments( do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, list[float]]] = None, image_std: Optional[Union[float, list[float]]] = None, do_center_crop: Optional[bool] = None, crop_size: Optional[SizeDict] = None, do_resize: Optional[bool] = None, size: Optional[SizeDict] = None, interpolation: Optional["F.InterpolationMode"] = None, return_tensors: Optional[Union[str, TensorType]] = None, data_format: ChannelDimension = ChannelDimension.FIRST, ): """ Checks validity of typically used arguments in an `ImageProcessorFast` `preprocess` method. Raises `ValueError` if arguments incompatibility is caught. """ validate_preprocess_arguments( do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, do_center_crop=do_center_crop, crop_size=crop_size, do_resize=do_resize, size=size, interpolation=interpolation, ) # Extra checks for ImageProcessorFast if return_tensors is not None and return_tensors != "pt": raise ValueError("Only returning PyTorch tensors is currently supported.") if data_format != ChannelDimension.FIRST: raise ValueError("Only channel first data format is currently supported.") def safe_squeeze(tensor: "torch.Tensor", axis: Optional[int] = None) -> "torch.Tensor": """ Squeezes a tensor, but only if the axis specified has dim 1. """ if axis is None: return tensor.squeeze() try: return tensor.squeeze(axis=axis) except ValueError: return tensor def max_across_indices(values: Iterable[Any]) -> list[Any]: """ Return the maximum value across all indices of an iterable of values. """ return [max(values_i) for values_i in zip(*values)] def get_max_height_width(images: list["torch.Tensor"]) -> tuple[int, ...]: """ Get the maximum height and width across all images in a batch. """ _, max_height, max_width = max_across_indices([img.shape for img in images]) return (max_height, max_width) def divide_to_patches( image: Union[np.ndarray, "torch.Tensor"], patch_size: int ) -> list[Union[np.ndarray, "torch.Tensor"]]: """ Divides an image into patches of a specified size. Args: image (`Union[np.array, "torch.Tensor"]`): The input image. patch_size (`int`): The size of each patch. Returns: list: A list of Union[np.array, "torch.Tensor"] representing the patches. """ patches = [] height, width = get_image_size(image, channel_dim=ChannelDimension.FIRST) for i in range(0, height, patch_size): for j in range(0, width, patch_size): patch = image[:, i : i + patch_size, j : j + patch_size] patches.append(patch) return patches @auto_docstring class BaseImageProcessorFast(BaseImageProcessor): r""" Base class for fast image processors using PyTorch and TorchVision for image transformations. This class provides a complete implementation for standard image preprocessing operations (resize, crop, rescale, normalize) with GPU support and batch processing optimizations. Most image processors can be implemented by simply setting class attributes; only processors requiring custom logic need to override methods. Basic Implementation -------------------- For processors that only need standard operations (resize, center crop, rescale, normalize), define class attributes: class MyImageProcessorFast(BaseImageProcessorFast): resample = PILImageResampling.BILINEAR image_mean = IMAGENET_DEFAULT_MEAN image_std = IMAGENET_DEFAULT_STD size = {"height": 224, "width": 224} do_resize = True do_rescale = True do_normalize = True Custom Processing ----------------- Override `_preprocess` (most common): For custom image processing logic, override `_preprocess`. This method receives a list of torch tensors with channel dimension first and should return a BatchFeature. Use `group_images_by_shape` and `reorder_images` for efficient batch processing: def _preprocess( self, images: list[torch.Tensor], do_resize: bool, size: SizeDict, # ... other parameters **kwargs, ) -> BatchFeature: # Group images by shape for batched operations grouped_images, indices = group_images_by_shape(images) processed_groups = {} for shape, stacked_images in grouped_images.items(): if do_resize: stacked_images = self.resize(stacked_images, size) # Custom processing here processed_groups[shape] = stacked_images processed_images = reorder_images(processed_groups, indices) return BatchFeature(data={"pixel_values": torch.stack(processed_images)}) Override `_preprocess_image_like_inputs` (for additional inputs): For processors handling multiple input types (e.g., images + segmentation maps), override this method: def _preprocess_image_like_inputs( self, images: ImageInput, segmentation_maps: Optional[ImageInput] = None, do_convert_rgb: bool, input_data_format: ChannelDimension, device: Optional[torch.device] = None, **kwargs, ) -> BatchFeature: images = self._prepare_image_like_inputs(images, do_convert_rgb, input_data_format, device) batch_feature = self._preprocess(images, **kwargs) if segmentation_maps is not None: # Process segmentation maps separately maps = self._prepare_image_like_inputs(segmentation_maps, ...) batch_feature["labels"] = self._preprocess(maps, ...) return batch_feature Override `_further_process_kwargs` (for custom kwargs formatting): To format custom kwargs before validation: def _further_process_kwargs(self, custom_param=None, **kwargs): kwargs = super()._further_process_kwargs(**kwargs) if custom_param is not None: kwargs["custom_param"] = self._format_custom_param(custom_param) return kwargs Override `_validate_preprocess_kwargs` (for custom validation): To add custom validation logic: def _validate_preprocess_kwargs(self, custom_param=None, **kwargs): super()._validate_preprocess_kwargs(**kwargs) if custom_param is not None and custom_param < 0: raise ValueError("custom_param must be non-negative") Override `_prepare_images_structure` (for nested inputs): By default, nested image lists are flattened. Override to preserve structure: def _prepare_images_structure(self, images, expected_ndims=3): # Custom logic to handle nested structure return images # Return as-is or with custom processing Custom Parameters ----------------- To add parameters beyond `ImagesKwargs`, create a custom kwargs class and set it as `valid_kwargs`: class MyImageProcessorKwargs(ImagesKwargs): custom_param: Optional[int] = None another_param: Optional[bool] = None class MyImageProcessorFast(BaseImageProcessorFast): valid_kwargs = MyImageProcessorKwargs custom_param = 10 # default value def _preprocess(self, images, custom_param, **kwargs): # Use custom_param in processing ... Key Notes --------- - Images in `_preprocess` are always torch tensors with channel dimension first, regardless of input format - Arguments not provided by users default to class attribute values - Use batch processing utilities (`group_images_by_shape`, `reorder_images`) for GPU efficiency - Image loading, format conversion, and argument handling are automatic - focus only on processing logic """ resample = None image_mean = None image_std = None size = None default_to_square = True crop_size = None do_resize = None do_center_crop = None do_pad = None pad_size = None do_rescale = None rescale_factor = 1 / 255 do_normalize = None do_convert_rgb = None return_tensors = None data_format = ChannelDimension.FIRST input_data_format = None device = None model_input_names = ["pixel_values"] image_seq_length = None valid_kwargs = ImagesKwargs unused_kwargs = None def __init__(self, **kwargs: Unpack[ImagesKwargs]): super().__init__(**kwargs) kwargs = self.filter_out_unused_kwargs(kwargs) size = kwargs.pop("size", self.size) self.size = ( get_size_dict(size=size, default_to_square=kwargs.pop("default_to_square", self.default_to_square)) if size is not None else None ) crop_size = kwargs.pop("crop_size", self.crop_size) self.crop_size = get_size_dict(crop_size, param_name="crop_size") if crop_size is not None else None pad_size = kwargs.pop("pad_size", self.pad_size) self.pad_size = get_size_dict(size=pad_size, param_name="pad_size") if pad_size is not None else None for key in self.valid_kwargs.__annotations__: kwarg = kwargs.pop(key, None) if kwarg is not None: setattr(self, key, kwarg) else: setattr(self, key, deepcopy(getattr(self, key, None))) # get valid kwargs names self._valid_kwargs_names = list(self.valid_kwargs.__annotations__.keys()) @property def is_fast(self) -> bool: """ `bool`: Whether or not this image processor is a fast processor (backed by PyTorch and TorchVision). """ return True def pad( self, images: list["torch.Tensor"], pad_size: SizeDict = None, fill_value: Optional[int] = 0, padding_mode: Optional[str] = "constant", return_mask: bool = False, disable_grouping: Optional[bool] = False, is_nested: Optional[bool] = False, **kwargs, ) -> Union[tuple["torch.Tensor", "torch.Tensor"], "torch.Tensor"]: """ Pads images to `(pad_size["height"], pad_size["width"])` or to the largest size in the batch. Args: images (`list[torch.Tensor]`): Images to pad. pad_size (`SizeDict`, *optional*): Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image. fill_value (`int`, *optional*, defaults to `0`): The constant value used to fill the padded area. padding_mode (`str`, *optional*, defaults to "constant"): The padding mode to use. Can be any of the modes supported by `torch.nn.functional.pad` (e.g. constant, reflection, replication). return_mask (`bool`, *optional*, defaults to `False`): Whether to return a pixel mask to denote padded regions. disable_grouping (`bool`, *optional*, defaults to `False`): Whether to disable grouping of images by size. Returns: `Union[tuple[torch.Tensor, torch.Tensor], torch.Tensor]`: The padded images and pixel masks if `return_mask` is `True`. """ if pad_size is not None: if not (pad_size.height and pad_size.width): raise ValueError(f"Pad size must contain 'height' and 'width' keys only. Got pad_size={pad_size}.") pad_size = (pad_size.height, pad_size.width) else: pad_size = get_max_height_width(images) grouped_images, grouped_images_index = group_images_by_shape( images, disable_grouping=disable_grouping, is_nested=is_nested ) processed_images_grouped = {} processed_masks_grouped = {} for shape, stacked_images in grouped_images.items(): image_size = stacked_images.shape[-2:] padding_height = pad_size[0] - image_size[0] padding_width = pad_size[1] - image_size[1] if padding_height < 0 or padding_width < 0: raise ValueError( f"Padding dimensions are negative. Please make sure that the `pad_size` is larger than the " f"image size. Got pad_size={pad_size}, image_size={image_size}." ) if image_size != pad_size: padding = (0, 0, padding_width, padding_height) stacked_images = F.pad(stacked_images, padding, fill=fill_value, padding_mode=padding_mode) processed_images_grouped[shape] = stacked_images if return_mask: # keep only one from the channel dimension in pixel mask stacked_masks = torch.zeros_like(stacked_images, dtype=torch.int64)[..., 0, :, :] stacked_masks[..., : image_size[0], : image_size[1]] = 1 processed_masks_grouped[shape] = stacked_masks processed_images = reorder_images(processed_images_grouped, grouped_images_index, is_nested=is_nested) if return_mask: processed_masks = reorder_images(processed_masks_grouped, grouped_images_index, is_nested=is_nested) return processed_images, processed_masks return processed_images def resize( self, image: "torch.Tensor", size: SizeDict, interpolation: Optional["F.InterpolationMode"] = None, antialias: bool = True, **kwargs, ) -> "torch.Tensor": """ Resize an image to `(size["height"], size["width"])`. Args: image (`torch.Tensor`): Image to resize. size (`SizeDict`): Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image. interpolation (`InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`): `InterpolationMode` filter to use when resizing the image e.g. `InterpolationMode.BICUBIC`. antialias (`bool`, *optional*, defaults to `True`): Whether to use antialiasing. Returns: `torch.Tensor`: The resized image. """ interpolation = interpolation if interpolation is not None else F.InterpolationMode.BILINEAR if size.shortest_edge and size.longest_edge: # Resize the image so that the shortest edge or the longest edge is of the given size # while maintaining the aspect ratio of the original image. new_size = get_size_with_aspect_ratio( image.size()[-2:], size.shortest_edge, size.longest_edge, ) elif size.shortest_edge: new_size = get_resize_output_image_size( image, size=size.shortest_edge, default_to_square=False, input_data_format=ChannelDimension.FIRST, ) elif size.max_height and size.max_width: new_size = get_image_size_for_max_height_width(image.size()[-2:], size.max_height, size.max_width) elif size.height and size.width: new_size = (size.height, size.width) else: raise ValueError( "Size must contain 'height' and 'width' keys, or 'max_height' and 'max_width', or 'shortest_edge' key. Got" f" {size}." ) # This is a workaround to avoid a bug in torch.compile when dealing with uint8 on AMD MI3XX GPUs # Tracked in PyTorch issue: https://github.com/pytorch/pytorch/issues/155209 # TODO: remove this once the bug is fixed (detected with torch==2.7.0+git1fee196, torchvision==0.22.0+9eb57cd) if is_torchdynamo_compiling() and is_rocm_platform(): return self.compile_friendly_resize(image, new_size, interpolation, antialias) return F.resize(image, new_size, interpolation=interpolation, antialias=antialias) @staticmethod def compile_friendly_resize( image: "torch.Tensor", new_size: tuple[int, int], interpolation: Optional["F.InterpolationMode"] = None, antialias: bool = True, ) -> "torch.Tensor": """ A wrapper around `F.resize` so that it is compatible with torch.compile when the image is a uint8 tensor. """ if image.dtype == torch.uint8: # 256 is used on purpose instead of 255 to avoid numerical differences # see https://github.com/huggingface/transformers/pull/38540#discussion_r2127165652 image = image.float() / 256 image = F.resize(image, new_size, interpolation=interpolation, antialias=antialias) image = image * 256 # torch.where is used on purpose instead of torch.clamp to avoid bug in torch.compile # see https://github.com/huggingface/transformers/pull/38540#discussion_r2126888471 image = torch.where(image > 255, 255, image) image = torch.where(image < 0, 0, image) image = image.round().to(torch.uint8) else: image = F.resize(image, new_size, interpolation=interpolation, antialias=antialias) return image def rescale( self, image: "torch.Tensor", scale: float, **kwargs, ) -> "torch.Tensor": """ Rescale an image by a scale factor. image = image * scale. Args: image (`torch.Tensor`): Image to rescale. scale (`float`): The scaling factor to rescale pixel values by. Returns: `torch.Tensor`: The rescaled image. """ return image * scale def normalize( self, image: "torch.Tensor", mean: Union[float, Iterable[float]], std: Union[float, Iterable[float]], **kwargs, ) -> "torch.Tensor": """ Normalize an image. image = (image - image_mean) / image_std. Args: image (`torch.Tensor`): Image to normalize. mean (`torch.Tensor`, `float` or `Iterable[float]`): Image mean to use for normalization. std (`torch.Tensor`, `float` or `Iterable[float]`): Image standard deviation to use for normalization. Returns: `torch.Tensor`: The normalized image. """ return F.normalize(image, mean, std) @lru_cache(maxsize=10) def _fuse_mean_std_and_rescale_factor( self, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, list[float]]] = None, image_std: Optional[Union[float, list[float]]] = None, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, device: Optional["torch.device"] = None, ) -> tuple: if do_rescale and do_normalize: # Fused rescale and normalize image_mean = torch.tensor(image_mean, device=device) * (1.0 / rescale_factor) image_std = torch.tensor(image_std, device=device) * (1.0 / rescale_factor) do_rescale = False return image_mean, image_std, do_rescale def rescale_and_normalize( self, images: "torch.Tensor", do_rescale: bool, rescale_factor: float, do_normalize: bool, image_mean: Union[float, list[float]], image_std: Union[float, list[float]], ) -> "torch.Tensor": """ Rescale and normalize images. """ image_mean, image_std, do_rescale = self._fuse_mean_std_and_rescale_factor( do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, do_rescale=do_rescale, rescale_factor=rescale_factor, device=images.device, ) # if/elif as we use fused rescale and normalize if both are set to True if do_normalize: images = self.normalize(images.to(dtype=torch.float32), image_mean, image_std) elif do_rescale: images = self.rescale(images, rescale_factor) return images def center_crop( self, image: "torch.Tensor", size: SizeDict, **kwargs, ) -> "torch.Tensor": """ Note: override torchvision's center_crop to have the same behavior as the slow processor. Center crop an image to `(size["height"], size["width"])`. If the input size is smaller than `crop_size` along any edge, the image is padded with 0's and then center cropped. Args: image (`"torch.Tensor"`): Image to center crop. size (`dict[str, int]`): Size of the output image. Returns: `torch.Tensor`: The center cropped image. """ if size.height is None or size.width is None: raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}") image_height, image_width = image.shape[-2:] crop_height, crop_width = size.height, size.width if crop_width > image_width or crop_height > image_height: padding_ltrb = [ (crop_width - image_width) // 2 if crop_width > image_width else 0, (crop_height - image_height) // 2 if crop_height > image_height else 0, (crop_width - image_width + 1) // 2 if crop_width > image_width else 0, (crop_height - image_height + 1) // 2 if crop_height > image_height else 0, ] image = F.pad(image, padding_ltrb, fill=0) # PIL uses fill value 0 image_height, image_width = image.shape[-2:] if crop_width == image_width and crop_height == image_height: return image crop_top = int((image_height - crop_height) / 2.0) crop_left = int((image_width - crop_width) / 2.0) return F.crop(image, crop_top, crop_left, crop_height, crop_width) def convert_to_rgb( self, image: ImageInput, ) -> ImageInput: """ Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image as is. Args: image (ImageInput): The image to convert. Returns: ImageInput: The converted image. """ return convert_to_rgb(image) def filter_out_unused_kwargs(self, kwargs: dict): """ Filter out the unused kwargs from the kwargs dictionary. """ if self.unused_kwargs is None: return kwargs for kwarg_name in self.unused_kwargs: if kwarg_name in kwargs: logger.warning_once(f"This processor does not use the `{kwarg_name}` parameter. It will be ignored.") kwargs.pop(kwarg_name) return kwargs def _prepare_images_structure( self, images: ImageInput, expected_ndims: int = 3, ) -> ImageInput: """ Prepare the images structure for processing. Args: images (`ImageInput`): The input images to process. Returns: `ImageInput`: The images with a valid nesting. """ # Checks for `str` in case of URL/local path and optionally loads images images = self.fetch_images(images) return make_flat_list_of_images(images, expected_ndims=expected_ndims) def _process_image( self, image: ImageInput, do_convert_rgb: Optional[bool] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, device: Optional["torch.device"] = None, ) -> "torch.Tensor": image_type = get_image_type(image) if image_type not in [ImageType.PIL, ImageType.TORCH, ImageType.NUMPY]: raise ValueError(f"Unsupported input image type {image_type}") if do_convert_rgb: image = self.convert_to_rgb(image) if image_type == ImageType.PIL: image = F.pil_to_tensor(image) elif image_type == ImageType.NUMPY: # not using F.to_tensor as it doesn't handle (C, H, W) numpy arrays image = torch.from_numpy(image).contiguous() # If the image is 2D, we need to unsqueeze it to add a channel dimension for processing if image.ndim == 2: image = image.unsqueeze(0) # Infer the channel dimension format if not provided if input_data_format is None: input_data_format = infer_channel_dimension_format(image) if input_data_format == ChannelDimension.LAST: # We force the channel dimension to be first for torch tensors as this is what torchvision expects. image = image.permute(2, 0, 1).contiguous() # Now that we have torch tensors, we can move them to the right device if device is not None: image = image.to(device) return image def _prepare_image_like_inputs( self, images: ImageInput, do_convert_rgb: Optional[bool] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, device: Optional["torch.device"] = None, expected_ndims: int = 3, ) -> list["torch.Tensor"]: """ Prepare image-like inputs for processing. Args: images (`ImageInput`): The image-like inputs to process. do_convert_rgb (`bool`, *optional*): Whether to convert the images to RGB. input_data_format (`str` or `ChannelDimension`, *optional*): The input data format of the images. device (`torch.device`, *optional*): The device to put the processed images on. expected_ndims (`int`, *optional*): The expected number of dimensions for the images. (can be 2 for segmentation maps etc.) Returns: List[`torch.Tensor`]: The processed images. """ # Get structured images (potentially nested) images = self._prepare_images_structure(images, expected_ndims=expected_ndims) process_image_partial = partial( self._process_image, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device ) # Check if we have nested structure, assuming the nesting is consistent has_nested_structure = len(images) > 0 and isinstance(images[0], (list, tuple)) if has_nested_structure: processed_images = [[process_image_partial(img) for img in nested_list] for nested_list in images] else: processed_images = [process_image_partial(img) for img in images] return processed_images def _further_process_kwargs( self, size: Optional[SizeDict] = None, crop_size: Optional[SizeDict] = None, pad_size: Optional[SizeDict] = None, default_to_square: Optional[bool] = None, image_mean: Optional[Union[float, list[float]]] = None, image_std: Optional[Union[float, list[float]]] = None, data_format: Optional[ChannelDimension] = None, **kwargs, ) -> dict: """ Update kwargs that need further processing before being validated Can be overridden by subclasses to customize the processing of kwargs. """ if kwargs is None: kwargs = {} if size is not None: size = SizeDict(**get_size_dict(size=size, default_to_square=default_to_square)) if crop_size is not None: crop_size = SizeDict(**get_size_dict(crop_size, param_name="crop_size")) if pad_size is not None: pad_size = SizeDict(**get_size_dict(size=pad_size, param_name="pad_size")) if isinstance(image_mean, list): image_mean = tuple(image_mean) if isinstance(image_std, list): image_std = tuple(image_std) if data_format is None: data_format = ChannelDimension.FIRST kwargs["size"] = size kwargs["crop_size"] = crop_size kwargs["pad_size"] = pad_size kwargs["image_mean"] = image_mean kwargs["image_std"] = image_std kwargs["data_format"] = data_format # torch resize uses interpolation instead of resample # Check if resample is an int before checking if it's an instance of PILImageResampling # because if pillow < 9.1.0, resample is an int and PILImageResampling is a module. # Checking PILImageResampling will fail with error `TypeError: isinstance() arg 2 must be a type or tuple of types`. resample = kwargs.pop("resample") kwargs["interpolation"] = ( pil_torch_interpolation_mapping[resample] if isinstance(resample, (PILImageResampling, int)) else resample ) return kwargs def _validate_preprocess_kwargs( self, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, tuple[float]]] = None, image_std: Optional[Union[float, tuple[float]]] = None, do_resize: Optional[bool] = None, size: Optional[SizeDict] = None, do_center_crop: Optional[bool] = None, crop_size: Optional[SizeDict] = None, interpolation: Optional["F.InterpolationMode"] = None, return_tensors: Optional[Union[str, TensorType]] = None, data_format: Optional[ChannelDimension] = None, **kwargs, ): """ validate the kwargs for the preprocess method. """ validate_fast_preprocess_arguments( do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, do_resize=do_resize,
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/convert_slow_tokenizer.py
src/transformers/convert_slow_tokenizer.py
# Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Utilities to convert slow tokenizers in their fast tokenizers counterparts. All the conversions are grouped here to gather SentencePiece dependencies outside of the fast tokenizers files and allow to make our dependency on SentencePiece optional. """ import warnings from collections.abc import Collection from functools import lru_cache from typing import Optional from packaging import version from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors from tokenizers.models import BPE, Unigram, WordPiece from tqdm import tqdm from .utils import is_protobuf_available, is_sentencepiece_available, logging, requires_backends from .utils.import_utils import PROTOBUF_IMPORT_ERROR logger = logging.get_logger(__name__) MBART_LANGUAGES = [ "ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN", ] MBART50_LANGUAGES = MBART_LANGUAGES + [ "af_ZA", "az_AZ", "bn_IN", "fa_IR", "he_IL", "hr_HR", "id_ID", "ka_GE", "km_KH", "mk_MK", "ml_IN", "mn_MN", "mr_IN", "pl_PL", "ps_AF", "pt_XX", "sv_SE", "sw_KE", "ta_IN", "te_IN", "th_TH", "tl_XX", "uk_UA", "ur_PK", "xh_ZA", "gl_ES", "sl_SI", ] def import_protobuf(error_message=""): if is_sentencepiece_available(): from sentencepiece import sentencepiece_model_pb2 return sentencepiece_model_pb2 if is_protobuf_available(): import google.protobuf if version.parse(google.protobuf.__version__) < version.parse("4.0.0"): from transformers.utils import sentencepiece_model_pb2 else: from transformers.utils import sentencepiece_model_pb2_new as sentencepiece_model_pb2 return sentencepiece_model_pb2 else: raise ImportError(PROTOBUF_IMPORT_ERROR.format(error_message)) def _get_prepend_scheme(add_prefix_space: bool, original_tokenizer) -> str: if add_prefix_space: prepend_scheme = "always" if not getattr(original_tokenizer, "legacy", True): prepend_scheme = "first" else: prepend_scheme = "never" return prepend_scheme def generate_merges(vocab, vocab_scores, skip_tokens: Optional[Collection[str]] = None): skip_tokens = set(skip_tokens) if skip_tokens is not None else set() reverse = vocab_scores is not None vocab_scores = dict(vocab_scores) if reverse else vocab merges = [] for merge, piece_score in vocab_scores.items(): if merge in skip_tokens: continue local = [] for index in range(1, len(merge)): piece_l, piece_r = merge[:index], merge[index:] if piece_l in skip_tokens or piece_r in skip_tokens: continue if piece_l in vocab and piece_r in vocab: local.append((piece_l, piece_r, piece_score)) local = sorted(local, key=lambda x: (vocab[x[0]], vocab[x[1]])) merges.extend(local) merges = sorted(merges, key=lambda val: (val[2], len(val[0]), len(val[1])), reverse=reverse) merges = [(val[0], val[1]) for val in merges] return merges class SentencePieceExtractor: """ Extractor implementation for SentencePiece trained models. https://github.com/google/sentencepiece """ def __init__(self, model: str): requires_backends(self, "sentencepiece") requires_backends(self, "protobuf") # from .utils import sentencepiece_model_pb2 as model_pb2 model_pb2 = import_protobuf() m = model_pb2.ModelProto() with open(model, "rb") as f: m.ParseFromString(f.read()) self.proto = m def extract(self, model_type, **kwargs) -> tuple[dict[str, int], list[tuple]]: """ By default will return vocab and merges with respect to their order, by sending `vocab_scores` we're going to order the merges with respect to the piece scores instead. """ self.proto.trainer_spec.unk_id if model_type is None: from tokenizers.models import BPE, Unigram model_type = Unigram if self.proto.trainer_spec.model_type == 2 else BPE vocab = [(piece.piece, piece.score) for piece in self.proto.pieces] if model_type.__name__ != "BPE": kwargs["unk_id"] = self.proto.trainer_spec.unk_id kwargs["vocab"] = vocab else: from .tokenization_utils_base import generate_merges vocab = {word: i for i, (word, score) in enumerate(vocab)} merges = generate_merges(vocab) kwargs["vocab"] = vocab kwargs["merges"] = merges # control tokens are special # user defined symbols are not # both user and control tokens are AddedTokens # Add user defined symbols (type == 4) from sentencepiece (https://github.com/google/sentencepiece/blob/6225e08edb2577757163b3f5dbba4c0b670ef445/src/sentencepiece_model.proto#L299C29-L299C33) spm_added_tokens = [(id, p.piece, p.type == 3) for id, p in enumerate(self.proto.pieces) if p.type in [3, 4]] kwargs["additional_special_tokens"] = [ AddedToken(token, normalized=False, special=special) for id, token, special in sorted(spm_added_tokens, key=lambda x: x[0]) ] return kwargs class GemmaSentencePieceExtractor(SentencePieceExtractor): def extract(self, vocab_scores=None) -> tuple[dict[str, int], list[tuple]]: """ By default will return vocab and merges with respect to their order, by sending `vocab_scores` we're going to order the merges with respect to the piece scores instead. """ sp = self.sp vocab = {sp.id_to_piece(index): index for index in range(sp.GetPieceSize())} # If "\t" is missing in the vocab, we have to do this to support merges # "<0x09>" is the bytefallback for `\t` if "\t" not in vocab: vocab["\t"] = vocab.get("<0x09>") merges = generate_merges(vocab, vocab_scores) return vocab, merges def check_number_comma(piece: str) -> bool: return len(piece) < 2 or piece[-1] != "," or not piece[-2].isdigit() class Converter: def __init__(self, original_tokenizer): self.original_tokenizer = original_tokenizer def converted(self) -> Tokenizer: raise NotImplementedError() class BertConverter(Converter): def converted(self) -> Tokenizer: vocab = self.original_tokenizer.vocab tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token))) tokenize_chinese_chars = False strip_accents = False do_lower_case = False if hasattr(self.original_tokenizer, "basic_tokenizer"): tokenize_chinese_chars = self.original_tokenizer.basic_tokenizer.tokenize_chinese_chars strip_accents = self.original_tokenizer.basic_tokenizer.strip_accents do_lower_case = self.original_tokenizer.basic_tokenizer.do_lower_case tokenizer.normalizer = normalizers.BertNormalizer( clean_text=True, handle_chinese_chars=tokenize_chinese_chars, strip_accents=strip_accents, lowercase=do_lower_case, ) tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer() cls = str(self.original_tokenizer.cls_token) sep = str(self.original_tokenizer.sep_token) cls_token_id = self.original_tokenizer.cls_token_id sep_token_id = self.original_tokenizer.sep_token_id tokenizer.post_processor = processors.TemplateProcessing( single=f"{cls}:0 $A:0 {sep}:0", pair=f"{cls}:0 $A:0 {sep}:0 $B:1 {sep}:1", special_tokens=[ (cls, cls_token_id), (sep, sep_token_id), ], ) tokenizer.decoder = decoders.WordPiece(prefix="##") return tokenizer class SplinterConverter(Converter): def converted(self) -> Tokenizer: vocab = self.original_tokenizer.vocab tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token))) tokenize_chinese_chars = False strip_accents = False do_lower_case = False if hasattr(self.original_tokenizer, "basic_tokenizer"): tokenize_chinese_chars = self.original_tokenizer.basic_tokenizer.tokenize_chinese_chars strip_accents = self.original_tokenizer.basic_tokenizer.strip_accents do_lower_case = self.original_tokenizer.basic_tokenizer.do_lower_case tokenizer.normalizer = normalizers.BertNormalizer( clean_text=True, handle_chinese_chars=tokenize_chinese_chars, strip_accents=strip_accents, lowercase=do_lower_case, ) tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer() cls = str(self.original_tokenizer.cls_token) sep = str(self.original_tokenizer.sep_token) question = str(self.original_tokenizer.question_token) dot = "." cls_token_id = self.original_tokenizer.cls_token_id sep_token_id = self.original_tokenizer.sep_token_id question_token_id = self.original_tokenizer.question_token_id dot_token_id = self.original_tokenizer.convert_tokens_to_ids(".") if self.original_tokenizer.padding_side == "right": pair = f"{cls}:0 $A:0 {question} {dot} {sep}:0 $B:1 {sep}:1" else: pair = f"{cls}:0 $A:0 {sep}:0 $B:1 {question} {dot} {sep}:1" tokenizer.post_processor = processors.TemplateProcessing( single=f"{cls}:0 $A:0 {sep}:0", pair=pair, special_tokens=[ (cls, cls_token_id), (sep, sep_token_id), (question, question_token_id), (dot, dot_token_id), ], ) tokenizer.decoder = decoders.WordPiece(prefix="##") return tokenizer class FunnelConverter(Converter): def converted(self) -> Tokenizer: vocab = self.original_tokenizer.vocab tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token))) tokenize_chinese_chars = False strip_accents = False do_lower_case = False if hasattr(self.original_tokenizer, "basic_tokenizer"): tokenize_chinese_chars = self.original_tokenizer.basic_tokenizer.tokenize_chinese_chars strip_accents = self.original_tokenizer.basic_tokenizer.strip_accents do_lower_case = self.original_tokenizer.basic_tokenizer.do_lower_case tokenizer.normalizer = normalizers.BertNormalizer( clean_text=True, handle_chinese_chars=tokenize_chinese_chars, strip_accents=strip_accents, lowercase=do_lower_case, ) tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer() cls = str(self.original_tokenizer.cls_token) sep = str(self.original_tokenizer.sep_token) cls_token_id = self.original_tokenizer.cls_token_id sep_token_id = self.original_tokenizer.sep_token_id tokenizer.post_processor = processors.TemplateProcessing( single=f"{cls}:2 $A:0 {sep}:0", # token_type_id is 2 for Funnel transformer pair=f"{cls}:2 $A:0 {sep}:0 $B:1 {sep}:1", special_tokens=[ (cls, cls_token_id), (sep, sep_token_id), ], ) tokenizer.decoder = decoders.WordPiece(prefix="##") return tokenizer class MPNetConverter(Converter): def converted(self) -> Tokenizer: vocab = self.original_tokenizer.vocab tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token))) tokenize_chinese_chars = False strip_accents = False do_lower_case = False if hasattr(self.original_tokenizer, "basic_tokenizer"): tokenize_chinese_chars = self.original_tokenizer.basic_tokenizer.tokenize_chinese_chars strip_accents = self.original_tokenizer.basic_tokenizer.strip_accents do_lower_case = self.original_tokenizer.basic_tokenizer.do_lower_case tokenizer.normalizer = normalizers.BertNormalizer( clean_text=True, handle_chinese_chars=tokenize_chinese_chars, strip_accents=strip_accents, lowercase=do_lower_case, ) tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer() cls = str(self.original_tokenizer.cls_token) sep = str(self.original_tokenizer.sep_token) cls_token_id = self.original_tokenizer.cls_token_id sep_token_id = self.original_tokenizer.sep_token_id tokenizer.post_processor = processors.TemplateProcessing( single=f"{cls}:0 $A:0 {sep}:0", pair=f"{cls}:0 $A:0 {sep}:0 {sep}:0 $B:1 {sep}:1", # MPNet uses two [SEP] tokens special_tokens=[ (cls, cls_token_id), (sep, sep_token_id), ], ) tokenizer.decoder = decoders.WordPiece(prefix="##") return tokenizer class OpenAIGPTConverter(Converter): def converted(self) -> Tokenizer: vocab = self.original_tokenizer.encoder merges = list(self.original_tokenizer.bpe_ranks.keys()) unk_token = self.original_tokenizer.unk_token tokenizer = Tokenizer( BPE( vocab=vocab, merges=merges, dropout=None, unk_token=str(unk_token), end_of_word_suffix="</w>", fuse_unk=False, ) ) if tokenizer.token_to_id(str(unk_token)) is not None: tokenizer.add_special_tokens([str(unk_token)]) tokenizer.normalizer = normalizers.BertNormalizer(lowercase=True) tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer() tokenizer.decoder = decoders.BPEDecoder(suffix="</w>") return tokenizer class GPT2Converter(Converter): def converted( self, vocab: Optional[dict[str, int]] = None, merges: Optional[list[tuple[str, str]]] = None ) -> Tokenizer: if not vocab: vocab = self.original_tokenizer.encoder if not merges: merges = list(self.original_tokenizer.bpe_ranks) tokenizer = Tokenizer( BPE( vocab=vocab, merges=merges, dropout=None, continuing_subword_prefix="", end_of_word_suffix="", fuse_unk=False, ) ) add_prefix_space = getattr(self.original_tokenizer, "add_prefix_space", False) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space) tokenizer.decoder = decoders.ByteLevel() if getattr(self.original_tokenizer, "add_bos_token", False): bos = self.original_tokenizer.bos_token bos_token_id = self.original_tokenizer.bos_token_id tokenizer.post_processor = processors.TemplateProcessing( single=f"{bos}:0 $A:0", pair=f"{bos}:0 $A:0 $B:1", special_tokens=[ (bos, bos_token_id), ], ) else: # XXX trim_offsets=False actually means this post_processor doesn't # really do anything. tokenizer.post_processor = processors.ByteLevel(trim_offsets=False) return tokenizer class HerbertConverter(Converter): def converted(self) -> Tokenizer: tokenizer_info_str = "#version:" token_suffix = "</w>" vocab = self.original_tokenizer.encoder merges = list(self.original_tokenizer.bpe_ranks.keys()) if tokenizer_info_str in merges[0][0]: merges = merges[1:] tokenizer = Tokenizer( BPE( vocab, merges, dropout=None, unk_token=self.original_tokenizer.unk_token, end_of_word_suffix=token_suffix, ) ) tokenizer.normalizer = normalizers.BertNormalizer(lowercase=False, strip_accents=False) tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer() tokenizer.decoder = decoders.BPEDecoder(suffix=token_suffix) tokenizer.post_processor = processors.BertProcessing( sep=(self.original_tokenizer.sep_token, self.original_tokenizer.sep_token_id), cls=(self.original_tokenizer.cls_token, self.original_tokenizer.cls_token_id), ) return tokenizer class Qwen2Converter(Converter): def converted( self, vocab: Optional[dict[str, int]] = None, merges: Optional[list[tuple[str, str]]] = None ) -> Tokenizer: if not vocab: vocab = self.original_tokenizer.encoder if not merges: merges = list(self.original_tokenizer.bpe_ranks.keys()) tokenizer = Tokenizer( BPE( vocab=vocab, merges=merges, dropout=None, unk_token=None, continuing_subword_prefix="", end_of_word_suffix="", fuse_unk=False, byte_fallback=False, ) ) tokenizer.normalizer = normalizers.NFC() tokenizer.pre_tokenizer = pre_tokenizers.Sequence( [ pre_tokenizers.Split( Regex( r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+""" ), behavior="isolated", invert=False, ), pre_tokenizers.ByteLevel( add_prefix_space=getattr(self.original_tokenizer, "add_prefix_space", False), use_regex=False, ), ] ) tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor = processors.ByteLevel(trim_offsets=False) return tokenizer class RobertaConverter(Converter): def converted(self) -> Tokenizer: ot = self.original_tokenizer vocab = ot.encoder merges = list(ot.bpe_ranks.keys()) tokenizer = Tokenizer( BPE( vocab=vocab, merges=merges, dropout=None, continuing_subword_prefix="", end_of_word_suffix="", fuse_unk=False, ) ) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=ot.add_prefix_space) tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor = processors.RobertaProcessing( sep=(ot.sep_token, ot.sep_token_id), cls=(ot.cls_token, ot.cls_token_id), add_prefix_space=ot.add_prefix_space, trim_offsets=True, # True by default on Roberta (historical) ) return tokenizer class RoFormerConverter(Converter): def converted(self) -> Tokenizer: from .models.roformer.tokenization_utils import JiebaPreTokenizer vocab = self.original_tokenizer.vocab tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token))) strip_accents = False do_lower_case = False if hasattr(self.original_tokenizer, "basic_tokenizer"): strip_accents = self.original_tokenizer.basic_tokenizer.strip_accents do_lower_case = self.original_tokenizer.basic_tokenizer.do_lower_case tokenizer.normalizer = normalizers.BertNormalizer( clean_text=True, handle_chinese_chars=False, strip_accents=strip_accents, lowercase=do_lower_case, ) tokenizer.pre_tokenizer = pre_tokenizers.PreTokenizer.custom(JiebaPreTokenizer(vocab)) cls = str(self.original_tokenizer.cls_token) sep = str(self.original_tokenizer.sep_token) cls_token_id = self.original_tokenizer.cls_token_id sep_token_id = self.original_tokenizer.sep_token_id tokenizer.post_processor = processors.TemplateProcessing( single=f"{cls}:0 $A:0 {sep}:0", pair=f"{cls}:0 $A:0 {sep}:0 $B:1 {sep}:1", special_tokens=[ (cls, cls_token_id), (sep, sep_token_id), ], ) tokenizer.decoder = decoders.WordPiece(prefix="##") return tokenizer class DebertaConverter(Converter): def converted(self) -> Tokenizer: ot = self.original_tokenizer vocab = ot.encoder merges = list(ot.bpe_ranks.keys()) tokenizer = Tokenizer( BPE( vocab=vocab, merges=merges, dropout=None, continuing_subword_prefix="", end_of_word_suffix="", fuse_unk=False, ) ) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=ot.add_prefix_space) tokenizer.decoder = decoders.ByteLevel() tokenizer.post_processor = processors.TemplateProcessing( single="[CLS]:0 $A:0 [SEP]:0", pair="[CLS]:0 $A:0 [SEP]:0 $B:1 [SEP]:1", special_tokens=[ ("[CLS]", self.original_tokenizer.convert_tokens_to_ids("[CLS]")), ("[SEP]", self.original_tokenizer.convert_tokens_to_ids("[SEP]")), ], ) return tokenizer class SpmConverter(Converter): handle_byte_fallback = False SpmExtractor = SentencePieceExtractor special_tokens = {} @classmethod def convert_from_spm(cls, vocab=None, **kwargs): """ Hook used when converting directly from a SentencePiece model without a slow tokenizer instance. By default, return kwargs unchanged. """ if vocab is not None: kwargs["vocab"] = vocab return kwargs def __init__(self, *args): requires_backends(self, "protobuf") super().__init__(*args) # from .utils import sentencepiece_model_pb2 as model_pb2 model_pb2 = import_protobuf() m = model_pb2.ModelProto() with open(self.original_tokenizer.vocab_file, "rb") as f: m.ParseFromString(f.read()) self.proto = m if self.proto.trainer_spec.byte_fallback and not self.handle_byte_fallback: warnings.warn( "The sentencepiece tokenizer that you are converting to a fast tokenizer uses the byte fallback option" " which is not implemented in the fast tokenizers. In practice this means that the fast version of the" " tokenizer can produce unknown tokens whereas the sentencepiece version would have converted these " "unknown tokens into a sequence of byte tokens matching the original piece of text." ) def vocab(self, proto): return [(piece.piece, piece.score) for piece in proto.pieces] def unk_id(self, proto): return proto.trainer_spec.unk_id def tokenizer(self, proto): model_type = proto.trainer_spec.model_type vocab_scores = self.vocab(proto) if model_type == 1: tokenizer = Tokenizer( Unigram( vocab_scores, unk_id=self.unk_id(proto), byte_fallback=self.handle_byte_fallback, ) ) elif model_type == 2: _, merges = self.SpmExtractor(self.original_tokenizer.vocab_file).extract(vocab_scores) bpe_vocab = {word: i for i, (word, score) in enumerate(vocab_scores)} tokenizer = Tokenizer( BPE( bpe_vocab, merges, unk_token=proto.trainer_spec.unk_piece, fuse_unk=True, byte_fallback=self.handle_byte_fallback, dropout=None, ) ) else: raise Exception( "You're trying to run a `Unigram` model but you're file was trained with a different algorithm" ) # control tokens are special # user defined symbols are not # both user and control tokens are AddedTokens # Add user defined symbols (type == 4) from sentencepiece (https://github.com/google/sentencepiece/blob/6225e08edb2577757163b3f5dbba4c0b670ef445/src/sentencepiece_model.proto#L299C29-L299C33) spm_added_tokens = [ (id, p.piece, p.type == 3 or p.piece in self.special_tokens) for id, p in enumerate(proto.pieces) if p.type in [3, 4] ] tokenizer.add_tokens( [ AddedToken(token, normalized=False, special=special) for id, token, special in sorted(spm_added_tokens, key=lambda x: x[0]) ] ) return tokenizer def normalizer(self, proto): precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap _normalizers = [ normalizers.Strip(left=False, right=True), # stripping is important normalizers.Replace(Regex(" {2,}"), "▁"), ] if not precompiled_charsmap: return normalizers.Sequence(_normalizers) else: return normalizers.Sequence([normalizers.Precompiled(precompiled_charsmap)] + _normalizers) def pre_tokenizer(self, replacement, add_prefix_space): prepend_scheme = _get_prepend_scheme(add_prefix_space, self.original_tokenizer) return pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) def post_processor(self): return None def decoder(self, replacement, add_prefix_space): prepend_scheme = _get_prepend_scheme(add_prefix_space, self.original_tokenizer) return decoders.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) def converted(self) -> Tokenizer: tokenizer = self.tokenizer(self.proto) # Tokenizer assemble normalizer = self.normalizer(self.proto) if normalizer is not None: tokenizer.normalizer = normalizer replacement = "▁" add_prefix_space = True if hasattr(self.original_tokenizer, "add_prefix_space"): add_prefix_space = self.original_tokenizer.add_prefix_space pre_tokenizer = self.pre_tokenizer(replacement, add_prefix_space) if pre_tokenizer is not None: tokenizer.pre_tokenizer = pre_tokenizer tokenizer.decoder = self.decoder(replacement, add_prefix_space) post_processor = self.post_processor() if post_processor: tokenizer.post_processor = post_processor return tokenizer class AlbertConverter(SpmConverter): def vocab(self, proto): return [ (piece.piece, piece.score) if check_number_comma(piece.piece) else (piece.piece, piece.score - 100) for piece in proto.pieces ] def normalizer(self, proto): list_normalizers = [ normalizers.Replace("``", '"'), normalizers.Replace("''", '"'), ] if not self.original_tokenizer.keep_accents: list_normalizers.append(normalizers.NFKD()) list_normalizers.append(normalizers.StripAccents()) if self.original_tokenizer.do_lower_case: list_normalizers.append(normalizers.Lowercase()) precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap if precompiled_charsmap: list_normalizers.append(normalizers.Precompiled(precompiled_charsmap)) list_normalizers.append(normalizers.Replace(Regex(" {2,}"), " ")) return normalizers.Sequence(list_normalizers) def post_processor(self): return processors.TemplateProcessing( single="[CLS]:0 $A:0 [SEP]:0", pair="[CLS]:0 $A:0 [SEP]:0 $B:1 [SEP]:1", special_tokens=[ ("[CLS]", self.original_tokenizer.convert_tokens_to_ids("[CLS]")), ("[SEP]", self.original_tokenizer.convert_tokens_to_ids("[SEP]")), ], ) class BarthezConverter(SpmConverter): def unk_id(self, proto): unk_id = 3 return unk_id def post_processor(self): return processors.TemplateProcessing( single="<s> $A </s>", pair="<s> $A </s> </s> $B </s>", special_tokens=[ ("<s>", self.original_tokenizer.convert_tokens_to_ids("<s>")), ("</s>", self.original_tokenizer.convert_tokens_to_ids("</s>")), ], ) class CamembertConverter(SpmConverter): def vocab(self, proto): vocab = [ ("<s>NOTUSED", 0.0), ("<pad>", 0.0), ("</s>NOTUSED", 0.0), ("<unk>", 0.0), ("<unk>NOTUSED", -100), ] # We down-grade the original SentencePiece by -100 to avoid using it and use our added token instead vocab += [(piece.piece, piece.score) for piece in proto.pieces[1:]] vocab += [("<mask>", 0.0)] return vocab def unk_id(self, proto): # See vocab unk position return 3 def post_processor(self): return processors.TemplateProcessing( single="<s> $A </s>", pair="<s> $A </s> </s> $B </s>", special_tokens=[ ("<s>", self.original_tokenizer.convert_tokens_to_ids("<s>")), ("</s>", self.original_tokenizer.convert_tokens_to_ids("</s>")), ], ) @classmethod def convert_from_spm(cls, vocab=None, **kwargs): pad_token = str(kwargs.get("pad_token", "<pad>")) unk_token = str(kwargs.get("unk_token", "<unk>")) mask_token = str(kwargs.get("mask_token", "<mask>")) vocab_list = [ ("<s>NOTUSED", 0.0), (pad_token, 0.0), ("</s>NOTUSED", 0.0), (unk_token, 0.0), ("<unk>NOTUSED", -100.0), ] if vocab is not None: vocab_list.extend(list(vocab)[1:]) vocab_list.append((mask_token, 0.0)) kwargs["vocab"] = vocab_list return kwargs class DebertaV2Converter(SpmConverter): def pre_tokenizer(self, replacement, add_prefix_space): list_pretokenizers = [] if self.original_tokenizer.split_by_punct: list_pretokenizers.append(pre_tokenizers.Punctuation(behavior="isolated")) prepend_scheme = _get_prepend_scheme(add_prefix_space, self.original_tokenizer) list_pretokenizers.append(pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme)) return pre_tokenizers.Sequence(list_pretokenizers) def normalizer(self, proto): list_normalizers = [] if self.original_tokenizer.do_lower_case: list_normalizers.append(normalizers.Lowercase()) list_normalizers.append(normalizers.Strip()) precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap if precompiled_charsmap: list_normalizers.append(normalizers.Precompiled(precompiled_charsmap)) list_normalizers.append(normalizers.Replace(Regex(" {2,}"), " ")) return normalizers.Sequence(list_normalizers) def post_processor(self): return processors.TemplateProcessing( single="[CLS]:0 $A:0 [SEP]:0", pair="[CLS]:0 $A:0 [SEP]:0 $B:1 [SEP]:1", special_tokens=[ ("[CLS]", self.original_tokenizer.convert_tokens_to_ids("[CLS]")),
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/modeling_layers.py
src/transformers/modeling_layers.py
# Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from functools import partial from typing import Optional import torch import torch.nn as nn from .cache_utils import Cache from .modeling_outputs import ( BaseModelOutputWithPast, QuestionAnsweringModelOutput, SequenceClassifierOutputWithPast, TokenClassifierOutput, ) from .models.auto import AutoModel from .processing_utils import Unpack from .utils import TransformersKwargs, auto_docstring, can_return_tuple, logging logger = logging.get_logger(__name__) class GradientCheckpointingLayer(nn.Module): """Base class for layers with gradient checkpointing. This class enables gradient checkpointing functionality for a layer. By default, gradient checkpointing is disabled (`gradient_checkpointing = False`). When `model.set_gradient_checkpointing()` is called, gradient checkpointing is enabled by setting `gradient_checkpointing = True` and assigning a checkpointing function to `_gradient_checkpointing_func`. Important: When using gradient checkpointing with `use_reentrant=True`, inputs that require gradients (e.g. hidden states) must be passed as positional arguments (`*args`) rather than keyword arguments to properly propagate gradients. Example: ```python >>> # Correct - hidden_states passed as positional arg >>> out = self.layer(hidden_states, attention_mask=attention_mask) >>> # Incorrect - hidden_states passed as keyword arg >>> out = self.layer(hidden_states=hidden_states, attention_mask=attention_mask) ``` """ gradient_checkpointing = False def __call__(self, *args, **kwargs): if self.gradient_checkpointing and self.training: do_warn = False layer_name = self.__class__.__name__ message = f"Caching is incompatible with gradient checkpointing in {layer_name}. Setting" if "use_cache" in kwargs and kwargs["use_cache"]: kwargs["use_cache"] = False message += " `use_cache=False`," do_warn = True # different names for the same thing in different layers # TODO cyril: this one without `S` can be removed after deprection cycle if "past_key_value" in kwargs and kwargs["past_key_value"] is not None: kwargs["past_key_value"] = None message += " `past_key_value=None`," do_warn = True if "past_key_values" in kwargs and kwargs["past_key_values"] is not None: kwargs["past_key_values"] = None message += " `past_key_values=None`," do_warn = True if "layer_past" in kwargs and kwargs["layer_past"] is not None: kwargs["layer_past"] = None message += " `layer_past=None`," do_warn = True # warn if anything was changed if do_warn: message = message.rstrip(",") + "." logger.warning_once(message) return self._gradient_checkpointing_func(partial(super().__call__, **kwargs), *args) return super().__call__(*args, **kwargs) @auto_docstring class GenericForSequenceClassification: base_model_prefix = "model" def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels # Similar to `self.model = AutoModel.from_config(config)` but allows to change the base model name if needed in the child class setattr(self, self.base_model_prefix, AutoModel.from_config(config)) self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, **kwargs: Unpack[TransformersKwargs], ) -> SequenceClassifierOutputWithPast: transformer_outputs: BaseModelOutputWithPast = getattr(self, self.base_model_prefix)( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, **kwargs, ) hidden_states = transformer_outputs.last_hidden_state logits = self.score(hidden_states) if input_ids is not None: batch_size = input_ids.shape[0] else: batch_size = inputs_embeds.shape[0] if self.config.pad_token_id is None and batch_size != 1: raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") if self.config.pad_token_id is None: last_non_pad_token = -1 elif input_ids is not None: # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32) token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32) last_non_pad_token = (token_indices * non_pad_mask).argmax(-1) else: last_non_pad_token = -1 logger.warning_once( f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " "unexpected if using padding tokens in conjunction with `inputs_embeds.`" ) pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token] loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config) return SequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) @auto_docstring class GenericForQuestionAnswering: base_model_prefix = "model" def __init__(self, config): super().__init__(config) # Similar to `self.model = AutoModel.from_config(config)` but allows to change the base model name if needed in the child class setattr(self, self.base_model_prefix, AutoModel.from_config(config)) self.qa_outputs = nn.Linear(config.hidden_size, 2) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return getattr(self, self.base_model_prefix).embed_tokens def set_input_embeddings(self, value): getattr(self, self.base_model_prefix).embed_tokens = value @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, start_positions: Optional[torch.LongTensor] = None, end_positions: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> QuestionAnsweringModelOutput: outputs: BaseModelOutputWithPast = getattr(self, self.base_model_prefix)( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs, ) sequence_output = outputs.last_hidden_state logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1).contiguous() end_logits = end_logits.squeeze(-1).contiguous() loss = None if start_positions is not None and end_positions is not None: loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs) return QuestionAnsweringModelOutput( loss=loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @auto_docstring class GenericForTokenClassification: base_model_prefix = "model" def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels # Similar to `self.model = AutoModel.from_config(config)` but allows to change the base model name if needed in the child class setattr(self, self.base_model_prefix, AutoModel.from_config(config)) if getattr(config, "classifier_dropout", None) is not None: classifier_dropout = config.classifier_dropout elif getattr(config, "hidden_dropout", None) is not None: classifier_dropout = config.hidden_dropout else: classifier_dropout = 0.1 self.dropout = nn.Dropout(classifier_dropout) self.score = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, **kwargs: Unpack[TransformersKwargs], ) -> TokenClassifierOutput: outputs: BaseModelOutputWithPast = getattr(self, self.base_model_prefix)( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, **kwargs, ) sequence_output = outputs.last_hidden_state sequence_output = self.dropout(sequence_output) logits = self.score(sequence_output) loss = None if labels is not None: loss = self.loss_function(logits, labels, self.config) return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/image_utils.py
src/transformers/image_utils.py
# Copyright 2021 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import base64 import os from collections.abc import Iterable from dataclasses import dataclass from io import BytesIO from typing import Optional, Union import httpx import numpy as np from .utils import ( ExplicitEnum, is_numpy_array, is_torch_available, is_torch_tensor, is_torchvision_available, is_vision_available, logging, requires_backends, to_numpy, ) from .utils.constants import ( # noqa: F401 IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ) if is_vision_available(): import PIL.Image import PIL.ImageOps PILImageResampling = PIL.Image.Resampling if is_torchvision_available(): from torchvision.transforms import InterpolationMode pil_torch_interpolation_mapping = { PILImageResampling.NEAREST: InterpolationMode.NEAREST_EXACT, PILImageResampling.BOX: InterpolationMode.BOX, PILImageResampling.BILINEAR: InterpolationMode.BILINEAR, PILImageResampling.HAMMING: InterpolationMode.HAMMING, PILImageResampling.BICUBIC: InterpolationMode.BICUBIC, PILImageResampling.LANCZOS: InterpolationMode.LANCZOS, } else: pil_torch_interpolation_mapping = {} if is_torch_available(): import torch logger = logging.get_logger(__name__) ImageInput = Union[ "PIL.Image.Image", np.ndarray, "torch.Tensor", list["PIL.Image.Image"], list[np.ndarray], list["torch.Tensor"] ] class ChannelDimension(ExplicitEnum): FIRST = "channels_first" LAST = "channels_last" class AnnotationFormat(ExplicitEnum): COCO_DETECTION = "coco_detection" COCO_PANOPTIC = "coco_panoptic" class AnnotionFormat(ExplicitEnum): COCO_DETECTION = AnnotationFormat.COCO_DETECTION.value COCO_PANOPTIC = AnnotationFormat.COCO_PANOPTIC.value AnnotationType = dict[str, Union[int, str, list[dict]]] def is_pil_image(img): return is_vision_available() and isinstance(img, PIL.Image.Image) class ImageType(ExplicitEnum): PIL = "pillow" TORCH = "torch" NUMPY = "numpy" def get_image_type(image): if is_pil_image(image): return ImageType.PIL if is_torch_tensor(image): return ImageType.TORCH if is_numpy_array(image): return ImageType.NUMPY raise ValueError(f"Unrecognized image type {type(image)}") def is_valid_image(img): return is_pil_image(img) or is_numpy_array(img) or is_torch_tensor(img) def is_valid_list_of_images(images: list): return images and all(is_valid_image(image) for image in images) def concatenate_list(input_list): if isinstance(input_list[0], list): return [item for sublist in input_list for item in sublist] elif isinstance(input_list[0], np.ndarray): return np.concatenate(input_list, axis=0) elif isinstance(input_list[0], torch.Tensor): return torch.cat(input_list, dim=0) def valid_images(imgs): # If we have an list of images, make sure every image is valid if isinstance(imgs, (list, tuple)): for img in imgs: if not valid_images(img): return False # If not a list of tuple, we have been given a single image or batched tensor of images elif not is_valid_image(imgs): return False return True def is_batched(img): if isinstance(img, (list, tuple)): return is_valid_image(img[0]) return False def is_scaled_image(image: np.ndarray) -> bool: """ Checks to see whether the pixel values have already been rescaled to [0, 1]. """ if image.dtype == np.uint8: return False # It's possible the image has pixel values in [0, 255] but is of floating type return np.min(image) >= 0 and np.max(image) <= 1 def make_list_of_images(images, expected_ndims: int = 3) -> list[ImageInput]: """ Ensure that the output is a list of images. If the input is a single image, it is converted to a list of length 1. If the input is a batch of images, it is converted to a list of images. Args: images (`ImageInput`): Image of images to turn into a list of images. expected_ndims (`int`, *optional*, defaults to 3): Expected number of dimensions for a single input image. If the input image has a different number of dimensions, an error is raised. """ if is_batched(images): return images # Either the input is a single image, in which case we create a list of length 1 if is_pil_image(images): # PIL images are never batched return [images] if is_valid_image(images): if images.ndim == expected_ndims + 1: # Batch of images images = list(images) elif images.ndim == expected_ndims: # Single image images = [images] else: raise ValueError( f"Invalid image shape. Expected either {expected_ndims + 1} or {expected_ndims} dimensions, but got" f" {images.ndim} dimensions." ) return images raise ValueError( f"Invalid image type. Expected either PIL.Image.Image, numpy.ndarray, or torch.Tensor, but got {type(images)}." ) def make_flat_list_of_images( images: Union[list[ImageInput], ImageInput], expected_ndims: int = 3, ) -> ImageInput: """ Ensure that the output is a flat list of images. If the input is a single image, it is converted to a list of length 1. If the input is a nested list of images, it is converted to a flat list of images. Args: images (`Union[list[ImageInput], ImageInput]`): The input image. expected_ndims (`int`, *optional*, defaults to 3): The expected number of dimensions for a single input image. Returns: list: A list of images or a 4d array of images. """ # If the input is a nested list of images, we flatten it if ( isinstance(images, (list, tuple)) and all(isinstance(images_i, (list, tuple)) for images_i in images) and all(is_valid_list_of_images(images_i) or not images_i for images_i in images) ): return [img for img_list in images for img in img_list] if isinstance(images, (list, tuple)) and is_valid_list_of_images(images): if is_pil_image(images[0]) or images[0].ndim == expected_ndims: return images if images[0].ndim == expected_ndims + 1: return [img for img_list in images for img in img_list] if is_valid_image(images): if is_pil_image(images) or images.ndim == expected_ndims: return [images] if images.ndim == expected_ndims + 1: return list(images) raise ValueError(f"Could not make a flat list of images from {images}") def make_nested_list_of_images( images: Union[list[ImageInput], ImageInput], expected_ndims: int = 3, ) -> list[ImageInput]: """ Ensure that the output is a nested list of images. Args: images (`Union[list[ImageInput], ImageInput]`): The input image. expected_ndims (`int`, *optional*, defaults to 3): The expected number of dimensions for a single input image. Returns: list: A list of list of images or a list of 4d array of images. """ # If it's a list of batches, it's already in the right format if ( isinstance(images, (list, tuple)) and all(isinstance(images_i, (list, tuple)) for images_i in images) and all(is_valid_list_of_images(images_i) or not images_i for images_i in images) ): return images # If it's a list of images, it's a single batch, so convert it to a list of lists if isinstance(images, (list, tuple)) and is_valid_list_of_images(images): if is_pil_image(images[0]) or images[0].ndim == expected_ndims: return [images] if images[0].ndim == expected_ndims + 1: return [list(image) for image in images] # If it's a single image, convert it to a list of lists if is_valid_image(images): if is_pil_image(images) or images.ndim == expected_ndims: return [[images]] if images.ndim == expected_ndims + 1: return [list(images)] raise ValueError("Invalid input type. Must be a single image, a list of images, or a list of batches of images.") def to_numpy_array(img) -> np.ndarray: if not is_valid_image(img): raise ValueError(f"Invalid image type: {type(img)}") if is_vision_available() and isinstance(img, PIL.Image.Image): return np.array(img) return to_numpy(img) def infer_channel_dimension_format( image: np.ndarray, num_channels: Optional[Union[int, tuple[int, ...]]] = None ) -> ChannelDimension: """ Infers the channel dimension format of `image`. Args: image (`np.ndarray`): The image to infer the channel dimension of. num_channels (`int` or `tuple[int, ...]`, *optional*, defaults to `(1, 3)`): The number of channels of the image. Returns: The channel dimension of the image. """ num_channels = num_channels if num_channels is not None else (1, 3) num_channels = (num_channels,) if isinstance(num_channels, int) else num_channels if image.ndim == 3: first_dim, last_dim = 0, 2 elif image.ndim == 4: first_dim, last_dim = 1, 3 elif image.ndim == 5: first_dim, last_dim = 2, 4 else: raise ValueError(f"Unsupported number of image dimensions: {image.ndim}") if image.shape[first_dim] in num_channels and image.shape[last_dim] in num_channels: logger.warning( f"The channel dimension is ambiguous. Got image shape {image.shape}. Assuming channels are the first dimension. Use the [input_data_format](https://huggingface.co/docs/transformers/main/internal/image_processing_utils#transformers.image_transforms.rescale.input_data_format) parameter to assign the channel dimension." ) return ChannelDimension.FIRST elif image.shape[first_dim] in num_channels: return ChannelDimension.FIRST elif image.shape[last_dim] in num_channels: return ChannelDimension.LAST raise ValueError("Unable to infer channel dimension format") def get_channel_dimension_axis( image: np.ndarray, input_data_format: Optional[Union[ChannelDimension, str]] = None ) -> int: """ Returns the channel dimension axis of the image. Args: image (`np.ndarray`): The image to get the channel dimension axis of. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format of the image. If `None`, will infer the channel dimension from the image. Returns: The channel dimension axis of the image. """ if input_data_format is None: input_data_format = infer_channel_dimension_format(image) if input_data_format == ChannelDimension.FIRST: return image.ndim - 3 elif input_data_format == ChannelDimension.LAST: return image.ndim - 1 raise ValueError(f"Unsupported data format: {input_data_format}") def get_image_size(image: np.ndarray, channel_dim: Optional[ChannelDimension] = None) -> tuple[int, int]: """ Returns the (height, width) dimensions of the image. Args: image (`np.ndarray`): The image to get the dimensions of. channel_dim (`ChannelDimension`, *optional*): Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image. Returns: A tuple of the image's height and width. """ if channel_dim is None: channel_dim = infer_channel_dimension_format(image) if channel_dim == ChannelDimension.FIRST: return image.shape[-2], image.shape[-1] elif channel_dim == ChannelDimension.LAST: return image.shape[-3], image.shape[-2] else: raise ValueError(f"Unsupported data format: {channel_dim}") def get_image_size_for_max_height_width( image_size: tuple[int, int], max_height: int, max_width: int, ) -> tuple[int, int]: """ Computes the output image size given the input image and the maximum allowed height and width. Keep aspect ratio. Important, even if image_height < max_height and image_width < max_width, the image will be resized to at least one of the edges be equal to max_height or max_width. For example: - input_size: (100, 200), max_height: 50, max_width: 50 -> output_size: (25, 50) - input_size: (100, 200), max_height: 200, max_width: 500 -> output_size: (200, 400) Args: image_size (`tuple[int, int]`): The image to resize. max_height (`int`): The maximum allowed height. max_width (`int`): The maximum allowed width. """ height, width = image_size height_scale = max_height / height width_scale = max_width / width min_scale = min(height_scale, width_scale) new_height = int(height * min_scale) new_width = int(width * min_scale) return new_height, new_width def is_valid_annotation_coco_detection(annotation: dict[str, Union[list, tuple]]) -> bool: if ( isinstance(annotation, dict) and "image_id" in annotation and "annotations" in annotation and isinstance(annotation["annotations"], (list, tuple)) and ( # an image can have no annotations len(annotation["annotations"]) == 0 or isinstance(annotation["annotations"][0], dict) ) ): return True return False def is_valid_annotation_coco_panoptic(annotation: dict[str, Union[list, tuple]]) -> bool: if ( isinstance(annotation, dict) and "image_id" in annotation and "segments_info" in annotation and "file_name" in annotation and isinstance(annotation["segments_info"], (list, tuple)) and ( # an image can have no segments len(annotation["segments_info"]) == 0 or isinstance(annotation["segments_info"][0], dict) ) ): return True return False def valid_coco_detection_annotations(annotations: Iterable[dict[str, Union[list, tuple]]]) -> bool: return all(is_valid_annotation_coco_detection(ann) for ann in annotations) def valid_coco_panoptic_annotations(annotations: Iterable[dict[str, Union[list, tuple]]]) -> bool: return all(is_valid_annotation_coco_panoptic(ann) for ann in annotations) def load_image(image: Union[str, "PIL.Image.Image"], timeout: Optional[float] = None) -> "PIL.Image.Image": """ Loads `image` to a PIL Image. Args: image (`str` or `PIL.Image.Image`): The image to convert to the PIL Image format. timeout (`float`, *optional*): The timeout value in seconds for the URL request. Returns: `PIL.Image.Image`: A PIL Image. """ requires_backends(load_image, ["vision"]) if isinstance(image, str): if image.startswith("http://") or image.startswith("https://"): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png image = PIL.Image.open(BytesIO(httpx.get(image, timeout=timeout, follow_redirects=True).content)) elif os.path.isfile(image): image = PIL.Image.open(image) else: if image.startswith("data:image/"): image = image.split(",")[1] # Try to load as base64 try: b64 = base64.decodebytes(image.encode()) image = PIL.Image.open(BytesIO(b64)) except Exception as e: raise ValueError( f"Incorrect image source. Must be a valid URL starting with `http://` or `https://`, a valid path to an image file, or a base64 encoded string. Got {image}. Failed with {e}" ) elif not isinstance(image, PIL.Image.Image): raise TypeError( "Incorrect format used for image. Should be an url linking to an image, a base64 string, a local path, or a PIL image." ) image = PIL.ImageOps.exif_transpose(image) image = image.convert("RGB") return image def load_images( images: Union[list, tuple, str, "PIL.Image.Image"], timeout: Optional[float] = None ) -> Union["PIL.Image.Image", list["PIL.Image.Image"], list[list["PIL.Image.Image"]]]: """Loads images, handling different levels of nesting. Args: images: A single image, a list of images, or a list of lists of images to load. timeout: Timeout for loading images. Returns: A single image, a list of images, a list of lists of images. """ if isinstance(images, (list, tuple)): if len(images) and isinstance(images[0], (list, tuple)): return [[load_image(image, timeout=timeout) for image in image_group] for image_group in images] else: return [load_image(image, timeout=timeout) for image in images] else: return load_image(images, timeout=timeout) def validate_preprocess_arguments( do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, list[float]]] = None, image_std: Optional[Union[float, list[float]]] = None, do_pad: Optional[bool] = None, pad_size: Optional[Union[dict[str, int], int]] = None, do_center_crop: Optional[bool] = None, crop_size: Optional[dict[str, int]] = None, do_resize: Optional[bool] = None, size: Optional[dict[str, int]] = None, resample: Optional["PILImageResampling"] = None, interpolation: Optional["InterpolationMode"] = None, ): """ Checks validity of typically used arguments in an `ImageProcessor` `preprocess` method. Raises `ValueError` if arguments incompatibility is caught. Many incompatibilities are model-specific. `do_pad` sometimes needs `size_divisor`, sometimes `size_divisibility`, and sometimes `size`. New models and processors added should follow existing arguments when possible. """ if do_rescale and rescale_factor is None: raise ValueError("`rescale_factor` must be specified if `do_rescale` is `True`.") if do_pad and pad_size is None: # Processors pad images using different args depending on the model, so the below check is pointless # but we keep it for BC for now. TODO: remove in v5 # Usually padding can be called with: # - "pad_size/size" if we're padding to specific values # - "size_divisor" if we're padding to any value divisible by X # - "None" if we're padding to the maximum size image in batch raise ValueError( "Depending on the model, `size_divisor` or `pad_size` or `size` must be specified if `do_pad` is `True`." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("`image_mean` and `image_std` must both be specified if `do_normalize` is `True`.") if do_center_crop and crop_size is None: raise ValueError("`crop_size` must be specified if `do_center_crop` is `True`.") if interpolation is not None and resample is not None: raise ValueError( "Only one of `interpolation` and `resample` should be specified, depending on image processor type." ) if do_resize and not (size is not None and (resample is not None or interpolation is not None)): raise ValueError("`size` and `resample/interpolation` must be specified if `do_resize` is `True`.") class ImageFeatureExtractionMixin: """ Mixin that contain utilities for preparing image features. """ def _ensure_format_supported(self, image): if not isinstance(image, (PIL.Image.Image, np.ndarray)) and not is_torch_tensor(image): raise ValueError( f"Got type {type(image)} which is not supported, only `PIL.Image.Image`, `np.ndarray` and " "`torch.Tensor` are." ) def to_pil_image(self, image, rescale=None): """ Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if needed. Args: image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`): The image to convert to the PIL Image format. rescale (`bool`, *optional*): Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will default to `True` if the image type is a floating type, `False` otherwise. """ self._ensure_format_supported(image) if is_torch_tensor(image): image = image.numpy() if isinstance(image, np.ndarray): if rescale is None: # rescale default to the array being of floating type. rescale = isinstance(image.flat[0], np.floating) # If the channel as been moved to first dim, we put it back at the end. if image.ndim == 3 and image.shape[0] in [1, 3]: image = image.transpose(1, 2, 0) if rescale: image = image * 255 image = image.astype(np.uint8) return PIL.Image.fromarray(image) return image def convert_rgb(self, image): """ Converts `PIL.Image.Image` to RGB format. Args: image (`PIL.Image.Image`): The image to convert. """ self._ensure_format_supported(image) if not isinstance(image, PIL.Image.Image): return image return image.convert("RGB") def rescale(self, image: np.ndarray, scale: Union[float, int]) -> np.ndarray: """ Rescale a numpy image by scale amount """ self._ensure_format_supported(image) return image * scale def to_numpy_array(self, image, rescale=None, channel_first=True): """ Converts `image` to a numpy array. Optionally rescales it and puts the channel dimension as the first dimension. Args: image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`): The image to convert to a NumPy array. rescale (`bool`, *optional*): Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). Will default to `True` if the image is a PIL Image or an array/tensor of integers, `False` otherwise. channel_first (`bool`, *optional*, defaults to `True`): Whether or not to permute the dimensions of the image to put the channel dimension first. """ self._ensure_format_supported(image) if isinstance(image, PIL.Image.Image): image = np.array(image) if is_torch_tensor(image): image = image.numpy() rescale = isinstance(image.flat[0], np.integer) if rescale is None else rescale if rescale: image = self.rescale(image.astype(np.float32), 1 / 255.0) if channel_first and image.ndim == 3: image = image.transpose(2, 0, 1) return image def expand_dims(self, image): """ Expands 2-dimensional `image` to 3 dimensions. Args: image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`): The image to expand. """ self._ensure_format_supported(image) # Do nothing if PIL image if isinstance(image, PIL.Image.Image): return image if is_torch_tensor(image): image = image.unsqueeze(0) else: image = np.expand_dims(image, axis=0) return image def normalize(self, image, mean, std, rescale=False): """ Normalizes `image` with `mean` and `std`. Note that this will trigger a conversion of `image` to a NumPy array if it's a PIL Image. Args: image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`): The image to normalize. mean (`list[float]` or `np.ndarray` or `torch.Tensor`): The mean (per channel) to use for normalization. std (`list[float]` or `np.ndarray` or `torch.Tensor`): The standard deviation (per channel) to use for normalization. rescale (`bool`, *optional*, defaults to `False`): Whether or not to rescale the image to be between 0 and 1. If a PIL image is provided, scaling will happen automatically. """ self._ensure_format_supported(image) if isinstance(image, PIL.Image.Image): image = self.to_numpy_array(image, rescale=True) # If the input image is a PIL image, it automatically gets rescaled. If it's another # type it may need rescaling. elif rescale: if isinstance(image, np.ndarray): image = self.rescale(image.astype(np.float32), 1 / 255.0) elif is_torch_tensor(image): image = self.rescale(image.float(), 1 / 255.0) if isinstance(image, np.ndarray): if not isinstance(mean, np.ndarray): mean = np.array(mean).astype(image.dtype) if not isinstance(std, np.ndarray): std = np.array(std).astype(image.dtype) elif is_torch_tensor(image): import torch if not isinstance(mean, torch.Tensor): if isinstance(mean, np.ndarray): mean = torch.from_numpy(mean) else: mean = torch.tensor(mean) if not isinstance(std, torch.Tensor): if isinstance(std, np.ndarray): std = torch.from_numpy(std) else: std = torch.tensor(std) if image.ndim == 3 and image.shape[0] in [1, 3]: return (image - mean[:, None, None]) / std[:, None, None] else: return (image - mean) / std def resize(self, image, size, resample=None, default_to_square=True, max_size=None): """ Resizes `image`. Enforces conversion of input to PIL.Image. Args: image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`): The image to resize. size (`int` or `tuple[int, int]`): The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to this. If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this number. i.e, if height > width, then image will be rescaled to (size * height / width, size). resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`): The filter to user for resampling. default_to_square (`bool`, *optional*, defaults to `True`): How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square (`size`,`size`). If set to `False`, will replicate [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize) with support for resizing only the smallest edge and providing an optional `max_size`. max_size (`int`, *optional*, defaults to `None`): The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater than `max_size` after being resized according to `size`, then the image is resized again so that the longer edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter than `size`. Only used if `default_to_square` is `False`. Returns: image: A resized `PIL.Image.Image`. """ resample = resample if resample is not None else PILImageResampling.BILINEAR self._ensure_format_supported(image) if not isinstance(image, PIL.Image.Image): image = self.to_pil_image(image) if isinstance(size, list): size = tuple(size) if isinstance(size, int) or len(size) == 1: if default_to_square: size = (size, size) if isinstance(size, int) else (size[0], size[0]) else: width, height = image.size # specified size only for the smallest edge short, long = (width, height) if width <= height else (height, width) requested_new_short = size if isinstance(size, int) else size[0] if short == requested_new_short: return image new_short, new_long = requested_new_short, int(requested_new_short * long / short) if max_size is not None: if max_size <= requested_new_short: raise ValueError( f"max_size = {max_size} must be strictly greater than the requested " f"size for the smaller edge size = {size}" ) if new_long > max_size: new_short, new_long = int(max_size * new_short / new_long), max_size size = (new_short, new_long) if width <= height else (new_long, new_short) return image.resize(size, resample=resample) def center_crop(self, image, size): """ Crops `image` to the given size using a center crop. Note that if the image is too small to be cropped to the size given, it will be padded (so the returned result has the size asked). Args: image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor` of shape (n_channels, height, width) or (height, width, n_channels)): The image to resize. size (`int` or `tuple[int, int]`): The size to which crop the image. Returns: new_image: A center cropped `PIL.Image.Image` or `np.ndarray` or `torch.Tensor` of shape: (n_channels, height, width). """ self._ensure_format_supported(image) if not isinstance(size, tuple): size = (size, size) # PIL Image.size is (width, height) but NumPy array and torch Tensors have (height, width) if is_torch_tensor(image) or isinstance(image, np.ndarray): if image.ndim == 2: image = self.expand_dims(image) image_shape = image.shape[1:] if image.shape[0] in [1, 3] else image.shape[:2] else: image_shape = (image.size[1], image.size[0]) top = (image_shape[0] - size[0]) // 2 bottom = top + size[0] # In case size is odd, (image_shape[0] + size[0]) // 2 won't give the proper result. left = (image_shape[1] - size[1]) // 2 right = left + size[1] # In case size is odd, (image_shape[1] + size[1]) // 2 won't give the proper result. # For PIL Images we have a method to crop directly. if isinstance(image, PIL.Image.Image): return image.crop((left, top, right, bottom)) # Check if image is in (n_channels, height, width) or (height, width, n_channels) format channel_first = image.shape[0] in [1, 3] # Transpose (height, width, n_channels) format images if not channel_first: if isinstance(image, np.ndarray): image = image.transpose(2, 0, 1) if is_torch_tensor(image): image = image.permute(2, 0, 1) # Check if cropped area is within image boundaries
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/trainer_jit_checkpoint.py
src/transformers/trainer_jit_checkpoint.py
import os import signal import threading from typing import Optional from .trainer_callback import TrainerCallback from .trainer_utils import PREFIX_CHECKPOINT_DIR from .utils import logging logger = logging.get_logger(__name__) class CheckpointManager: def __init__(self, trainer, kill_wait: int = 3): """ Initialize the CheckpointManager for Just-In-Time checkpoint handling. Args: trainer: The Trainer instance that will be used to save checkpoints when SIGTERM is received. kill_wait (`int`, *optional*, defaults to 3): Grace period to distinguish between SIGTERM and SIGKILL. """ self.trainer = trainer self.is_checkpoint_requested = False self._original_sigterm_handler = None self.kill_wait = kill_wait def setup_signal_handler(self): self._original_sigterm_handler = signal.signal(signal.SIGTERM, self._sigterm_handler) logger.info("JIT checkpoint signal handler registered for SIGTERM") def _sigterm_handler(self, signum, frame): if self.is_checkpoint_requested: return logger.info(f"SIGTERM received, will request JIT checkpoint after {self.kill_wait}s") threading.Timer(self.kill_wait, self._enable_checkpoint).start() def _enable_checkpoint(self): logger.info("Kill wait period elapsed, requesting checkpoint") self.is_checkpoint_requested = True def execute_jit_checkpoint(self): try: # Set checkpoint flag to False to avoid multiple checkpoints getting triggered by other callbacks self.is_checkpoint_requested = False logger.info("Starting JIT checkpointing...") current_step = self.trainer.state.global_step logger.info(f"Saving JIT checkpoint at step {current_step}") output_dir = self.trainer._get_output_dir(trial=None) checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{current_step}" checkpoint_path = os.path.join(output_dir, checkpoint_folder) # Create checkpoint directory os.makedirs(checkpoint_path, exist_ok=True) # Create a sentinel file to indicate checkpointing is in progress sentinel_file = os.path.join(output_dir, checkpoint_folder, "checkpoint-is-incomplete.txt") with open(sentinel_file, "w") as f: f.write(f"Checkpoint started at step {current_step} and in progress...") logger.info(f"Created checkpoint progress sentinel marker file: {sentinel_file}") # Invoke the trainer's checkpoint method directly self.trainer._save_checkpoint(self.trainer.model, trial=None) # Remove sentinel file upon successful checkpointing if os.path.exists(sentinel_file): os.remove(sentinel_file) logger.info("Sentinel marker file removed") logger.info("Immediate JIT checkpoint completed successfully") except Exception as e: logger.error(f"Failed to save JIT checkpoint: {e}") raise class JITCheckpointCallback(TrainerCallback): """ Callback for Just-In-Time checkpointing on SIGTERM signals. When SIGTERM is received, the checkpoint manager sets `is_checkpoint_requested=True`. The callbacks detect this flag and set `control.should_training_stop=True`, which signals the Trainer's training loop to exit gracefully after saving the checkpoint. """ def __init__(self): self.trainer = None self.jit_manager: Optional[CheckpointManager] = None def set_trainer(self, trainer): self.trainer = trainer if trainer.args.enable_jit_checkpoint: self.jit_manager = CheckpointManager(trainer=trainer) self.jit_manager.setup_signal_handler() logger.info("JIT checkpointing enabled") def on_pre_optimizer_step(self, args, state, control, **kwargs): if self.jit_manager and self.jit_manager.is_checkpoint_requested: control.should_training_stop = True self.jit_manager.execute_jit_checkpoint() def on_step_begin(self, args, state, control, **kwargs): if self.jit_manager and self.jit_manager.is_checkpoint_requested: control.should_training_stop = True self.jit_manager.execute_jit_checkpoint() def on_step_end(self, args, state, control, **kwargs): if self.jit_manager and self.jit_manager.is_checkpoint_requested: control.should_save = False control.should_training_stop = True self.jit_manager.execute_jit_checkpoint() def on_epoch_end(self, args, state, control, **kwargs): if self.jit_manager and self.jit_manager.is_checkpoint_requested: control.should_save = False control.should_training_stop = True self.jit_manager.execute_jit_checkpoint() def on_train_end(self, args, state, control, **kwargs): # Restore original SIGTERM handler if self.jit_manager and self.jit_manager._original_sigterm_handler is not None: signal.signal(signal.SIGTERM, self.jit_manager._original_sigterm_handler) logger.info("Restored original SIGTERM handler after training completion")
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/optimization.py
src/transformers/optimization.py
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PyTorch optimization for BERT model.""" import math import warnings from functools import partial import torch from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR, ReduceLROnPlateau from .trainer_pt_utils import LayerWiseDummyOptimizer, LayerWiseDummyScheduler from .trainer_utils import SchedulerType from .utils import logging logger = logging.get_logger(__name__) def _get_constant_lambda(_=None): return 1 def get_constant_schedule(optimizer: Optimizer, last_epoch: int = -1): """ Create a schedule with a constant learning rate, using the learning rate set in optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. last_epoch (`int`, *optional*, defaults to -1): The index of the last epoch when resuming training. Return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. """ return LambdaLR(optimizer, _get_constant_lambda, last_epoch=last_epoch) def get_reduce_on_plateau_schedule(optimizer: Optimizer, **kwargs): """ Create a schedule with a constant learning rate that decreases when a metric has stopped improving. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. kwargs (`dict`, *optional*): Extra parameters to be passed to the scheduler. See `torch.optim.lr_scheduler.ReduceLROnPlateau` for possible parameters. Return: `torch.optim.lr_scheduler.ReduceLROnPlateau` with the appropriate schedule. """ return ReduceLROnPlateau(optimizer, **kwargs) def _get_constant_schedule_with_warmup_lr_lambda(current_step: int, *, num_warmup_steps: int): if current_step < num_warmup_steps: return float(current_step) / float(max(1.0, num_warmup_steps)) return 1.0 def get_constant_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, last_epoch: int = -1): """ Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate increases linearly between 0 and the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. num_warmup_steps (`int`): The number of steps for the warmup phase. last_epoch (`int`, *optional*, defaults to -1): The index of the last epoch when resuming training. Return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. """ lr_lambda = partial(_get_constant_schedule_with_warmup_lr_lambda, num_warmup_steps=num_warmup_steps) return LambdaLR(optimizer, lr_lambda, last_epoch=last_epoch) def _get_linear_schedule_with_warmup_lr_lambda(current_step: int, *, num_warmup_steps: int, num_training_steps: int): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) return max(0.0, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps))) def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1): """ Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. num_warmup_steps (`int`): The number of steps for the warmup phase. num_training_steps (`int`): The total number of training steps. last_epoch (`int`, *optional*, defaults to -1): The index of the last epoch when resuming training. Return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. """ lr_lambda = partial( _get_linear_schedule_with_warmup_lr_lambda, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, ) return LambdaLR(optimizer, lr_lambda, last_epoch) def _get_cosine_schedule_with_warmup_lr_lambda( current_step: int, *, num_warmup_steps: int, num_training_steps: int, num_cycles: float ): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps)) return max(0.0, 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress))) def get_cosine_schedule_with_warmup( optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float = 0.5, last_epoch: int = -1 ): """ Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. num_warmup_steps (`int`): The number of steps for the warmup phase. num_training_steps (`int`): The total number of training steps. num_cycles (`float`, *optional*, defaults to 0.5): The number of waves in the cosine schedule (the defaults is to just decrease from the max value to 0 following a half-cosine). last_epoch (`int`, *optional*, defaults to -1): The index of the last epoch when resuming training. Return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. """ lr_lambda = partial( _get_cosine_schedule_with_warmup_lr_lambda, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, num_cycles=num_cycles, ) return LambdaLR(optimizer, lr_lambda, last_epoch) def _get_cosine_with_hard_restarts_schedule_with_warmup_lr_lambda( current_step: int, *, num_warmup_steps: int, num_training_steps: int, num_cycles: int ): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps)) if progress >= 1.0: return 0.0 return max(0.0, 0.5 * (1.0 + math.cos(math.pi * ((float(num_cycles) * progress) % 1.0)))) def get_cosine_with_hard_restarts_schedule_with_warmup( optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: int = 1, last_epoch: int = -1 ): """ Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to 0, with several hard restarts, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. num_warmup_steps (`int`): The number of steps for the warmup phase. num_training_steps (`int`): The total number of training steps. num_cycles (`int`, *optional*, defaults to 1): The number of hard restarts to use. last_epoch (`int`, *optional*, defaults to -1): The index of the last epoch when resuming training. Return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. """ lr_lambda = partial( _get_cosine_with_hard_restarts_schedule_with_warmup_lr_lambda, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, num_cycles=num_cycles, ) return LambdaLR(optimizer, lr_lambda, last_epoch) def _get_polynomial_decay_schedule_with_warmup_lr_lambda( current_step: int, *, num_warmup_steps: int, num_training_steps: int, lr_end: float, power: float, lr_init: int, ): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: lr_range = lr_init - lr_end decay_steps = num_training_steps - num_warmup_steps pct_remaining = 1 - (current_step - num_warmup_steps) / decay_steps decay = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init def get_polynomial_decay_schedule_with_warmup( optimizer, num_warmup_steps, num_training_steps, lr_end=1e-7, power=1.0, last_epoch=-1 ): """ Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the optimizer to end lr defined by *lr_end*, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. num_warmup_steps (`int`): The number of steps for the warmup phase. num_training_steps (`int`): The total number of training steps. lr_end (`float`, *optional*, defaults to 1e-7): The end LR. power (`float`, *optional*, defaults to 1.0): Power factor. last_epoch (`int`, *optional*, defaults to -1): The index of the last epoch when resuming training. Note: *power* defaults to 1.0 as in the fairseq implementation, which in turn is based on the original BERT implementation at https://github.com/google-research/bert/blob/f39e881b169b9d53bea03d2d341b31707a6c052b/optimization.py#L37 Return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. """ lr_init = optimizer.defaults["lr"] if not (lr_init > lr_end): raise ValueError(f"lr_end ({lr_end}) must be smaller than initial lr ({lr_init})") lr_lambda = partial( _get_polynomial_decay_schedule_with_warmup_lr_lambda, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, lr_end=lr_end, power=power, lr_init=lr_init, ) return LambdaLR(optimizer, lr_lambda, last_epoch) def _get_inverse_sqrt_schedule_lr_lambda(current_step: int, *, num_warmup_steps: int, timescale: int | None = None): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) shift = timescale - num_warmup_steps decay = 1.0 / math.sqrt((current_step + shift) / timescale) return decay def get_inverse_sqrt_schedule( optimizer: Optimizer, num_warmup_steps: int, timescale: int | None = None, last_epoch: int = -1 ): """ Create a schedule with an inverse square-root learning rate, from the initial lr set in the optimizer, after a warmup period which increases lr linearly from 0 to the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. num_warmup_steps (`int`): The number of steps for the warmup phase. timescale (`int`, *optional*, defaults to `num_warmup_steps`): Time scale. last_epoch (`int`, *optional*, defaults to -1): The index of the last epoch when resuming training. Return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. """ # Note: this implementation is adapted from # https://github.com/google-research/big_vision/blob/f071ce68852d56099437004fd70057597a95f6ef/big_vision/utils.py#L930 if timescale is None: timescale = num_warmup_steps or 10_000 lr_lambda = partial(_get_inverse_sqrt_schedule_lr_lambda, num_warmup_steps=num_warmup_steps, timescale=timescale) return LambdaLR(optimizer, lr_lambda, last_epoch=last_epoch) def _get_cosine_schedule_with_warmup_lr_lambda( current_step: int, *, num_warmup_steps: int, num_training_steps: int, num_cycles: float, min_lr_rate: float = 0.0 ): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps)) factor = 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress)) factor = factor * (1 - min_lr_rate) + min_lr_rate return max(0, factor) def get_cosine_with_min_lr_schedule_with_warmup( optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float = 0.5, last_epoch: int = -1, min_lr: float | None = None, min_lr_rate: float | None = None, ): """ Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to min_lr, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. num_warmup_steps (`int`): The number of steps for the warmup phase. num_training_steps (`int`): The total number of training steps. num_cycles (`float`, *optional*, defaults to 0.5): The number of waves in the cosine schedule (the defaults is to just decrease from the max value to 0 following a half-cosine). last_epoch (`int`, *optional*, defaults to -1): The index of the last epoch when resuming training. min_lr (`float`, *optional*): The minimum learning rate to reach after the cosine schedule. min_lr_rate (`float`, *optional*): The minimum learning rate as a ratio of the initial learning rate. If set, `min_lr` should not be set. Return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. """ if min_lr is not None and min_lr_rate is not None: raise ValueError("Only one of min_lr or min_lr_rate should be set") elif min_lr is not None: min_lr_rate = min_lr / optimizer.defaults["lr"] elif min_lr_rate is None: raise ValueError("One of min_lr or min_lr_rate should be set through the `lr_scheduler_kwargs`") lr_lambda = partial( _get_cosine_schedule_with_warmup_lr_lambda, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, num_cycles=num_cycles, min_lr_rate=min_lr_rate, ) return LambdaLR(optimizer, lr_lambda, last_epoch) def _get_cosine_with_min_lr_schedule_with_warmup_lr_rate_lambda( current_step: int, *, num_warmup_steps: int, num_training_steps: int, num_cycles: float, min_lr_rate: float = 0.0, warmup_lr_rate: float | None = None, ): current_step = float(current_step) num_warmup_steps = float(num_warmup_steps) num_training_steps = float(num_training_steps) if current_step < num_warmup_steps: if warmup_lr_rate is None: return (current_step + 1.0) / max(1.0, num_warmup_steps) else: warmup_lr_rate = float(warmup_lr_rate) return warmup_lr_rate + (1.0 - warmup_lr_rate) * (current_step) / (max(1, num_warmup_steps - 1)) progress = (current_step - num_warmup_steps + 1.0) / (max(1.0, num_training_steps - num_warmup_steps)) factor = 0.5 * (1.0 + math.cos(math.pi * num_cycles * 2.0 * progress)) factor = factor * (1 - min_lr_rate) + min_lr_rate return max(0, factor) def get_cosine_with_min_lr_schedule_with_warmup_lr_rate( optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float = 0.5, last_epoch: int = -1, min_lr: float | None = None, min_lr_rate: float | None = None, warmup_lr_rate: float | None = None, ): """ Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to min_lr, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. num_warmup_steps (`int`): The number of steps for the warmup phase. num_training_steps (`int`): The total number of training steps. num_cycles (`float`, *optional*, defaults to 0.5): The number of waves in the cosine schedule (the defaults is to just decrease from the max value to 0 following a half-cosine). last_epoch (`int`, *optional*, defaults to -1): The index of the last epoch when resuming training. min_lr (`float`, *optional*): The minimum learning rate to reach after the cosine schedule. min_lr_rate (`float`, *optional*): The minimum learning rate as a ratio of the initial learning rate. If set, `min_lr` should not be set. warmup_lr_rate (`float`, *optional*): The minimum learning rate as a ratio of the start learning rate. If not set, `warmup_lr_rate` will be treated as float(1/num_warmup_steps). Return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. """ if min_lr is not None and min_lr_rate is not None: raise ValueError("Only one of min_lr or min_lr_rate should be set") elif min_lr is not None: min_lr_rate = min_lr / optimizer.defaults["lr"] elif min_lr_rate is None: raise ValueError("One of min_lr or min_lr_rate should be set through the `lr_scheduler_kwargs`") lr_lambda = partial( _get_cosine_with_min_lr_schedule_with_warmup_lr_rate_lambda, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, num_cycles=num_cycles, min_lr_rate=min_lr_rate, warmup_lr_rate=warmup_lr_rate, ) return LambdaLR(optimizer, lr_lambda, last_epoch) def _get_wsd_scheduler_lambda( current_step: int, *, num_warmup_steps: int, num_stable_steps: int, num_decay_steps: int, warmup_type: str, decay_type: str, min_lr_ratio: float, num_cycles: float, ): if current_step < num_warmup_steps: progress = float(current_step) / float(max(1, num_warmup_steps)) if warmup_type == "linear": factor = progress elif warmup_type == "cosine": factor = 0.5 * (1.0 - math.cos(math.pi * progress)) elif warmup_type == "1-sqrt": factor = 1.0 - math.sqrt(1.0 - progress) factor = factor * (1.0 - min_lr_ratio) + min_lr_ratio return max(0.0, factor) if current_step < num_warmup_steps + num_stable_steps: return 1.0 if current_step < num_warmup_steps + num_stable_steps + num_decay_steps: progress = float(current_step - num_warmup_steps - num_stable_steps) / float(max(1, num_decay_steps)) if decay_type == "linear": factor = 1.0 - progress elif decay_type == "cosine": factor = 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress)) elif decay_type == "1-sqrt": factor = 1.0 - math.sqrt(progress) factor = factor * (1.0 - min_lr_ratio) + min_lr_ratio return max(0.0, factor) return min_lr_ratio def get_wsd_schedule( optimizer: Optimizer, num_warmup_steps: int, num_decay_steps: int, num_training_steps: int | None = None, num_stable_steps: int | None = None, warmup_type: str = "linear", decay_type: str = "cosine", min_lr_ratio: float = 0, num_cycles: float = 0.5, last_epoch: int = -1, ): """ Create a schedule with a learning rate that has three stages: 1. warmup: increase from min_lr_ratio times the initial learning rate to the initial learning rate following a warmup_type. 2. stable: constant learning rate. 3. decay: decrease from the initial learning rate to min_lr_ratio times the initial learning rate following a decay_type. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. num_warmup_steps (`int`): The number of steps for the warmup phase. num_decay_steps (`int`): The number of steps for the decay phase. num_training_steps (`int`, *optional*): The total number of training steps. This is the sum of the warmup, stable and decay steps. If `num_stable_steps` is not provided, the stable phase will be `num_training_steps - num_warmup_steps - num_decay_steps`. num_stable_steps (`int`, *optional*): The number of steps for the stable phase. Please ensure that `num_warmup_steps + num_stable_steps + num_decay_steps` equals `num_training_steps`, otherwise the other steps will default to the minimum learning rate. warmup_type (`str`, *optional*, defaults to "linear"): The type of warmup to use. Can be 'linear', 'cosine' or '1-sqrt'. decay_type (`str`, *optional*, defaults to "cosine"): The type of decay to use. Can be 'linear', 'cosine' or '1-sqrt'. min_lr_ratio (`float`, *optional*, defaults to 0): The minimum learning rate as a ratio of the initial learning rate. num_cycles (`float`, *optional*, defaults to 0.5): The number of waves in the cosine schedule (the defaults is to just decrease from the max value to 0 following a half-cosine). last_epoch (`int`, *optional*, defaults to -1): The index of the last epoch when resuming training. Return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. """ if num_training_steps is None and num_stable_steps is None: raise ValueError("Either num_training_steps or num_stable_steps must be specified.") if num_training_steps is not None and num_stable_steps is not None: warnings.warn("Both num_training_steps and num_stable_steps are specified. num_stable_steps will be used.") if warmup_type not in ["linear", "cosine", "1-sqrt"]: raise ValueError(f"Unknown warmup type: {warmup_type}, expected 'linear', 'cosine' or '1-sqrt'") if decay_type not in ["linear", "cosine", "1-sqrt"]: raise ValueError(f"Unknown decay type: {decay_type}, expected 'linear', 'cosine' or '1-sqrt'") if num_stable_steps is None: num_stable_steps = num_training_steps - num_warmup_steps - num_decay_steps lr_lambda = partial( _get_wsd_scheduler_lambda, num_warmup_steps=num_warmup_steps, num_stable_steps=num_stable_steps, num_decay_steps=num_decay_steps, warmup_type=warmup_type, decay_type=decay_type, min_lr_ratio=min_lr_ratio, num_cycles=num_cycles, ) return LambdaLR(optimizer, lr_lambda, last_epoch) TYPE_TO_SCHEDULER_FUNCTION = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.INVERSE_SQRT: get_inverse_sqrt_schedule, SchedulerType.REDUCE_ON_PLATEAU: get_reduce_on_plateau_schedule, SchedulerType.COSINE_WITH_MIN_LR: get_cosine_with_min_lr_schedule_with_warmup, SchedulerType.COSINE_WARMUP_WITH_MIN_LR: get_cosine_with_min_lr_schedule_with_warmup_lr_rate, SchedulerType.WARMUP_STABLE_DECAY: get_wsd_schedule, } def get_scheduler( name: str | SchedulerType, optimizer: Optimizer, num_warmup_steps: int | None = None, num_training_steps: int | None = None, scheduler_specific_kwargs: dict | None = None, ): """ Unified API to get any scheduler from its name. Args: name (`str` or `SchedulerType`): The name of the scheduler to use. optimizer (`torch.optim.Optimizer`): The optimizer that will be used during training. num_warmup_steps (`int`, *optional*): The number of warmup steps to do. This is not required by all schedulers (hence the argument being optional), the function will raise an error if it's unset and the scheduler type requires it. num_training_steps (`int``, *optional*): The number of training steps to do. This is not required by all schedulers (hence the argument being optional), the function will raise an error if it's unset and the scheduler type requires it. scheduler_specific_kwargs (`dict`, *optional*): Extra parameters for schedulers such as cosine with restarts. Mismatched scheduler types and scheduler parameters will cause the scheduler function to raise a TypeError. """ name = SchedulerType(name) schedule_func = TYPE_TO_SCHEDULER_FUNCTION[name] # If a `LayerWiseDummyOptimizer` is passed we extract the optimizer dict and # recursively call `get_scheduler` to get the proper schedulers on each parameter if optimizer is not None and isinstance(optimizer, LayerWiseDummyOptimizer): optimizer_dict = optimizer.optimizer_dict scheduler_dict = {} for param in optimizer_dict: scheduler_dict[param] = get_scheduler( name, optimizer=optimizer_dict[param], num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, scheduler_specific_kwargs=scheduler_specific_kwargs, ) def scheduler_hook(param): # Since the optimizer hook has been already attached we only need to # attach the scheduler hook, the gradients have been zeroed here scheduler_dict[param].step() for param in optimizer_dict: if param.requires_grad: param.register_post_accumulate_grad_hook(scheduler_hook) return LayerWiseDummyScheduler(optimizer_dict=optimizer_dict, lr=optimizer.defaults["lr"]) if name == SchedulerType.CONSTANT: return schedule_func(optimizer) if scheduler_specific_kwargs is None: scheduler_specific_kwargs = {} if name == SchedulerType.REDUCE_ON_PLATEAU: return schedule_func(optimizer, **scheduler_specific_kwargs) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(f"{name} requires `num_warmup_steps`, please provide that argument.") if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(optimizer, num_warmup_steps=num_warmup_steps) if name == SchedulerType.INVERSE_SQRT: return schedule_func(optimizer, num_warmup_steps=num_warmup_steps) # wsd scheduler requires either num_training_steps or num_stable_steps if name == SchedulerType.WARMUP_STABLE_DECAY: return schedule_func( optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, **scheduler_specific_kwargs, ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(f"{name} requires `num_training_steps`, please provide that argument.") return schedule_func( optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, **scheduler_specific_kwargs, ) class Adafactor(Optimizer): """ AdaFactor pytorch implementation can be used as a drop in replacement for Adam original fairseq code: https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py Paper: *Adafactor: Adaptive Learning Rates with Sublinear Memory Cost* https://huggingface.co/papers/1804.04235 Note that this optimizer internally adjusts the learning rate depending on the `scale_parameter`, `relative_step` and `warmup_init` options. To use a manual (external) learning rate schedule you should set `scale_parameter=False` and `relative_step=False`. Arguments: params (`Iterable[nn.parameter.Parameter]`): Iterable of parameters to optimize or dictionaries defining parameter groups. lr (`float`, *optional*): The external learning rate. eps (`tuple[float, float]`, *optional*, defaults to `(1e-30, 0.001)`): Regularization constants for square gradient and parameter scale respectively clip_threshold (`float`, *optional*, defaults to 1.0): Threshold of root mean square of final gradient update decay_rate (`float`, *optional*, defaults to -0.8): Coefficient used to compute running averages of square beta1 (`float`, *optional*): Coefficient used for computing running averages of gradient weight_decay (`float`, *optional*, defaults to 0.0): Weight decay (L2 penalty) scale_parameter (`bool`, *optional*, defaults to `True`): If True, learning rate is scaled by root mean square relative_step (`bool`, *optional*, defaults to `True`): If True, time-dependent learning rate is computed instead of external learning rate warmup_init (`bool`, *optional*, defaults to `False`): Time-dependent learning rate computation depends on whether warm-up initialization is being used This implementation handles low-precision (FP16, bfloat) values, but we have not thoroughly tested. Recommended T5 finetuning settings (https://discuss.huggingface.co/t/t5-finetuning-tips/684/3): - Training without LR warmup or clip_threshold is not recommended. - use scheduled LR warm-up to fixed LR - use clip_threshold=1.0 (https://huggingface.co/papers/1804.04235) - Disable relative updates - Use scale_parameter=False - Additional optimizer operations like gradient clipping should not be used alongside Adafactor Example: ```python Adafactor(model.parameters(), scale_parameter=False, relative_step=False, warmup_init=False, lr=1e-3) ``` Others reported the following combination to work well: ```python Adafactor(model.parameters(), scale_parameter=True, relative_step=True, warmup_init=True, lr=None) ``` When using `lr=None` with [`Trainer`] you will most likely need to use [`~optimization.AdafactorSchedule`] scheduler as following: ```python from transformers.optimization import Adafactor, AdafactorSchedule optimizer = Adafactor(model.parameters(), scale_parameter=True, relative_step=True, warmup_init=True, lr=None) lr_scheduler = AdafactorSchedule(optimizer) trainer = Trainer(..., optimizers=(optimizer, lr_scheduler)) ``` Usage: ```python # replace AdamW with Adafactor optimizer = Adafactor( model.parameters(), lr=1e-3, eps=(1e-30, 1e-3), clip_threshold=1.0, decay_rate=-0.8, beta1=None, weight_decay=0.0, relative_step=False, scale_parameter=False, warmup_init=False, ) ```""" def __init__( self, params, lr=None, eps=(1e-30, 1e-3), clip_threshold=1.0, decay_rate=-0.8, beta1=None, weight_decay=0.0, scale_parameter=True, relative_step=True, warmup_init=False, ): if lr is not None and relative_step:
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/debug_utils.py
src/transformers/debug_utils.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections from .utils import ExplicitEnum, is_torch_available, logging if is_torch_available(): import torch logger = logging.get_logger(__name__) class DebugUnderflowOverflow: """ This debug class helps detect and understand where the model starts getting very large or very small, and more importantly `nan` or `inf` weight and activation elements. There are 2 working modes: 1. Underflow/overflow detection (default) 2. Specific batch absolute min/max tracing without detection Mode 1: Underflow/overflow detection To activate the underflow/overflow detection, initialize the object with the model : ```python debug_overflow = DebugUnderflowOverflow(model) ``` then run the training as normal and if `nan` or `inf` gets detected in at least one of the weight, input or output elements this module will throw an exception and will print `max_frames_to_save` frames that lead to this event, each frame reporting 1. the fully qualified module name plus the class name whose `forward` was run 2. the absolute min and max value of all elements for each module weights, and the inputs and output For example, here is the header and the last few frames in detection report for `google/mt5-small` run in fp16 mixed precision : ``` Detected inf/nan during batch_number=0 Last 21 forward frames: abs min abs max metadata [...] encoder.block.2.layer.1.DenseReluDense.wi_0 Linear 2.17e-07 4.50e+00 weight 1.79e-06 4.65e+00 input[0] 2.68e-06 3.70e+01 output encoder.block.2.layer.1.DenseReluDense.wi_1 Linear 8.08e-07 2.66e+01 weight 1.79e-06 4.65e+00 input[0] 1.27e-04 2.37e+02 output encoder.block.2.layer.1.DenseReluDense.wo Linear 1.01e-06 6.44e+00 weight 0.00e+00 9.74e+03 input[0] 3.18e-04 6.27e+04 output encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense 1.79e-06 4.65e+00 input[0] 3.18e-04 6.27e+04 output encoder.block.2.layer.1.dropout Dropout 3.18e-04 6.27e+04 input[0] 0.00e+00 inf output ``` You can see here, that `T5DenseGatedGeluDense.forward` resulted in output activations, whose absolute max value was around 62.7K, which is very close to fp16's top limit of 64K. In the next frame we have `Dropout` which renormalizes the weights, after it zeroed some of the elements, which pushes the absolute max value to more than 64K, and we get an overflow. As you can see it's the previous frames that we need to look into when the numbers start going into very large for fp16 numbers. The tracking is done in a forward hook, which gets invoked immediately after `forward` has completed. By default the last 21 frames are printed. You can change the default to adjust for your needs. For example : ```python debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100) ``` To validate that you have set up this debugging feature correctly, and you intend to use it in a training that may take hours to complete, first run it with normal tracing enabled for one of a few batches as explained in the next section. Mode 2. Specific batch absolute min/max tracing without detection The second work mode is per-batch tracing with the underflow/overflow detection feature turned off. Let's say you want to watch the absolute min and max values for all the ingredients of each `forward` call of a given batch, and only do that for batches 1 and 3. Then you instantiate this class as : ```python debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3]) ``` And now full batches 1 and 3 will be traced using the same format as explained above. Batches are 0-indexed. This is helpful if you know that the program starts misbehaving after a certain batch number, so you can fast-forward right to that area. Early stopping: You can also specify the batch number after which to stop the training, with : ```python debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3], abort_after_batch_num=3) ``` This feature is mainly useful in the tracing mode, but you can use it for any mode. **Performance**: As this module measures absolute `min`/``max` of each weight of the model on every forward it'll slow the training down. Therefore remember to turn it off once the debugging needs have been met. Args: model (`nn.Module`): The model to debug. max_frames_to_save (`int`, *optional*, defaults to 21): How many frames back to record trace_batch_nums(`list[int]`, *optional*, defaults to `[]`): Which batch numbers to trace (turns detection off) abort_after_batch_num (`int``, *optional*): Whether to abort after a certain batch number has finished """ def __init__(self, model, max_frames_to_save=21, trace_batch_nums=[], abort_after_batch_num=None): self.model = model self.trace_batch_nums = trace_batch_nums self.abort_after_batch_num = abort_after_batch_num # keep a LIFO buffer of frames to dump as soon as inf/nan is encountered to give context to the problem emergence self.frames = collections.deque([], max_frames_to_save) self.frame = [] self.batch_number = 0 self.total_calls = 0 self.detected_overflow = False self.prefix = " " self.analyse_model() self.register_forward_hook() def save_frame(self, frame=None): if frame is not None: self.expand_frame(frame) self.frames.append("\n".join(self.frame)) self.frame = [] # start a new frame def expand_frame(self, line): self.frame.append(line) def trace_frames(self): print("\n".join(self.frames)) self.frames = [] def reset_saved_frames(self): self.frames = [] def dump_saved_frames(self): print(f"\nDetected inf/nan during batch_number={self.batch_number}") print(f"Last {len(self.frames)} forward frames:") print(f"{'abs min':8} {'abs max':8} metadata") print("\n".join(self.frames)) print("\n\n") self.frames = [] def analyse_model(self): # extract the fully qualified module names, to be able to report at run time. e.g.: # encoder.block.2.layer.0.SelfAttention.o # # for shared weights only the first shared module name will be registered self.module_names = {m: name for name, m in self.model.named_modules()} # self.longest_module_name = max(len(v) for v in self.module_names.values()) def analyse_variable(self, var, ctx): if torch.is_tensor(var): self.expand_frame(get_abs_min_max(var, ctx)) if detect_overflow(var, ctx): self.detected_overflow = True elif var is None: self.expand_frame(f"{'None':>17} {ctx}") else: self.expand_frame(f"{'not a tensor':>17} {ctx}") def batch_start_frame(self): self.expand_frame(f"\n\n{self.prefix} *** Starting batch number={self.batch_number} ***") self.expand_frame(f"{'abs min':8} {'abs max':8} metadata") def batch_end_frame(self): self.expand_frame(f"{self.prefix} *** Finished batch number={self.batch_number - 1} ***\n\n") def create_frame(self, module, input, output): self.expand_frame(f"{self.prefix} {self.module_names[module]} {module.__class__.__name__}") # params for name, p in module.named_parameters(recurse=False): self.analyse_variable(p, name) # inputs if isinstance(input, tuple): for i, x in enumerate(input): self.analyse_variable(x, f"input[{i}]") else: self.analyse_variable(input, "input") # outputs if isinstance(output, tuple): for i, x in enumerate(output): # possibly a tuple of tuples if isinstance(x, tuple): for j, y in enumerate(x): self.analyse_variable(y, f"output[{i}][{j}]") else: self.analyse_variable(x, f"output[{i}]") else: self.analyse_variable(output, "output") self.save_frame() def register_forward_hook(self): self.model.apply(self._register_forward_hook) def _register_forward_hook(self, module): module.register_forward_hook(self.forward_hook) def forward_hook(self, module, input, output): # - input is a tuple of packed inputs (could be non-Tensors) # - output could be a Tensor or a tuple of Tensors and non-Tensors last_frame_of_batch = False trace_mode = self.batch_number in self.trace_batch_nums if trace_mode: self.reset_saved_frames() if self.total_calls == 0: self.batch_start_frame() self.total_calls += 1 # count batch numbers - the very first forward hook of the batch will be called when the # batch completes - i.e. it gets called very last - we know this batch has finished if module == self.model: self.batch_number += 1 last_frame_of_batch = True self.create_frame(module, input, output) # if last_frame_of_batch: # self.batch_end_frame() if trace_mode: self.trace_frames() if last_frame_of_batch: self.batch_start_frame() if self.detected_overflow and not trace_mode: self.dump_saved_frames() # now we can abort, as it's pointless to continue running raise ValueError( "DebugUnderflowOverflow: inf/nan detected, aborting as there is no point running further. " "Please scroll up above this traceback to see the activation values prior to this event." ) # abort after certain batch if requested to do so if self.abort_after_batch_num is not None and self.batch_number > self.abort_after_batch_num: raise ValueError( f"DebugUnderflowOverflow: aborting after {self.batch_number} batches due to" f" `abort_after_batch_num={self.abort_after_batch_num}` arg" ) def get_abs_min_max(var, ctx): abs_var = var.abs() return f"{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}" def detect_overflow(var, ctx): """ Report whether the tensor contains any `nan` or `inf` entries. This is useful for detecting overflows/underflows and best to call right after the function that did some math that modified the tensor in question. This function contains a few other helper features that you can enable and tweak directly if you want to track various other things. Args: var: the tensor variable to check ctx: the message to print as a context Return: `True` if `inf` or `nan` was detected, `False` otherwise """ detected = False if torch.isnan(var).any().item(): detected = True print(f"{ctx} has nans") if torch.isinf(var).any().item(): detected = True print(f"{ctx} has infs") # if needed to monitor large elements can enable the following if 0: # and detected: n100 = var[torch.ge(var.abs(), 100)] if n100.numel() > 0: print(f"{ctx}: n100={n100.numel()}") n1000 = var[torch.ge(var.abs(), 1000)] if n1000.numel() > 0: print(f"{ctx}: n1000={n1000.numel()}") n10000 = var[torch.ge(var.abs(), 10000)] if n10000.numel() > 0: print(f"{ctx}: n10000={n10000.numel()}") if 0: print(f"min={var.min():9.2e} max={var.max():9.2e}") if 0: print(f"min={var.min():9.2e} max={var.max():9.2e} var={var.var():9.2e} mean={var.mean():9.2e} ({ctx})") return detected class DebugOption(ExplicitEnum): UNDERFLOW_OVERFLOW = "underflow_overflow" TPU_METRICS_DEBUG = "tpu_metrics_debug"
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/video_processing_utils.py
src/transformers/video_processing_utils.py
# coding=utf-8 # Copyright 2025 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import warnings from collections.abc import Callable from copy import deepcopy from functools import partial from typing import Any, Optional, Union import numpy as np from huggingface_hub import create_repo, is_offline_mode from huggingface_hub.dataclasses import validate_typed_dict from .dynamic_module_utils import custom_object_save from .image_processing_utils import ( BatchFeature, get_size_dict, ) from .image_processing_utils_fast import BaseImageProcessorFast from .image_utils import ( ChannelDimension, SizeDict, validate_kwargs, ) from .processing_utils import Unpack, VideosKwargs from .utils import ( IMAGE_PROCESSOR_NAME, PROCESSOR_NAME, VIDEO_PROCESSOR_NAME, TensorType, add_start_docstrings, copy_func, is_torch_available, is_torchcodec_available, is_torchvision_v2_available, logging, safe_load_json_file, ) from .utils.hub import cached_file from .utils.import_utils import requires from .video_utils import ( VideoInput, VideoMetadata, group_videos_by_shape, infer_channel_dimension_format, is_valid_video, load_video, make_batched_metadata, make_batched_videos, reorder_videos, ) if is_torch_available(): import torch if is_torchvision_v2_available(): from torchvision.transforms.v2 import functional as F logger = logging.get_logger(__name__) BASE_VIDEO_PROCESSOR_DOCSTRING = r""" Args: do_resize (`bool`, *optional*, defaults to `self.do_resize`): Whether to resize the video's (height, width) dimensions to the specified `size`. Can be overridden by the `do_resize` parameter in the `preprocess` method. size (`dict`, *optional*, defaults to `self.size`): Size of the output video after resizing. Can be overridden by the `size` parameter in the `preprocess` method. size_divisor (`int`, *optional*, defaults to `self.size_divisor`): The size by which to make sure both the height and width can be divided. default_to_square (`bool`, *optional*, defaults to `self.default_to_square`): Whether to default to a square video when resizing, if size is an int. resample (`PILImageResampling`, *optional*, defaults to `self.resample`): Resampling filter to use if resizing the video. Only has an effect if `do_resize` is set to `True`. Can be overridden by the `resample` parameter in the `preprocess` method. do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`): Whether to center crop the video to the specified `crop_size`. Can be overridden by `do_center_crop` in the `preprocess` method. crop_size (`dict[str, int]` *optional*, defaults to `self.crop_size`): Size of the output video after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess` method. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): Whether to rescale the video by the specified scale `rescale_factor`. Can be overridden by the `do_rescale` parameter in the `preprocess` method. rescale_factor (`int` or `float`, *optional*, defaults to `self.rescale_factor`): Scale factor to use if rescaling the video. Only has an effect if `do_rescale` is set to `True`. Can be overridden by the `rescale_factor` parameter in the `preprocess` method. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`): Whether to normalize the video. Can be overridden by the `do_normalize` parameter in the `preprocess` method. Can be overridden by the `do_normalize` parameter in the `preprocess` method. image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`): Mean to use if normalizing the video. This is a float or list of floats the length of the number of channels in the video. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be overridden by the `image_mean` parameter in the `preprocess` method. image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`): Standard deviation to use if normalizing the video. This is a float or list of floats the length of the number of channels in the video. Can be overridden by the `image_std` parameter in the `preprocess` method. Can be overridden by the `image_std` parameter in the `preprocess` method. do_convert_rgb (`bool`, *optional*, defaults to `self.image_std`): Whether to convert the video to RGB. video_metadata (`VideoMetadata`, *optional*): Metadata of the video containing information about total duration, fps and total number of frames. do_sample_frames (`int`, *optional*, defaults to `self.do_sample_frames`): Whether to sample frames from the video before processing or to process the whole video. num_frames (`int`, *optional*, defaults to `self.num_frames`): Maximum number of frames to sample when `do_sample_frames=True`. fps (`int` or `float`, *optional*, defaults to `self.fps`): Target frames to sample per second when `do_sample_frames=True`. return_tensors (`str` or `TensorType`, *optional*): Returns stacked tensors if set to `pt, otherwise returns a list of tensors. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`): The channel dimension format for the output video. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: video in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: video in (height, width, num_channels) format. - Unset: Use the channel dimension format of the input video. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input video. If unset, the channel dimension format is inferred from the input video. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: video in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: video in (height, width, num_channels) format. - `"none"` or `ChannelDimension.NONE`: video in (height, width) format. device (`torch.device`, *optional*): The device to process the videos on. If unset, the device is inferred from the input videos. return_metadata (`bool`, *optional*): Whether to return video metadata or not. """ @add_start_docstrings( "Constructs a base VideoProcessor.", BASE_VIDEO_PROCESSOR_DOCSTRING, ) @requires(backends=("vision", "torchvision")) class BaseVideoProcessor(BaseImageProcessorFast): _auto_class = None resample = None image_mean = None image_std = None size = None size_divisor = None default_to_square = True crop_size = None do_resize = None do_center_crop = None do_rescale = None rescale_factor = 1 / 255 do_normalize = None do_convert_rgb = None do_sample_frames = None fps = None num_frames = None video_metadata = None return_metadata = False valid_kwargs = VideosKwargs model_input_names = ["pixel_values_videos"] def __init__(self, **kwargs: Unpack[VideosKwargs]) -> None: super().__init__() kwargs.pop("processor_class", None) # Additional attributes without default values for key, value in kwargs.items(): try: setattr(self, key, value) except AttributeError as err: logger.error(f"Can't set {key} with value {value} for {self}") raise err # Prepare size related keys and turn then into `SizeDict` size = kwargs.pop("size", self.size) self.size = ( get_size_dict(size=size, default_to_square=kwargs.pop("default_to_square", self.default_to_square)) if size is not None else None ) crop_size = kwargs.pop("crop_size", self.crop_size) self.crop_size = get_size_dict(crop_size, param_name="crop_size") if crop_size is not None else None # Save valid kwargs in a list for further processing self.model_valid_processing_keys = list(self.valid_kwargs.__annotations__.keys()) for key in self.model_valid_processing_keys: if kwargs.get(key) is not None: setattr(self, key, kwargs[key]) else: setattr(self, key, deepcopy(getattr(self, key, None))) def __call__(self, videos, **kwargs) -> BatchFeature: return self.preprocess(videos, **kwargs) def convert_to_rgb( self, video: "torch.Tensor", ) -> VideoInput: """ Converts a video to RGB format. Args: video (`"torch.Tensor"`): The video to convert. Returns: `torch.Tensor`: The converted video. """ video = F.grayscale_to_rgb(video) if video.shape[-3] == 3 or not (video[..., 3, :, :] < 255).any(): return video # There is a transparency layer, blend it with a white background. # Calculate the alpha proportion for blending. alpha = video[..., 3, :, :] / 255.0 video = (1 - alpha[..., None, :, :]) * 255 + alpha[..., None, :, :] * video[..., :3, :, :] return video def sample_frames( self, metadata: VideoMetadata, num_frames: Optional[int] = None, fps: Optional[Union[int, float]] = None, **kwargs, ): """ Default sampling function which uniformly samples the desired number of frames between 0 and total number of frames. If `fps` is passed along with metadata, `fps` frames per second are sampled uniformty. Arguments `num_frames` and `fps` are mutually exclusive. Args: metadata (`VideoMetadata`): Metadata of the video containing information about total duration, fps and total number of frames. num_frames (`int`, *optional*): Maximum number of frames to sample. Defaults to `self.num_frames`. fps (`int` or `float`, *optional*): Target frames to sample per second. Defaults to `self.fps`. Returns: np.ndarray: Indices to sample video frames. """ if fps is not None and num_frames is not None: raise ValueError( "`num_frames`, `fps`, and `sample_indices_fn` are mutually exclusive arguments, please use only one!" ) num_frames = num_frames if num_frames is not None else self.num_frames fps = fps if fps is not None else self.fps total_num_frames = metadata.total_num_frames # If num_frames is not given but fps is, calculate num_frames from fps if num_frames is None and fps is not None: if metadata is None or metadata.fps is None: raise ValueError( "Asked to sample `fps` frames per second but no video metadata was provided which is required when sampling with `fps`. " "Please pass in `VideoMetadata` object or use a fixed `num_frames` per input video" ) num_frames = int(total_num_frames / metadata.fps * fps) if num_frames > total_num_frames: raise ValueError( f"Video can't be sampled. The `num_frames={num_frames}` exceeds `total_num_frames={total_num_frames}`. " ) if num_frames is not None: indices = torch.arange(0, total_num_frames, total_num_frames / num_frames).int() else: indices = torch.arange(0, total_num_frames).int() return indices def _decode_and_sample_videos( self, videos: VideoInput, video_metadata: Union[VideoMetadata, dict], do_sample_frames: Optional[bool] = None, sample_indices_fn: Optional[Callable] = None, ) -> list["torch.Tensor"]: """ Decode input videos and sample frames if needed. """ videos = make_batched_videos(videos) video_metadata = make_batched_metadata(videos, video_metadata=video_metadata) # Only sample frames if an array video is passed, otherwise first decode -> then sample if is_valid_video(videos[0]) and do_sample_frames: sampled_videos = [] sampled_metadata = [] for video, metadata in zip(videos, video_metadata): indices = sample_indices_fn(metadata=metadata) metadata.frames_indices = indices sampled_videos.append(video[indices]) sampled_metadata.append(metadata) videos = sampled_videos video_metadata = sampled_metadata elif not is_valid_video(videos[0]): if isinstance(videos[0], list): # Videos sometimes are passed as a list of image URLs, especially through templates videos = [ torch.stack([F.pil_to_tensor(image) for image in images], dim=0) for images in self.fetch_images(videos) ] if do_sample_frames: raise ValueError( "Sampling frames from a list of images is not supported! Set `do_sample_frames=False`." ) else: videos, video_metadata = self.fetch_videos(videos, sample_indices_fn=sample_indices_fn) return videos, video_metadata def _prepare_input_videos( self, videos: VideoInput, input_data_format: Optional[Union[str, ChannelDimension]] = None, device: Optional[str] = None, ) -> list["torch.Tensor"]: """ Prepare the input videos for processing. """ processed_videos = [] for video in videos: # `make_batched_videos` always returns a 4D array per video if isinstance(video, np.ndarray): # not using F.to_tensor as it doesn't handle (C, H, W) numpy arrays video = torch.from_numpy(video).contiguous() # Infer the channel dimension format if not provided if input_data_format is None: input_data_format = infer_channel_dimension_format(video) if input_data_format == ChannelDimension.LAST: video = video.permute(0, 3, 1, 2).contiguous() if device is not None: video = video.to(device) processed_videos.append(video) return processed_videos @add_start_docstrings( BASE_VIDEO_PROCESSOR_DOCSTRING, ) def preprocess( self, videos: VideoInput, **kwargs: Unpack[VideosKwargs], ) -> BatchFeature: validate_kwargs( captured_kwargs=kwargs.keys(), valid_processor_keys=list(self.valid_kwargs.__annotations__.keys()) + ["return_tensors"], ) # Perform type validation on received kwargs validate_typed_dict(self.valid_kwargs, kwargs) # Set default kwargs from self. This ensures that if a kwarg is not provided # by the user, it gets its default value from the instance, or is set to None. for kwarg_name in self.valid_kwargs.__annotations__: kwargs.setdefault(kwarg_name, getattr(self, kwarg_name, None)) input_data_format = kwargs.pop("input_data_format") do_sample_frames = kwargs.pop("do_sample_frames") device = kwargs.pop("device") video_metadata = kwargs.pop("video_metadata") sample_indices_fn = partial(self.sample_frames, **kwargs) if do_sample_frames else None videos, video_metadata = self._decode_and_sample_videos( videos, video_metadata=video_metadata, do_sample_frames=do_sample_frames, sample_indices_fn=sample_indices_fn, ) videos = self._prepare_input_videos(videos=videos, input_data_format=input_data_format, device=device) kwargs = self._further_process_kwargs(**kwargs) self._validate_preprocess_kwargs(**kwargs) # Pop kwargs that are not needed in _preprocess kwargs.pop("data_format") return_metadata = kwargs.pop("return_metadata") preprocessed_videos = self._preprocess(videos=videos, **kwargs) if return_metadata: preprocessed_videos["video_metadata"] = video_metadata return preprocessed_videos def _preprocess( self, videos: list["torch.Tensor"], do_convert_rgb: bool, do_resize: bool, size: SizeDict, interpolation: Optional["F.InterpolationMode"], do_center_crop: bool, crop_size: SizeDict, do_rescale: bool, rescale_factor: float, do_normalize: bool, image_mean: Optional[Union[float, list[float]]], image_std: Optional[Union[float, list[float]]], return_tensors: Optional[Union[str, TensorType]] = None, **kwargs, ) -> BatchFeature: # Group videos by size for batched resizing grouped_videos, grouped_videos_index = group_videos_by_shape(videos) resized_videos_grouped = {} for shape, stacked_videos in grouped_videos.items(): if do_convert_rgb: stacked_videos = self.convert_to_rgb(stacked_videos) if do_resize: stacked_videos = self.resize(stacked_videos, size=size, interpolation=interpolation) resized_videos_grouped[shape] = stacked_videos resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index) # Group videos by size for further processing # Needed in case do_resize is False, or resize returns videos with different sizes grouped_videos, grouped_videos_index = group_videos_by_shape(resized_videos) processed_videos_grouped = {} for shape, stacked_videos in grouped_videos.items(): if do_center_crop: stacked_videos = self.center_crop(stacked_videos, crop_size) # Fused rescale and normalize stacked_videos = self.rescale_and_normalize( stacked_videos, do_rescale, rescale_factor, do_normalize, image_mean, image_std ) processed_videos_grouped[shape] = stacked_videos processed_videos = reorder_videos(processed_videos_grouped, grouped_videos_index) return BatchFeature(data={"pixel_values_videos": processed_videos}, tensor_type=return_tensors) @classmethod def from_pretrained( cls, pretrained_model_name_or_path: Union[str, os.PathLike], cache_dir: Optional[Union[str, os.PathLike]] = None, force_download: bool = False, local_files_only: bool = False, token: Optional[Union[str, bool]] = None, revision: str = "main", **kwargs, ): r""" Instantiate a type of [`~video_processing_utils.VideoProcessorBase`] from an video processor. Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained video hosted inside a model repo on huggingface.co. - a path to a *directory* containing a video processor file saved using the [`~video_processing_utils.VideoProcessorBase.save_pretrained`] method, e.g., `./my_model_directory/`. - a path or url to a saved video processor JSON *file*, e.g., `./my_model_directory/video_preprocessor_config.json`. cache_dir (`str` or `os.PathLike`, *optional*): Path to a directory in which a downloaded pretrained model video processor should be cached if the standard cache should not be used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force to (re-)download the video processor files and override the cached versions if they exist. proxies (`dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. token (`str` or `bool`, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use the token generated when running `hf auth login` (stored in `~/.huggingface`). revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. <Tip> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`. </Tip> return_unused_kwargs (`bool`, *optional*, defaults to `False`): If `False`, then this function returns just the final video processor object. If `True`, then this functions returns a `Tuple(video_processor, unused_kwargs)` where *unused_kwargs* is a dictionary consisting of the key/value pairs whose keys are not video processor attributes: i.e., the part of `kwargs` which has not been used to update `video_processor` and is otherwise ignored. subfolder (`str`, *optional*, defaults to `""`): In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can specify the folder name here. kwargs (`dict[str, Any]`, *optional*): The values in kwargs of any keys which are video processor attributes will be used to override the loaded values. Behavior concerning key/value pairs whose keys are *not* video processor attributes is controlled by the `return_unused_kwargs` keyword parameter. Returns: A video processor of type [`~video_processing_utils.ImagVideoProcessorBase`]. Examples: ```python # We can't instantiate directly the base class *VideoProcessorBase* so let's show the examples on a # derived class: *LlavaOnevisionVideoProcessor* video_processor = LlavaOnevisionVideoProcessor.from_pretrained( "llava-hf/llava-onevision-qwen2-0.5b-ov-hf" ) # Download video_processing_config from huggingface.co and cache. video_processor = LlavaOnevisionVideoProcessor.from_pretrained( "./test/saved_model/" ) # E.g. video processor (or model) was saved using *save_pretrained('./test/saved_model/')* video_processor = LlavaOnevisionVideoProcessor.from_pretrained("./test/saved_model/video_preprocessor_config.json") video_processor = LlavaOnevisionVideoProcessor.from_pretrained( "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", do_normalize=False, foo=False ) assert video_processor.do_normalize is False video_processor, unused_kwargs = LlavaOnevisionVideoProcessor.from_pretrained( "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", do_normalize=False, foo=False, return_unused_kwargs=True ) assert video_processor.do_normalize is False assert unused_kwargs == {"foo": False} ```""" kwargs["cache_dir"] = cache_dir kwargs["force_download"] = force_download kwargs["local_files_only"] = local_files_only kwargs["revision"] = revision if token is not None: kwargs["token"] = token video_processor_dict, kwargs = cls.get_video_processor_dict(pretrained_model_name_or_path, **kwargs) return cls.from_dict(video_processor_dict, **kwargs) def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs): """ Save an video processor object to the directory `save_directory`, so that it can be re-loaded using the [`~video_processing_utils.VideoProcessorBase.from_pretrained`] class method. Args: save_directory (`str` or `os.PathLike`): Directory where the video processor JSON file will be saved (will be created if it does not exist). push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace). kwargs (`dict[str, Any]`, *optional*): Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method. """ if os.path.isfile(save_directory): raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file") os.makedirs(save_directory, exist_ok=True) if push_to_hub: commit_message = kwargs.pop("commit_message", None) repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1]) repo_id = create_repo(repo_id, exist_ok=True, **kwargs).repo_id files_timestamps = self._get_files_timestamps(save_directory) # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be # loaded from the Hub. if self._auto_class is not None: custom_object_save(self, save_directory, config=self) # If we save using the predefined names, we can load using `from_pretrained` output_video_processor_file = os.path.join(save_directory, VIDEO_PROCESSOR_NAME) self.to_json_file(output_video_processor_file) logger.info(f"Video processor saved in {output_video_processor_file}") if push_to_hub: self._upload_modified_files( save_directory, repo_id, files_timestamps, commit_message=commit_message, token=kwargs.get("token"), ) return [output_video_processor_file] @classmethod def get_video_processor_dict( cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs ) -> tuple[dict[str, Any], dict[str, Any]]: """ From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a video processor of type [`~video_processing_utils.VideoProcessorBase`] using `from_dict`. Parameters: pretrained_model_name_or_path (`str` or `os.PathLike`): The identifier of the pre-trained checkpoint from which we want the dictionary of parameters. subfolder (`str`, *optional*, defaults to `""`): In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can specify the folder name here. Returns: `tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the video processor object. """ cache_dir = kwargs.pop("cache_dir", None) force_download = kwargs.pop("force_download", False) proxies = kwargs.pop("proxies", None) token = kwargs.pop("token", None) local_files_only = kwargs.pop("local_files_only", False) revision = kwargs.pop("revision", None) subfolder = kwargs.pop("subfolder", "") from_pipeline = kwargs.pop("_from_pipeline", None) from_auto_class = kwargs.pop("_from_auto", False) user_agent = {"file_type": "video processor", "from_auto_class": from_auto_class} if from_pipeline is not None: user_agent["using_pipeline"] = from_pipeline if is_offline_mode() and not local_files_only: logger.info("Offline mode: forcing local_files_only=True") local_files_only = True pretrained_model_name_or_path = str(pretrained_model_name_or_path) is_local = os.path.isdir(pretrained_model_name_or_path) if os.path.isfile(pretrained_model_name_or_path): resolved_video_processor_file = pretrained_model_name_or_path resolved_processor_file = None is_local = True else: video_processor_file = VIDEO_PROCESSOR_NAME try: # Try to load with a new config name first and if not successful try with the old file name # NOTE: we save all processor configs as nested dict in PROCESSOR_NAME from v5, which is the standard resolved_processor_file = cached_file( pretrained_model_name_or_path, filename=PROCESSOR_NAME, cache_dir=cache_dir, force_download=force_download, proxies=proxies, local_files_only=local_files_only, token=token, user_agent=user_agent, revision=revision, subfolder=subfolder, _raise_exceptions_for_missing_entries=False, ) resolved_video_processor_files = [ resolved_file for filename in [video_processor_file, IMAGE_PROCESSOR_NAME] if ( resolved_file := cached_file( pretrained_model_name_or_path, filename=filename, cache_dir=cache_dir, force_download=force_download, proxies=proxies, local_files_only=local_files_only, token=token, user_agent=user_agent, revision=revision, subfolder=subfolder, _raise_exceptions_for_missing_entries=False, ) ) is not None ] resolved_video_processor_file = ( resolved_video_processor_files[0] if resolved_video_processor_files else None ) except OSError: # Raise any OS error raise by `cached_file`. It will have a helpful error message adapted to # the original exception. raise except Exception: # For any other exception, we throw a generic error. raise OSError( f"Can't load video processor for '{pretrained_model_name_or_path}'. If you were trying to load" " it from 'https://huggingface.co/models', make sure you don't have a local directory with the" f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a" f" directory containing a {video_processor_file} file" ) # Load video_processor dict. Priority goes as (nested config if found -> video processor config -> image processor config) # We are downloading both configs because almost all models have a `processor_config.json` but # not all of these are nested. We need to check if it was saved recebtly as nested or if it is legacy style video_processor_dict = None if resolved_processor_file is not None:
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/tokenization_python.py
src/transformers/tokenization_python.py
# Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Tokenization classes for python tokenizers. For fast tokenizers (provided by HuggingFace's tokenizers library) see tokenization_utils_tokenizers.py """ import bisect import unicodedata from collections import OrderedDict from typing import Any, overload from .tokenization_utils_base import ( INIT_TOKENIZER_DOCSTRING, AddedToken, BatchEncoding, EncodedInput, PreTokenizedInput, PreTrainedTokenizerBase, TextInput, TruncationStrategy, ) from .utils import PaddingStrategy, TensorType, add_end_docstrings, logging logger = logging.get_logger(__name__) # Slow tokenizers are saved in a vocabulary plus three separated files SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json" ADDED_TOKENS_FILE = "added_tokens.json" TOKENIZER_CONFIG_FILE = "tokenizer_config.json" class Trie: """ Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass Loose reference https://en.wikipedia.org/wiki/Trie """ def __init__(self, *args): self.data = {} self._tokens = set() self._termination_char = "" self.update(*args) def update(self, *args): """ Updates the Trie with new tokens provided as arguments. Args: *args: Variable number of words to be added to the Trie. """ for token in tuple(*args): self.add(token) def add(self, word: str): """ Passes over every char (utf-8 char) on word and recursively adds it to the internal `data` trie representation. The special key `""` in `self._termination_char` is used to represent termination. This function is idempotent, adding twice the same word will leave the trie unchanged Example: ```python >>> trie = Trie() >>> trie.add("Hello 友達") >>> trie.data {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} >>> trie.add("Hello") >>> trie.data {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} ``` """ if not word: # Prevent empty string return self._tokens.add(word) ref = self.data for char in word: ref[char] = ref.setdefault(char, {}) ref = ref[char] ref[self._termination_char] = 1 def split(self, text: str) -> list[str]: """ Will look for the words added to the trie within `text`. Output is the original string split along the boundaries of the words found. This trie will match the longest possible word first ! Example: ```python >>> trie = Trie() >>> trie.split("[CLS] This is a extra_id_100") ["[CLS] This is a extra_id_100"] >>> trie.add("[CLS]") >>> trie.add("extra_id_1") >>> trie.add("extra_id_100") >>> trie.split("[CLS] This is a extra_id_100") ["[CLS]", " This is a ", "extra_id_100"] ``` """ # indexes are counted left of the chars index. # "hello", index 0, is left of h, index 1 is between h and e. # index 5 is right of the "o". # States are going to capture every possible start (indexes as above) # as keys, and have as values, a pointer to the position in the trie # where we're at. This is a partial match for now. # This enables to keep track of multiple matches while we're iterating # the string # If the trie contains, "blowing", and "lower" and we encounter the # string "blower", we need to split into ["b", "lower"]. # This is where we need to keep track of multiple possible starts. states = OrderedDict() # This will contain every indices where we need # to cut. # We force to cut at offset 0 and len(text) (added later) offsets = [0] # This is used by the lookahead which needs to skip over # some text where the full match exceeded the place in the initial # for loop skip = 0 # Main loop, Giving this algorithm O(n) complexity for current, current_char in enumerate(text): if skip and current < skip: # Prevents the lookahead for matching twice # like extra_id_100 and id_100 continue # This will track every state # that stop matching, we need to stop tracking them. # If we look at "lowball", we're going to match "l" (add it to states), "o", "w", then # fail on "b", we need to remove 0 from the valid states. to_remove = set() # Whenever we found a match, we need to drop everything # this is a greedy algorithm, it will match on the first found token reset = False # In this case, we already have partial matches (But unfinished) for start, trie_pointer in states.items(): if "" in trie_pointer: # This is a final match, we need to reset and # store the results in `offsets`. # Lookahead to match longest first # Important in case of extra_id_1 vs extra_id_100 # Here we are also actively looking for other earlier partial # matches # "[CLS]", "L", we need to match CLS even if L is special for lookstart, looktrie_pointer in states.items(): if lookstart > start: # This partial match is later, we can stop looking break elif lookstart < start: # This partial match is earlier, the trie pointer # was already updated, so index is + 1 lookahead_index = current + 1 end = current + 1 else: # Here lookstart == start and # looktrie_pointer == trie_pointer # It wasn't updated yet so indices are current ones lookahead_index = current end = current next_char = text[lookahead_index] if lookahead_index < len(text) else None if "" in looktrie_pointer: start = lookstart end = lookahead_index skip = lookahead_index while next_char in looktrie_pointer: looktrie_pointer = looktrie_pointer[next_char] lookahead_index += 1 if "" in looktrie_pointer: start = lookstart end = lookahead_index skip = lookahead_index if lookahead_index == len(text): # End of string break next_char = text[lookahead_index] # End lookahead # Storing and resetting offsets.append(start) offsets.append(end) reset = True break elif current_char in trie_pointer: # The current character being looked at has a match within the trie # update the pointer (it will be stored back into states later). trie_pointer = trie_pointer[current_char] # Storing back the new pointer into the states. # Partial matches got longer by one. states[start] = trie_pointer else: # The new character has not match in the trie, we need # to stop keeping track of this partial match. # We can't do it directly within the loop because of how # python iteration works to_remove.add(start) # Either clearing the full start (we found a real match) # Or clearing only the partial matches that didn't work. if reset: states = {} else: for start in to_remove: del states[start] # If this character is a starting character within the trie # start keeping track of this partial match. if current >= skip and current_char in self.data: states[current] = self.data[current_char] # We have a cut at the end with states. for start, trie_pointer in states.items(): if "" in trie_pointer: # This is a final match, we need to reset and # store the results in `offsets`. end = len(text) offsets.append(start) offsets.append(end) # Longest cut is always the one with lower start so the first # item so we need to break. break return self.cut_text(text, offsets) def cut_text(self, text, offsets): # We have all the offsets now, we just need to do the actual splitting. # We need to eventually add the first part of the string and the eventual # last part. offsets.append(len(text)) tokens = [] start = 0 for end in offsets: if start > end: logger.error( "There was a bug in Trie algorithm in tokenization. Attempting to recover. Please report it" " anyway." ) continue elif start == end: # This might happen if there's a match at index 0 # we're also preventing zero-width cuts in case of two # consecutive matches continue tokens.append(text[start:end]) start = end return tokens class ExtensionsTrie(Trie): def __init__(self, *args): super().__init__(*args) def extensions(self, prefix: str): """ Generates all extensions of a given prefix token in the Trie. Example: ```python >>> trie = Trie() >>> trie.add("apple") >>> trie.add("app") >>> trie.add("application") >>> trie.extensions("app") ['app', 'apple', 'application'] ``` """ prefix_node = self._get_node(prefix) ret = self._collect_tokens(prefix_node) return [prefix + token for token in ret] def _get_node(self, token: str) -> dict: """ Retrieves the node corresponding to the given token in the Trie. Args: token (str): The token for which the corresponding node needs to be retrieved. Returns: dict: The node in the Trie corresponding to the given token. """ node = self.data for char in token: if char not in node: break node = node[char] return node def _collect_tokens(self, node: dict) -> list: """ Generates all tokens in the Trie starting from a given node. Args: node (dict): The node in the Trie from which tokens need to be generated. Returns: list: List of tokens generated from the given node. """ tokens = [self._termination_char] if self._termination_char in node else [] for token, subtrie_head in node.items(): if token != self._termination_char: subtokens = self._collect_tokens(subtrie_head) tokens.extend([token + subtoken for subtoken in subtokens]) return tokens def _is_whitespace(char): """Checks whether `char` is a whitespace character.""" # \t, \n, and \r are technically control characters but we treat them # as whitespace since they are generally considered as such. if char == " " or char == "\t" or char == "\n" or char == "\r": return True cat = unicodedata.category(char) if cat == "Zs": return True return False def _is_control(char): """Checks whether `char` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char == "\t" or char == "\n" or char == "\r": return False cat = unicodedata.category(char) if cat.startswith("C"): return True return False def _is_punctuation(char): """Checks whether `char` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, for # consistency. if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True cat = unicodedata.category(char) if cat.startswith("P"): return True return False def _is_end_of_word(text): """Checks whether the last character in text is one of a punctuation, control or whitespace character.""" last_char = text[-1] return bool(_is_control(last_char) | _is_punctuation(last_char) | _is_whitespace(last_char)) def _is_start_of_word(text): """Checks whether the first character in text is one of a punctuation, control or whitespace character.""" first_char = text[0] return bool(_is_control(first_char) | _is_punctuation(first_char) | _is_whitespace(first_char)) def _insert_one_token_to_ordered_list(token_list: list[str], new_token: str): """ Inserts one token to an ordered list if it does not already exist. Note: token_list must be sorted. """ insertion_idx = bisect.bisect_left(token_list, new_token) # Checks if new_token is already in the ordered token_list if insertion_idx < len(token_list) and token_list[insertion_idx] == new_token: # new_token is in token_list, don't add return else: token_list.insert(insertion_idx, new_token) @add_end_docstrings(INIT_TOKENIZER_DOCSTRING) class PythonBackend(PreTrainedTokenizerBase): """ Base class for all slow tokenizers. Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`]. Handle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading pretrained tokenizers as well as adding tokens to the vocabulary. This class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...). """ def __init__(self, **kwargs): # 1. Init the parent class self.tokens_trie = Trie() # 2. init `_added_tokens_decoder` if child class did not if not hasattr(self, "_added_tokens_decoder"): self._added_tokens_decoder: dict[int, AddedToken] = {} # 3. if a `added_tokens_decoder` is passed, we are loading from a saved tokenizer, we overwrite self._added_tokens_decoder.update(kwargs.pop("added_tokens_decoder", {})) self._added_tokens_encoder: dict[str, int] = {k.content: v for v, k in self._added_tokens_decoder.items()} # 4. Token type ID configuration for dynamic mask building # These can be overridden by subclasses to avoid overriding create_token_type_ids_from_sequences self.token_type_ids_pattern = kwargs.pop("token_type_ids_pattern", "bert_style") # "all_zeros" or "bert_style" self.token_type_ids_include_special_tokens = kwargs.pop("token_type_ids_include_special_tokens", True) # 5. Special tokens mask configuration # Patterns: "none", "cls_sep", "eos", "bos", "bos_eos", "cls_double_sep", "prefix_suffix" self.special_tokens_pattern = kwargs.pop("special_tokens_pattern", "cls_sep") # 6. Set backend to "custom" if not already set (for direct PreTrainedTokenizer subclasses) if "backend" not in kwargs: kwargs["backend"] = "custom" # 7. init the parent class super().__init__(**kwargs) if self._added_tokens_decoder: self._update_total_vocab_size() # 4. If some of the special tokens are not part of the vocab, we add them, at the end. # V5: the order of addition follows self.SPECIAL_TOKENS_ATTRIBUTES, then extra special tokens # Note: _add_tokens will automatically skip tokens that are already in the base vocab self._add_tokens( [token for token in self.all_special_tokens if token not in self._added_tokens_encoder], special_tokens=True, ) self._update_total_vocab_size() @property def is_fast(self) -> bool: return False @property def added_tokens_encoder(self) -> dict[str, int]: """ Returns the sorted mapping from string to index. The added tokens encoder is cached for performance optimisation in `self._added_tokens_encoder` for the slow tokenizers. """ return {k.content: v for v, k in sorted(self._added_tokens_decoder.items(), key=lambda item: item[0])} @property def added_tokens_decoder(self) -> dict[int, AddedToken]: """ Returns the added tokens in the vocabulary as a dictionary of index to AddedToken. Returns: `dict[str, int]`: The added tokens. """ return dict(sorted(self._added_tokens_decoder.items(), key=lambda item: item[0])) @added_tokens_decoder.setter def added_tokens_decoder(self, value: dict[int, AddedToken | str]) -> dict[int, AddedToken]: # Always raise an error if string because users should define the behavior for index, token in value.items(): if not isinstance(token, (str, AddedToken)) or not isinstance(index, int): raise TypeError( f"The provided `added_tokens_decoder` has an element of type {index.__class__, token.__class__}, should be a dict of {int, AddedToken | str}" ) self._added_tokens_decoder[index] = AddedToken(token) if isinstance(token, str) else token self._added_tokens_encoder[str(token)] = index self._update_total_vocab_size() def get_added_vocab(self) -> dict[str, int]: """ Returns the added tokens in the vocabulary as a dictionary of token to index. Results might be different from the fast call because for now we always add the tokens even if they are already in the vocabulary. This is something we should change. Returns: `dict[str, int]`: The added tokens. """ return self._added_tokens_encoder def __len__(self): """ Size of the full vocabulary with the added tokens. """ return self.total_vocab_size def _update_total_vocab_size(self): """ Update the size of the full vocabulary with the added tokens. Counts the `keys` and not the `values` because otherwise if there is a hole in the vocab, we will add tokenizers at a wrong index. This operation is slow and is only updated when adding tokens. """ self.total_vocab_size = len(self.get_vocab()) def _add_tokens(self, new_tokens: list[str] | list[AddedToken], special_tokens: bool = False) -> int: """ Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to it with indices starting from length of the current vocabulary. Special tokens are sometimes already in the vocab which is why they have to be handled specifically. Args: new_tokens (`list[str]`or `list[tokenizers.AddedToken]`): Token(s) to add in vocabulary. A token is counted as added if it's not already in the vocabulary (tested by checking if the tokenizer assign the index of the `unk_token` to them). If a token is part of the vocabulary then we simply mark this token as an `AddedToken` which allows to control the stripping and normalization of this token. This is NOT possible in `tokenizers`. special_tokens (`bool`, *optional*, defaults to `False`): Whether or not the tokens should be added as special tokens. Returns: `int`: The number of tokens actually added to the vocabulary. Examples: ```python # Let's see how to increase the vocabulary of Bert model and tokenizer tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") model = BertModel.from_pretrained("google-bert/bert-base-uncased") num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"]) print("We have added", num_added_toks, "tokens") # Note: resize_token_embeddings expects to receive the full size of the new vocabulary, i.e. the length of the tokenizer. model.resize_token_embeddings(len(tokenizer)) ```""" added_tokens = 0 if new_tokens is None: return added_tokens # TODO this is fairly slow to improve! current_vocab = self.get_vocab().copy() new_idx = len(current_vocab) # only call this once, len gives the last index + 1 for token in new_tokens: if not isinstance(token, (str, AddedToken)): raise TypeError(f"Token {token} is not a string but a {type(token)}.") if str(token) == "": continue if isinstance(token, str): if token in self._added_tokens_encoder: continue else: # very important for fast and slow equivalence! is_special = token in self.all_special_tokens or special_tokens token = AddedToken( token, rstrip=False, lstrip=False, normalized=not is_special, special=is_special ) elif special_tokens: # doing token.special=True changes the normalization! will fix in rust # this is important and the only reason why the AddedTokens in each class are normalized by default token.__setstate__({"special": True, "normalized": token.normalized}) if token in self._added_tokens_decoder: continue if not token.special and token.normalized and getattr(self, "do_lower_case", False): # Normalize if requested token.content = token.content.lower() if token.content not in current_vocab: token_index = new_idx + added_tokens current_vocab[token.content] = token_index added_tokens += 1 else: token_index = current_vocab[token.content] if token.special and str(token) not in self.all_special_tokens: self._extra_special_tokens.append(token) # the setter automatically updates the reverse map self._added_tokens_decoder[token_index] = token self._added_tokens_encoder[token.content] = token_index if self.verbose: logger.info(f"Adding {token} to the vocabulary") self._update_trie() self._update_total_vocab_size() return added_tokens def _update_trie(self, unique_no_split_tokens: list[str] | None = None): for token in self._added_tokens_decoder.values(): if token.content not in self.tokens_trie._tokens: self.tokens_trie.add(token.content) for token in unique_no_split_tokens or []: if token not in self.tokens_trie._tokens: self.tokens_trie.add(token) def num_special_tokens_to_add(self, pair: bool = False) -> int: """ Returns the number of added tokens when encoding a sequence with special tokens. <Tip> This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put this inside your training loop. </Tip> Args: pair (`bool`, *optional*, defaults to `False`): Whether the number of added tokens should be computed in the case of a sequence pair or a single sequence. Returns: `int`: Number of special tokens added to sequences. """ token_ids_0 = [] token_ids_1 = [] return len(self.build_inputs_with_special_tokens(token_ids_0, token_ids_1 if pair else None)) def tokenize(self, text: TextInput, **kwargs) -> list[str]: """ Converts a string into a sequence of tokens, using the tokenizer. Args: text: The sequence to be encoded. **kwargs: Passed along to the model-specific `prepare_for_tokenization` preprocessing method. Returns: The list of tokens. """ split_special_tokens = kwargs.pop("split_special_tokens", self.split_special_tokens) text, kwargs = self.prepare_for_tokenization(text, **kwargs) if split_special_tokens: # Don't split on any tokens - just tokenize directly return self._tokenize(text) # Split on added tokens tokens = self.tokens_trie.split(text) no_split_token = self._added_tokens_encoder.keys() # Handle added token properties (lstrip, rstrip, single_word) for i, token in enumerate(tokens): if token in no_split_token: tok_extended = self._added_tokens_decoder.get(self._added_tokens_encoder[token]) left = tokens[i - 1] if i > 0 else None right = tokens[i + 1] if i < len(tokens) - 1 else None if isinstance(tok_extended, AddedToken): if tok_extended.rstrip and right: tokens[i + 1] = right.lstrip() if tok_extended.lstrip and left: tokens[i - 1] = left.rstrip() if tok_extended.single_word: if left and left[-1] != " ": tokens[i - 1] += token tokens[i] = "" elif right and right[0] != " ": tokens[i + 1] = token + tokens[i + 1] tokens[i] = "" # Tokenize non-added tokens result = [] all_special_tokens_set = set(self.all_special_tokens) for token in tokens: if not token: continue if token in no_split_token or token in all_special_tokens_set: result.append(token) else: result.extend(self._tokenize(token)) return result def _tokenize(self, text, **kwargs): """ Converts a string into a sequence of tokens (string), using the tokenizer. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces). Do NOT take care of added tokens. """ raise NotImplementedError def _convert_token_to_id_with_added_voc(self, token): if token in self.added_tokens_encoder: return self.added_tokens_encoder[token] return self._convert_token_to_id(token) def _convert_token_to_id(self, token): raise NotImplementedError def _encode_plus( self, text: TextInput | PreTokenizedInput | EncodedInput, text_pair: TextInput | PreTokenizedInput | EncodedInput | None = None, add_special_tokens: bool = True, padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE, max_length: int | None = None, stride: int = 0, is_split_into_words: bool = False, pad_to_multiple_of: int | None = None, padding_side: str | None = None, return_tensors: str | TensorType | None = None, return_token_type_ids: bool | None = None, return_attention_mask: bool | None = None, return_overflowing_tokens: bool = False, return_special_tokens_mask: bool = False, return_length: bool = False, verbose: bool = True, **kwargs, ) -> BatchEncoding: # Detect batched inputs (list of sequences) is_batched = isinstance(text, (list, tuple)) and ( (not text and not is_split_into_words) or (text and is_split_into_words and isinstance(text[0], (list, tuple))) or (text and not is_split_into_words and isinstance(text[0], (str, list, tuple))) ) if is_batched: if text_pair is not None: if not isinstance(text_pair, (list, tuple)) or len(text_pair) != len(text): raise ValueError("If `text` is a batch, `text_pair` must also be a batch of the same length.") pairs = text_pair if text_pair is not None else [None] * len(text) batch_outputs = {} for current_text, current_pair in zip(text, pairs): # Handle tuples/lists as sequence pairs like ("text1", "text2") # For is_split_into_words=True: only unpack if it's a tuple of exactly 2 sequences (pair) # Otherwise, treat the list as a single pretokenized sequence if ( isinstance(current_text, (list, tuple)) and current_text and not isinstance(current_text[0], int) and current_pair is None ): # Check if this looks like a pair: tuple/list of length 2 where elements are strings or lists/tuples is_pair = ( len(current_text) == 2 and (isinstance(current_text[0], str) or isinstance(current_text[0], (list, tuple))) and (isinstance(current_text[1], str) or isinstance(current_text[1], (list, tuple))) ) if is_pair: current_text, current_pair = current_text elif len(current_text) == 1: current_text = current_text[0] elif not is_split_into_words: # Only raise error for non-pretokenized input raise ValueError(f"Expected a pair of sequences, got {len(current_text)} sequences.") current_output = self._encode_plus( text=current_text, text_pair=current_pair, add_special_tokens=add_special_tokens, padding_strategy=PaddingStrategy.DO_NOT_PAD, # we pad in batch afterward truncation_strategy=truncation_strategy, max_length=max_length, stride=stride, is_split_into_words=is_split_into_words, pad_to_multiple_of=None, # we pad in batch afterward padding_side=None, # we pad in batch afterward return_tensors=None, # We convert the whole batch to tensors at the end return_token_type_ids=return_token_type_ids, return_attention_mask=False, # we pad in batch afterward return_overflowing_tokens=return_overflowing_tokens, return_special_tokens_mask=return_special_tokens_mask, return_length=return_length, verbose=verbose, **kwargs, )
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/modeling_gguf_pytorch_utils.py
src/transformers/modeling_gguf_pytorch_utils.py
# Copyright 2024 The ggml.ai team and The HuggingFace Inc. team. and pygguf author (github.com/99991) # https://github.com/99991/pygguf # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from typing import NamedTuple, Optional import numpy as np from tqdm.auto import tqdm from .integrations import ( GGUF_CONFIG_DEFAULTS_MAPPING, GGUF_CONFIG_MAPPING, GGUF_TOKENIZER_MAPPING, _gguf_parse_value, ) from .utils import is_torch_available from .utils.import_utils import is_gguf_available from .utils.logging import get_logger if is_torch_available(): import torch logger = get_logger(__name__) GGUF_TO_TRANSFORMERS_MAPPING = { "ignore": { "GGUF": { "version": "version", "tensor_count": "tensor_count", "kv_count": "kv_count", }, "general": {"file_type": "file_type", "quantization_version": "quantization_version"}, }, "config": GGUF_CONFIG_MAPPING, "tokenizer": {"tokenizer": GGUF_TOKENIZER_MAPPING["tokenizer"]}, "tokenizer_config": {"tokenizer": GGUF_TOKENIZER_MAPPING["tokenizer_config"]}, } GGUF_SUPPORTED_ARCHITECTURES = list(GGUF_TO_TRANSFORMERS_MAPPING["config"].keys()) class GGUFTensor(NamedTuple): weights: np.ndarray name: str metadata: dict class TensorProcessor: def __init__(self, config=None): self.config = config or {} def preprocess_name(self, hf_name: str) -> str: """ Preprocesses the tensor name to ease loading the GGUF tensors. """ return hf_name def perform_fallback_tensor_mapping( self, gguf_to_hf_name_map: dict[str, str], suffix: str, qual_name: str, hf_name: str ): """ Called when get_gguf_hf_weights_map fails to map a HF parameter (tensor) and corresponding GGUF one. This is particularly useful to resolve one-to-many HF-GGUF mappings sometimes appear in some MoE models. """ pass def process(self, weights, name, **kwargs): return GGUFTensor(weights, name, {}) class LlamaTensorProcessor(TensorProcessor): def __init__(self, config=None): super().__init__(config=config) def process(self, weights, name, **kwargs): if ".attn_k." in name or ".attn_q." in name: num_heads = self.config.get("num_attention_heads") num_kv_heads = self.config.get("num_key_value_heads") if None in (num_heads, num_kv_heads): return GGUFTensor(weights, name, {}) if ".attn_q." in name: weights = self._reverse_permute_weights(weights, num_heads, num_heads) elif ".attn_k." in name: weights = self._reverse_permute_weights(weights, num_heads, num_kv_heads) return GGUFTensor(weights, name, {}) def _reverse_permute_weights( self, weights: np.ndarray, n_head: int, num_kv_heads: Optional[int] = None ) -> np.ndarray: # Original permutation implementation # https://github.com/ggerganov/llama.cpp/blob/a38b884c6c4b0c256583acfaaabdf556c62fabea/convert_hf_to_gguf.py#L1402-L1408 if num_kv_heads is not None and n_head != num_kv_heads: n_head = num_kv_heads dim = weights.shape[0] // n_head // 2 w = weights.reshape(n_head, dim, 2, *weights.shape[1:]) return w.swapaxes(2, 1).reshape(weights.shape) class Qwen2MoeTensorProcessor(TensorProcessor): HF_EXPERT_RENAME_PATTERN = re.compile(r"mlp.experts.\d+.") HF_MOE_W13_PATTERN = re.compile(r"model\.layers\.(?P<bid>\d+)\.mlp\.experts\.gate_up_proj") GGUF_MOE_WEIGHTS_PATTERN = re.compile(r"(?P<name>.*\.ffn_(?P<w>gate|down|up)_exps)\.weight$") def __init__(self, config=None): super().__init__(config=config) def preprocess_name(self, hf_name: str) -> str: return re.sub(self.HF_EXPERT_RENAME_PATTERN, "mlp.experts.", hf_name) def perform_fallback_tensor_mapping( self, gguf_to_hf_name_map: dict[str, str], suffix: str, qual_name: str, hf_name: str ): # Map merged MoE weights (w1 (gate) and w3 (up)) separately. if m := re.fullmatch(self.HF_MOE_W13_PATTERN, hf_name): full_hf_name = qual_name + hf_name gguf_to_hf_name_map[f"blk.{m['bid']}.ffn_gate_exps{suffix}"] = full_hf_name gguf_to_hf_name_map[f"blk.{m['bid']}.ffn_up_exps{suffix}"] = full_hf_name def process(self, weights, name: str, **kwargs): if m := re.fullmatch(self.GGUF_MOE_WEIGHTS_PATTERN, name): tensor_key_mapping = kwargs.get("tensor_key_mapping") parsed_parameters = kwargs.get("parsed_parameters") if tensor_key_mapping: self._set_moe_expert_tensor(weights, parsed_parameters, tensor_key_mapping[m["name"]], m["w"]) return GGUFTensor(weights, None, {}) if "ffn_gate_inp_shexp" in name: # for compatibility tensor shared_expert_gate must be (1, 2048) dim, # quantized one is (2048) weights = np.expand_dims(weights, axis=0) return GGUFTensor(weights, name, {}) def _set_moe_expert_tensor(self, weights: np.ndarray, parsed_parameters: dict[str, dict], hf_name: str, w: str): torch_weights = torch.from_numpy(np.copy(weights)) if w == "down": parsed_parameters["tensors"][hf_name] = torch_weights else: # Double the size of the second dimension to interleave w1 (gate) and w3 (up) # weights per expert (which is the first dimension). # w1 (gate) comes first and w3 (up) comes second. # ref: https://github.com/vllm-project/vllm/blob/8f8fda261a620234fdeea338f44093d5d8072879/vllm/model_executor/layers/fused_moe/layer.py#L988-L1015 shape = list(weights.shape) shard_dim = 1 shard_size = shape[shard_dim] shape[shard_dim] = shard_size * 2 if hf_name not in parsed_parameters["tensors"]: parsed_parameters["tensors"][hf_name] = torch.zeros(shape, dtype=torch_weights.dtype) out: torch.Tensor = parsed_parameters["tensors"][hf_name] if w == "gate": out = out.narrow(shard_dim, 0, shard_size) else: # w == "up" out = out.narrow(shard_dim, shard_size, shard_size) out.copy_(torch_weights) class BloomTensorProcessor(TensorProcessor): def __init__(self, config=None): super().__init__(config=config) def process(self, weights, name, **kwargs): if "attn_qkv" in name: num_heads = self.config["n_head"] n_embed = self.config["hidden_size"] if "weight" in name: weights = self._reverse_reshape_weights(weights, num_heads, n_embed) else: weights = self._reverse_reshape_bias(weights, num_heads, n_embed) return GGUFTensor(weights, name, {}) def _reverse_reshape_weights(self, weights: np.ndarray, n_head: int, n_embed: int): # Original reshape implementation # https://github.com/ggerganov/llama.cpp/blob/master/convert_hf_to_gguf.py#L972-L985 q, k, v = np.array_split(weights, 3, axis=0) q = q.reshape(n_head, n_embed // n_head, n_embed) k = k.reshape(n_head, n_embed // n_head, n_embed) v = v.reshape(n_head, n_embed // n_head, n_embed) qkv_weights = np.stack([q, k, v], axis=1) return qkv_weights.reshape(n_head * 3 * (n_embed // n_head), n_embed) def _reverse_reshape_bias(self, weights: np.ndarray, n_head: int, n_embed: int): # Original reshape implementation # https://github.com/ggerganov/llama.cpp/blob/master/convert_hf_to_gguf.py#L986-L998 q_bias, k_bias, v_bias = np.array_split(weights, 3) q_bias = q_bias.reshape(n_head, n_embed // n_head) k_bias = k_bias.reshape(n_head, n_embed // n_head) v_bias = v_bias.reshape(n_head, n_embed // n_head) qkv_bias = np.stack([q_bias, k_bias, v_bias], axis=1).flatten() return qkv_bias class T5TensorProcessor(TensorProcessor): def __init__(self, config=None): super().__init__(config=config) def process(self, weights, name, **kwargs): bid = None for chunk in name.split("."): if chunk.isdigit(): bid = int(chunk) break return GGUFTensor(weights, name, {"bid": bid}) class GPT2TensorProcessor(TensorProcessor): def __init__(self, config=None): super().__init__(config=config) def process(self, weights, name, **kwargs): # Original transpose implementation # https://github.com/ggerganov/llama.cpp/blob/a38b884c6c4b0c256583acfaaabdf556c62fabea/convert_hf_to_gguf.py#L2060-L2061 if ( "attn_qkv.weight" in name or "ffn_down.weight" in name or "ffn_up.weight" in name or "attn_output.weight" in name ): weights = weights.T # Handle special case for output.weight if name == "output.weight": # output.weight has conflicts with attn_output.weight in name checking # Store the tensor directly and signal to skip further processing name = "lm_head.weight" parsed_parameters = kwargs.get("parsed_parameters", {}) parsed_parameters["tensors"][name] = torch.from_numpy(np.copy(weights)) name = None # Signal to skip further processing return GGUFTensor(weights, name, {}) class MambaTensorProcessor(TensorProcessor): def __init__(self, config=None): super().__init__(config=config) def process(self, weights, name, **kwargs): if "ssm_conv1d.weight" in name: # for compatibility tensor ssm_conv1d must be (5120, 1, 4]) dim, # quantized one is (5120, 4) weights = np.expand_dims(weights, axis=1) if "ssm_a" in name: # Original exponential implementation # https://github.com/ggerganov/llama.cpp/blob/master/convert_hf_to_gguf.py#L2975-L2977 weights = np.log(-weights) return GGUFTensor(weights, name, {}) class NemotronTensorProcessor(TensorProcessor): def __init__(self, config=None): super().__init__(config=config) # ref : https://github.com/ggerganov/llama.cpp/blob/master/convert_hf_to_gguf.py#L4666 def process(self, weights, name, **kwargs): if "norm.weight" in name: weights = weights - 1 return GGUFTensor(weights, name, {}) class Gemma2TensorProcessor(TensorProcessor): def __init__(self, config=None): super().__init__(config=config) # ref: https://github.com/ggerganov/llama.cpp/blob/d79d8f39b4da6deca4aea8bf130c6034c482b320/convert_hf_to_gguf.py#L3191 # ref: https://github.com/huggingface/transformers/blob/fc37f38915372c15992b540dfcbbe00a916d4fc6/src/transformers/models/gemma/modeling_gemma.py#L89 def process(self, weights, name, **kwargs): if "norm.weight" in name: weights = weights - 1 return GGUFTensor(weights, name, {}) class Lfm2TensorProcessor(TensorProcessor): def __init__(self, config=None): super().__init__(config=config) def process(self, weights, name, **kwargs): if "shortconv.conv.weight" in name: ## GGUF shape is [hidden_dim, L_cache], HF expects [hidden_dim, 1, L_cache] weights = np.expand_dims(weights, axis=1) ## equivalent to unsqueeze(1) return GGUFTensor(weights, name, {}) TENSOR_PROCESSORS = { "llama": LlamaTensorProcessor, "qwen2moe": Qwen2MoeTensorProcessor, "qwen3moe": Qwen2MoeTensorProcessor, "bloom": BloomTensorProcessor, "t5": T5TensorProcessor, "t5encoder": T5TensorProcessor, "gpt2": GPT2TensorProcessor, "mamba": MambaTensorProcessor, "nemotron": NemotronTensorProcessor, "gemma2": Gemma2TensorProcessor, "gemma3": Gemma2TensorProcessor, "lfm2": Lfm2TensorProcessor, } def read_field(reader, field): if field not in reader.fields: return [] value = reader.fields[field] return [_gguf_parse_value(value.parts[_data_index], value.types) for _data_index in value.data] # modified from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/model_executor/model_loader/loader.py#L1115-L1147 def get_gguf_hf_weights_map( hf_model, processor: TensorProcessor, model_type: Optional[str] = None, num_layers: Optional[int] = None, qual_name: str = "", ): """ GGUF uses this naming convention for their tensors from HF checkpoint: `blk.N.BB.weight` and `blk.N.BB.bias` where N signifies the block number of a layer, and BB signifies the attention/mlp layer components. See "Standardized tensor names" in https://github.com/ggerganov/ggml/blob/master/docs/gguf.md for details. """ if is_gguf_available() and is_torch_available(): from gguf import MODEL_ARCH_NAMES, get_tensor_name_map else: logger.error( "Loading a GGUF checkpoint in PyTorch, requires both PyTorch and GGUF>=0.10.0 to be installed. Please see " "https://pytorch.org/ and https://github.com/ggerganov/llama.cpp/tree/master/gguf-py for installation instructions." ) raise ImportError("Please install torch and gguf>=0.10.0 to load a GGUF checkpoint in PyTorch.") model_type = hf_model.config.model_type if model_type is None else model_type num_layers = hf_model.config.num_hidden_layers if num_layers is None else num_layers # hack: ggufs have a different name for cohere if model_type == "cohere": model_type = "command-r" elif model_type == "qwen2_moe": model_type = "qwen2moe" elif model_type == "qwen3_moe": model_type = "qwen3moe" elif model_type == "gemma3_text": model_type = "gemma3" elif model_type == "umt5": model_type = "t5" arch = None for key, value in MODEL_ARCH_NAMES.items(): if value == model_type: arch = key break if arch is None: raise NotImplementedError( f"Unknown gguf model_type: {model_type} in gguf-py. " "This might because you're using an outdated version of gguf-py package, " "you can install `gguf` package from source refer to " "https://github.com/ggerganov/llama.cpp/tree/master/gguf-py#development" ) name_map = get_tensor_name_map(arch, num_layers) # Use a dummy conversion to get the mapping, because # hf => gguf and gguf => hf mappings are reversed gguf_to_hf_name_map = {} state_dict = hf_model.state_dict() for hf_name in state_dict: hf_name = processor.preprocess_name(hf_name) name, suffix = hf_name, "" if hf_name.endswith(".weight") or hf_name.endswith(".bias"): name, suffix = hf_name.rsplit(".", 1) suffix = "." + suffix gguf_name = name_map.get_name(name) if gguf_name is None: processor.perform_fallback_tensor_mapping(gguf_to_hf_name_map, suffix, qual_name, hf_name) continue gguf_to_hf_name_map[gguf_name + suffix] = qual_name + hf_name # Some model like Bloom converted from BloomModel instead of BloomForCausalLM # Therefore, we need to check submodule as well to get a correct mapping if named_children := hf_model.named_children(): for name, child in named_children: sub_map = get_gguf_hf_weights_map( child, processor, model_type, num_layers, qual_name=f"{qual_name}{name}." ) # Ignore the keys that are already in the main map to avoid overwriting sub_map = {k: v for k, v in sub_map.items() if k not in gguf_to_hf_name_map} gguf_to_hf_name_map.update(sub_map) return gguf_to_hf_name_map def load_gguf_checkpoint(gguf_checkpoint_path, return_tensors=False, model_to_load=None): """ Load a GGUF file and return a dictionary of parsed parameters containing tensors, the parsed tokenizer and config attributes. Args: gguf_checkpoint_path (`str`): The path the to GGUF file to load return_tensors (`bool`, defaults to `False`): Whether to read the tensors from the file and return them. Not doing so is faster and only loads the metadata in memory. """ if is_gguf_available() and is_torch_available(): from gguf import GGUFReader, dequantize else: logger.error( "Loading a GGUF checkpoint in PyTorch, requires both PyTorch and GGUF>=0.10.0 to be installed. Please see " "https://pytorch.org/ and https://github.com/ggerganov/llama.cpp/tree/master/gguf-py for installation instructions." ) raise ImportError("Please install torch and gguf>=0.10.0 to load a GGUF checkpoint in PyTorch.") reader = GGUFReader(gguf_checkpoint_path) fields = reader.fields reader_keys = list(fields.keys()) parsed_parameters = {k: {} for k in GGUF_TO_TRANSFORMERS_MAPPING} architecture = read_field(reader, "general.architecture")[0] # NOTE: Some GGUF checkpoints may miss `general.name` field in metadata model_name = read_field(reader, "general.name") updated_architecture = None # in llama.cpp mistral models use the same architecture as llama. We need # to add this patch to ensure things work correctly on our side. if "llama" in architecture and "mistral" in model_name: updated_architecture = "mistral" # FIXME: Currently this implementation is only for flan-t5 architecture. # It needs to be developed for supporting legacy t5. elif "t5" in architecture or "t5encoder" in architecture: parsed_parameters["config"]["is_gated_act"] = True if model_name and "umt5" in model_name[0].lower(): updated_architecture = "umt5" if "t5encoder" in architecture: parsed_parameters["config"]["architectures"] = ["UMT5EncoderModel"] else: if "t5encoder" in architecture: parsed_parameters["config"]["architectures"] = ["T5EncoderModel"] updated_architecture = "t5" else: updated_architecture = architecture if "qwen2moe" in architecture: updated_architecture = "qwen2_moe" elif "qwen3moe" in architecture: updated_architecture = "qwen3_moe" # For stablelm architecture, we need to set qkv_bias and use_parallel_residual from tensors # If `qkv_bias=True`, qkv_proj with bias will be present in the tensors # If `use_parallel_residual=False`, ffn_norm will be present in the tensors if "stablelm" in architecture: attn_bias_name = {"attn_q.bias", "attn_k.bias", "attn_v.bias"} ffn_norm_name = "ffn_norm" qkv_bias = any(bias_name in tensor.name for tensor in reader.tensors for bias_name in attn_bias_name) use_parallel_residual = any(ffn_norm_name in tensor.name for tensor in reader.tensors) parsed_parameters["config"]["use_qkv_bias"] = qkv_bias parsed_parameters["config"]["use_parallel_residual"] = not use_parallel_residual if architecture not in GGUF_SUPPORTED_ARCHITECTURES and updated_architecture not in GGUF_SUPPORTED_ARCHITECTURES: raise ValueError(f"GGUF model with architecture {architecture} is not supported yet.") # Handle tie_word_embeddings, if lm_head.weight is not present in tensors, # tie_word_embeddings is true otherwise false exceptions = ["falcon", "bloom"] parsed_parameters["config"]["tie_word_embeddings"] = ( all("output.weight" != tensor.name for tensor in reader.tensors) or architecture in exceptions ) # Set GGUF-specific default values config_defaults = GGUF_CONFIG_DEFAULTS_MAPPING.get( updated_architecture, GGUF_CONFIG_DEFAULTS_MAPPING.get(architecture) or {} ) for key, value in config_defaults.items(): parsed_parameters["config"].setdefault(key, value) # List all key-value pairs in a columnized format for gguf_key, field in reader.fields.items(): gguf_key = gguf_key.replace(architecture, updated_architecture) split = gguf_key.split(".") prefix = split[0] config_key = ".".join(split[1:]) value = [_gguf_parse_value(field.parts[_data_index], field.types) for _data_index in field.data] if len(value) == 1: value = value[0] if isinstance(value, str) and architecture in value: value = value.replace(architecture, updated_architecture) for parameter, parameter_renames in GGUF_TO_TRANSFORMERS_MAPPING.items(): if prefix in parameter_renames and config_key in parameter_renames[prefix]: renamed_config_key = parameter_renames[prefix][config_key] if renamed_config_key == -1: continue if renamed_config_key is not None: parsed_parameters[parameter][renamed_config_key] = value if gguf_key in reader_keys: reader_keys.remove(gguf_key) if gguf_key in reader_keys: logger.info(f"Some keys were not parsed and added into account {gguf_key} | {value}") # Gemma3 GGUF checkpoint only contains weights of text backbone if parsed_parameters["config"]["model_type"] == "gemma3": parsed_parameters["config"]["model_type"] = "gemma3_text" if parsed_parameters["config"]["model_type"] == "lfm2": gguf_num_key_value_heads = parsed_parameters["config"]["num_key_value_heads"] # LFM2 GGUF checkpoint defines num_key_value_heads as a list of integers .e.g [0, 0, 8, 0, 0, 8, 0, 0, 8, 0, 8, 0, 8, 0, 8, 0] but we need to set it to the max value for HF parsed_parameters["config"]["num_key_value_heads"] = max(gguf_num_key_value_heads) ## we already read the correct intermediate_size from the GGUF checkpoint so we need to set block_auto_adjust_ff_dim to False parsed_parameters["config"]["block_auto_adjust_ff_dim"] = False ## llama.cpp defines the layers that are full-attention by looking at num_key_value_heads ## we need to set the full_attn_idxs to the layers that are full-attention parsed_parameters["config"]["full_attn_idxs"] = [ i for i, num_kv_heads in enumerate(gguf_num_key_value_heads) if num_kv_heads > 0 ] # retrieve config vocab_size from tokenizer # Please refer to https://github.com/huggingface/transformers/issues/32526 for more details if "vocab_size" not in parsed_parameters["config"]: tokenizer_parameters = parsed_parameters["tokenizer"] if "tokens" in tokenizer_parameters: parsed_parameters["config"]["vocab_size"] = len(tokenizer_parameters["tokens"]) else: logger.warning( "Can't find a way to retrieve missing config vocab_size from tokenizer parameters. " "This will use default value from model config class and cause unexpected behavior." ) if return_tensors: parsed_parameters["tensors"] = {} config = parsed_parameters.get("config", {}) ProcessorClass = TENSOR_PROCESSORS.get(architecture, TensorProcessor) processor = ProcessorClass(config=config) tensor_key_mapping = get_gguf_hf_weights_map(model_to_load, processor) for tensor in tqdm(reader.tensors, desc="Converting and de-quantizing GGUF tensors..."): name = tensor.name weights = dequantize(tensor.data, tensor.tensor_type) result = processor.process( weights=weights, name=name, tensor_key_mapping=tensor_key_mapping, parsed_parameters=parsed_parameters, ) weights = result.weights name = result.name if name not in tensor_key_mapping: continue name = tensor_key_mapping[name] parsed_parameters["tensors"][name] = torch.from_numpy(np.copy(weights)) if len(reader_keys) > 0: logger.info(f"Some keys of the GGUF file were not considered: {reader_keys}") return parsed_parameters
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/tokenization_utils_base.py
src/transformers/tokenization_utils_base.py
# base # coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Base classes common to both the slow and the fast tokenization classes: PreTrainedTokenizerBase (host all the user fronting encoding methods) Special token mixing (host the special tokens logic) and BatchEncoding (wrap the dictionary of output with special method for the Fast tokenizers) """ from __future__ import annotations import copy import json import os import re import warnings from collections import OrderedDict, UserDict from collections.abc import Callable, Collection, Mapping, Sequence, Sized from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any, NamedTuple, Optional, Union import numpy as np from huggingface_hub import create_repo, is_offline_mode, list_repo_files from packaging import version from . import __version__ from .dynamic_module_utils import custom_object_save from .utils import ( CHAT_TEMPLATE_DIR, CHAT_TEMPLATE_FILE, ExplicitEnum, PaddingStrategy, PushToHubMixin, TensorType, add_end_docstrings, cached_file, copy_func, extract_commit_hash, is_mlx_available, is_numpy_array, is_protobuf_available, is_tokenizers_available, is_torch_available, is_torch_device, is_torch_tensor, list_repo_templates, logging, requires_backends, to_py_obj, ) from .utils.chat_parsing_utils import recursive_parse from .utils.chat_template_utils import render_jinja_template from .utils.import_utils import PROTOBUF_IMPORT_ERROR if TYPE_CHECKING: if is_torch_available(): import torch def import_protobuf_decode_error(error_message=""): if is_protobuf_available(): from google.protobuf.message import DecodeError return DecodeError else: raise ImportError(PROTOBUF_IMPORT_ERROR.format(error_message)) def flatten(arr: list): res = [] if len(arr) > 0: for sub_arr in arr: if isinstance(arr[0], (list, tuple)): res.extend(flatten(sub_arr)) else: res.append(sub_arr) return res if is_tokenizers_available() or TYPE_CHECKING: from tokenizers import Encoding as EncodingFast if is_tokenizers_available(): from tokenizers import AddedToken else: @dataclass(frozen=False, eq=True) class AddedToken: """ AddedToken represents a token to be added to a Tokenizer An AddedToken can have special options defining the way it should behave. The `normalized` will default to `not special` if it is not specified, similarly to the definition in `tokenizers`. """ def __init__( self, content: str, single_word=False, lstrip=False, rstrip=False, special=False, normalized=None ): self.content = content self.single_word = single_word self.lstrip = lstrip self.rstrip = rstrip self.special = special self.normalized = normalized if normalized is not None else not special def __getstate__(self): return self.__dict__ def __str__(self): return self.content logger = logging.get_logger(__name__) VERY_LARGE_INTEGER = int(1e30) # This is used to set the max input length for a model with infinite size input LARGE_INTEGER = int(1e20) # This is used when we need something big but slightly smaller than VERY_LARGE_INTEGER # Define type aliases and NamedTuples TextInput = str PreTokenizedInput = list[str] EncodedInput = list[int] TextInputPair = tuple[str, str] PreTokenizedInputPair = tuple[list[str], list[str]] EncodedInputPair = tuple[list[int], list[int]] # Define type aliases for text-related non-text modalities AudioInput = Union[np.ndarray, "torch.Tensor", list[np.ndarray], list["torch.Tensor"]] # Slow tokenizers used to be saved in three separated files SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json" ADDED_TOKENS_FILE = "added_tokens.json" TOKENIZER_CONFIG_FILE = "tokenizer_config.json" # Fast tokenizers (provided by HuggingFace tokenizer's library) can be saved in a single file FULL_TOKENIZER_FILE = "tokenizer.json" _re_tokenizer_file = re.compile(r"tokenizer\.(.*)\.json") class TruncationStrategy(ExplicitEnum): """ Possible values for the `truncation` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an IDE. """ ONLY_FIRST = "only_first" ONLY_SECOND = "only_second" LONGEST_FIRST = "longest_first" DO_NOT_TRUNCATE = "do_not_truncate" class CharSpan(NamedTuple): """ Character span in the original string. Args: start (`int`): Index of the first character in the original string. end (`int`): Index of the character following the last character in the original string. """ start: int end: int class TokenSpan(NamedTuple): """ Token span in an encoded string (list of tokens). Args: start (`int`): Index of the first token in the span. end (`int`): Index of the token following the last token in the span. """ start: int end: int class BatchEncoding(UserDict): """ Holds the output of the [`~tokenization_utils_base.PreTrainedTokenizerBase.__call__`], [`~tokenization_utils_base.PreTrainedTokenizerBase.encode_plus`] and [`~tokenization_utils_base.PreTrainedTokenizerBase.batch_encode_plus`] methods (tokens, attention_masks, etc). This class is derived from a python dictionary and can be used as a dictionary. In addition, this class exposes utility methods to map from word/character space to token space. Args: data (`dict`, *optional*): Dictionary of lists/arrays/tensors returned by the `__call__`/`encode_plus`/`batch_encode_plus` methods ('input_ids', 'attention_mask', etc.). encoding (`tokenizers.Encoding` or `Sequence[tokenizers.Encoding]`, *optional*): If the tokenizer is a fast tokenizer which outputs additional information like mapping from word/character space to token space the `tokenizers.Encoding` instance or list of instance (for batches) hold this information. tensor_type (`Union[None, str, TensorType]`, *optional*): You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization. prepend_batch_axis (`bool`, *optional*, defaults to `False`): Whether or not to add a batch axis when converting to tensors (see `tensor_type` above). Note that this parameter has an effect if the parameter `tensor_type` is set, *otherwise has no effect*. n_sequences (`Optional[int]`, *optional*): You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization. """ def __init__( self, data: Optional[dict[str, Any]] = None, encoding: Optional[Union[EncodingFast, Sequence[EncodingFast]]] = None, tensor_type: Union[None, str, TensorType] = None, prepend_batch_axis: bool = False, n_sequences: Optional[int] = None, ): super().__init__(data) # If encoding is not None, the fast tokenization is used if encoding is not None and isinstance(encoding, EncodingFast): encoding = [encoding] self._encodings = encoding if n_sequences is None and encoding is not None and encoding: n_sequences = encoding[0].n_sequences self._n_sequences = n_sequences self.convert_to_tensors(tensor_type=tensor_type, prepend_batch_axis=prepend_batch_axis) @property def n_sequences(self) -> Optional[int]: """ `Optional[int]`: The number of sequences used to generate each sample from the batch encoded in this [`BatchEncoding`]. Currently can be one of `None` (unknown), `1` (a single sentence) or `2` (a pair of sentences) """ return self._n_sequences def __getitem__(self, item: Union[int, str]) -> Union[Any, EncodingFast]: """ If the key is a string, returns the value of the dict associated to `key` ('input_ids', 'attention_mask', etc.). If the key is an integer, get the `tokenizers.Encoding` for batch item with index `key`. If the key is a slice, returns the value of the dict associated to `key` ('input_ids', 'attention_mask', etc.) with the constraint of slice. """ if isinstance(item, str): return self.data[item] elif self._encodings is not None: return self._encodings[item] elif isinstance(item, slice): return {key: self.data[key][item] for key in self.data} else: raise KeyError( "Invalid key. Only three types of key are available: " "(1) string, (2) integers for backend Encoding, and (3) slices for data subsetting." ) def __getattr__(self, item: str): try: return self.data[item] except KeyError: raise AttributeError def __getstate__(self): return {"data": self.data, "encodings": self._encodings} def __setstate__(self, state): if "data" in state: self.data = state["data"] if "encodings" in state: self._encodings = state["encodings"] # After this point: # Extended properties and methods only available for fast (Rust-based) tokenizers # provided by HuggingFace tokenizers library. @property def is_fast(self) -> bool: """ TOOD: ita i will rm this `bool`: Whether or not this BatchEncoding was created by a fast tokenizer. """ return self._encodings is not None @property def encodings(self) -> Optional[list[EncodingFast]]: """ `Optional[list[tokenizers.Encoding]]`: The list all encodings from the tokenization process. Returns `None` if the input was tokenized through Python (i.e., not a fast) tokenizer. """ return self._encodings def tokens(self, batch_index: int = 0) -> list[str]: """ Return the list of tokens (sub-parts of the input strings after word/subword splitting and before conversion to integer indices) at a given batch index (only works for the output of a fast tokenizer). Args: batch_index (`int`, *optional*, defaults to 0): The index to access in the batch. Returns: `list[str]`: The list of tokens at that index. """ if not self._encodings: raise ValueError( "tokens() is not available when using non-fast tokenizers (e.g. instance of a `XxxTokenizerFast`" " class)." ) return self._encodings[batch_index].tokens def sequence_ids(self, batch_index: int = 0) -> list[Optional[int]]: """ Return a list mapping the tokens to the id of their original sentences: - `None` for special tokens added around or between sequences, - `0` for tokens corresponding to words in the first sequence, - `1` for tokens corresponding to words in the second sequence when a pair of sequences was jointly encoded. Args: batch_index (`int`, *optional*, defaults to 0): The index to access in the batch. Returns: `list[Optional[int]]`: A list indicating the sequence id corresponding to each token. Special tokens added by the tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding sequence. """ if not self._encodings: raise ValueError( "sequence_ids() is not available when using non-fast tokenizers (e.g. instance of a `XxxTokenizerFast`" " class)." ) return self._encodings[batch_index].sequence_ids def word_ids(self, batch_index: int = 0) -> list[Optional[int]]: """ Return a list mapping the tokens to their actual word in the initial sentence for a fast tokenizer. Args: batch_index (`int`, *optional*, defaults to 0): The index to access in the batch. Returns: `list[Optional[int]]`: A list indicating the word corresponding to each token. Special tokens added by the tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding word (several tokens will be mapped to the same word index if they are parts of that word). """ if not self._encodings: raise ValueError( "word_ids() is not available when using non-fast tokenizers (e.g. instance of a `XxxTokenizerFast`" " class)." ) return self._encodings[batch_index].word_ids def token_to_sequence(self, batch_or_token_index: int, token_index: Optional[int] = None) -> int: """ Get the index of the sequence represented by the given token. In the general use case, this method returns `0` for a single sequence or the first sequence of a pair, and `1` for the second sequence of a pair Can be called as: - `self.token_to_sequence(token_index)` if batch size is 1 - `self.token_to_sequence(batch_index, token_index)` if batch size is greater than 1 This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e., words are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized words. Args: batch_or_token_index (`int`): Index of the sequence in the batch. If the batch only comprises one sequence, this can be the index of the token in the sequence. token_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the token in the sequence. Returns: `int`: Index of the word in the input sequence. """ if not self._encodings: raise ValueError("token_to_sequence() is not available when using Python based tokenizers") if token_index is not None: batch_index = batch_or_token_index else: batch_index = 0 token_index = batch_or_token_index if batch_index < 0: batch_index = self._batch_size + batch_index if token_index < 0: token_index = self._seq_len + token_index return self._encodings[batch_index].token_to_sequence(token_index) def token_to_word(self, batch_or_token_index: int, token_index: Optional[int] = None) -> int: """ Get the index of the word corresponding (i.e. comprising) to an encoded token in a sequence of the batch. Can be called as: - `self.token_to_word(token_index)` if batch size is 1 - `self.token_to_word(batch_index, token_index)` if batch size is greater than 1 This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e., words are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized words. Args: batch_or_token_index (`int`): Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the token in the sequence. token_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the token in the sequence. Returns: `int`: Index of the word in the input sequence. """ if not self._encodings: raise ValueError("token_to_word() is not available when using Python based tokenizers") if token_index is not None: batch_index = batch_or_token_index else: batch_index = 0 token_index = batch_or_token_index if batch_index < 0: batch_index = self._batch_size + batch_index if token_index < 0: token_index = self._seq_len + token_index return self._encodings[batch_index].token_to_word(token_index) def word_to_tokens( self, batch_or_word_index: int, word_index: Optional[int] = None, sequence_index: int = 0 ) -> Optional[TokenSpan]: """ Get the encoded token span corresponding to a word in a sequence of the batch. Token spans are returned as a [`~tokenization_utils_base.TokenSpan`] with: - **start** -- Index of the first token. - **end** -- Index of the token following the last token. Can be called as: - `self.word_to_tokens(word_index, sequence_index: int = 0)` if batch size is 1 - `self.word_to_tokens(batch_index, word_index, sequence_index: int = 0)` if batch size is greater or equal to 1 This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized words. Args: batch_or_word_index (`int`): Index of the sequence in the batch. If the batch only comprises one sequence, this can be the index of the word in the sequence. word_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the sequence. sequence_index (`int`, *optional*, defaults to 0): If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0 or 1) the provided word index belongs to. Returns: ([`~tokenization_utils_base.TokenSpan`], *optional*): Span of tokens in the encoded sequence. Returns `None` if no tokens correspond to the word. This can happen especially when the token is a special token that has been used to format the tokenization. For example when we add a class token at the very beginning of the tokenization. """ if not self._encodings: raise ValueError("word_to_tokens() is not available when using Python based tokenizers") if word_index is not None: batch_index = batch_or_word_index else: batch_index = 0 word_index = batch_or_word_index if batch_index < 0: batch_index = self._batch_size + batch_index if word_index < 0: word_index = self._seq_len + word_index span = self._encodings[batch_index].word_to_tokens(word_index, sequence_index) return TokenSpan(*span) if span is not None else None def token_to_chars(self, batch_or_token_index: int, token_index: Optional[int] = None) -> Optional[CharSpan]: """ Get the character span corresponding to an encoded token in a sequence of the batch. Character spans are returned as a [`~tokenization_utils_base.CharSpan`] with: - **start** -- Index of the first character in the original string associated to the token. - **end** -- Index of the character following the last character in the original string associated to the token. Can be called as: - `self.token_to_chars(token_index)` if batch size is 1 - `self.token_to_chars(batch_index, token_index)` if batch size is greater or equal to 1 Args: batch_or_token_index (`int`): Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the token in the sequence. token_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the token or tokens in the sequence. Returns: [`~tokenization_utils_base.CharSpan`]: Span of characters in the original string, or None, if the token (e.g. <s>, </s>) doesn't correspond to any chars in the origin string. """ if not self._encodings: raise ValueError("token_to_chars() is not available when using Python based tokenizers") if token_index is not None: batch_index = batch_or_token_index else: batch_index = 0 token_index = batch_or_token_index span_indices = self._encodings[batch_index].token_to_chars(token_index) return CharSpan(*span_indices) if span_indices is not None else None def char_to_token( self, batch_or_char_index: int, char_index: Optional[int] = None, sequence_index: int = 0 ) -> int: """ Get the index of the token in the encoded output comprising a character in the original string for a sequence of the batch. Can be called as: - `self.char_to_token(char_index)` if batch size is 1 - `self.char_to_token(batch_index, char_index)` if batch size is greater or equal to 1 This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized words. Args: batch_or_char_index (`int`): Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the word in the sequence char_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the sequence. sequence_index (`int`, *optional*, defaults to 0): If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0 or 1) the provided character index belongs to. Returns: `int`: Index of the token, or None if the char index refers to a whitespace only token and whitespace is trimmed with `trim_offsets=True`. """ if not self._encodings: raise ValueError("char_to_token() is not available when using Python based tokenizers") if char_index is not None: batch_index = batch_or_char_index else: batch_index = 0 char_index = batch_or_char_index return self._encodings[batch_index].char_to_token(char_index, sequence_index) def word_to_chars( self, batch_or_word_index: int, word_index: Optional[int] = None, sequence_index: int = 0 ) -> CharSpan: """ Get the character span in the original string corresponding to given word in a sequence of the batch. Character spans are returned as a CharSpan NamedTuple with: - start: index of the first character in the original string - end: index of the character following the last character in the original string Can be called as: - `self.word_to_chars(word_index)` if batch size is 1 - `self.word_to_chars(batch_index, word_index)` if batch size is greater or equal to 1 Args: batch_or_word_index (`int`): Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the word in the sequence word_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the sequence. sequence_index (`int`, *optional*, defaults to 0): If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0 or 1) the provided word index belongs to. Returns: `CharSpan` or `list[CharSpan]`: Span(s) of the associated character or characters in the string. CharSpan are NamedTuple with: - start: index of the first character associated to the token in the original string - end: index of the character following the last character associated to the token in the original string """ if not self._encodings: raise ValueError("word_to_chars() is not available when using Python based tokenizers") if word_index is not None: batch_index = batch_or_word_index else: batch_index = 0 word_index = batch_or_word_index return CharSpan(*(self._encodings[batch_index].word_to_chars(word_index, sequence_index))) def char_to_word(self, batch_or_char_index: int, char_index: Optional[int] = None, sequence_index: int = 0) -> int: """ Get the word in the original string corresponding to a character in the original string of a sequence of the batch. Can be called as: - `self.char_to_word(char_index)` if batch size is 1 - `self.char_to_word(batch_index, char_index)` if batch size is greater than 1 This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized words. Args: batch_or_char_index (`int`): Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the character in the original string. char_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the character in the original string. sequence_index (`int`, *optional*, defaults to 0): If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0 or 1) the provided character index belongs to. Returns: `int` or `list[int]`: Index or indices of the associated encoded token(s). """ if not self._encodings: raise ValueError("char_to_word() is not available when using Python based tokenizers") if char_index is not None: batch_index = batch_or_char_index else: batch_index = 0 char_index = batch_or_char_index return self._encodings[batch_index].char_to_word(char_index, sequence_index) def convert_to_tensors( self, tensor_type: Optional[Union[str, TensorType]] = None, prepend_batch_axis: bool = False ): """ Convert the inner content to tensors. Args: tensor_type (`str` or [`~utils.TensorType`], *optional*): The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If `None`, no modification is done. prepend_batch_axis (`int`, *optional*, defaults to `False`): Whether or not to add the batch dimension during the conversion. """ if tensor_type is None: return self # Convert to TensorType if not isinstance(tensor_type, TensorType): tensor_type = TensorType(tensor_type) if tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed.") import torch def as_tensor(value, dtype=None): if isinstance(value, list) and len(value) > 0 and isinstance(value[0], np.ndarray): return torch.from_numpy(np.array(value)) if len(flatten(value)) == 0 and dtype is None: dtype = torch.int64 return torch.tensor(value, dtype=dtype) is_tensor = torch.is_tensor elif tensor_type == TensorType.MLX: if not is_mlx_available(): raise ImportError("Unable to convert output to MLX tensors format, MLX is not installed.") import mlx.core as mx def as_tensor(value, dtype=None): if len(flatten(value)) == 0 and dtype is None: dtype = mx.int32 return mx.array(value, dtype=dtype) def is_tensor(obj): return isinstance(obj, mx.array) else: def as_tensor(value, dtype=None): if ( isinstance(value, (list, tuple)) and len(value) > 0 and isinstance(value[0], (list, tuple, np.ndarray)) ): value_lens = [len(val) for val in value] if len(set(value_lens)) > 1 and dtype is None: # we have a ragged list so handle explicitly value = as_tensor([np.asarray(val) for val in value], dtype=object) if len(flatten(value)) == 0 and dtype is None: dtype = np.int64 return np.asarray(value, dtype=dtype) is_tensor = is_numpy_array # Do the tensor conversion in batch for key, value in self.items(): try: if prepend_batch_axis: value = [value] if not is_tensor(value): tensor = as_tensor(value) # Removing this for now in favor of controlling the shape with `prepend_batch_axis` # # at-least2d # if tensor.ndim > 2: # tensor = tensor.squeeze(0) # elif tensor.ndim < 2: # tensor = tensor[None, :] self[key] = tensor except Exception as e: if key == "overflowing_tokens": raise ValueError( "Unable to create tensor returning overflowing tokens of different lengths. " "Please see if a fast version of this tokenizer is available to have this feature available." ) from e raise ValueError( "Unable to create tensor, you should probably activate truncation and/or padding with" " 'padding=True' 'truncation=True' to have batched tensors with the same length. Perhaps your" f" features (`{key}` in this case) have excessive nesting (inputs type `list` where type `int` is" " expected)." ) from e return self def to(self, device: Union[str, torch.device], *, non_blocking: bool = False) -> BatchEncoding: """ Send all values to device by calling `v.to(device, non_blocking=non_blocking)` (PyTorch only). Args: device (`str` or `torch.device`): The device to put the tensors on. non_blocking (`bool`): Whether to perform the copy asynchronously. Returns: [`BatchEncoding`]: The same instance after modification. """ requires_backends(self, ["torch"]) # This check catches things like APEX blindly calling "to" on all inputs to a module # Otherwise it passes the casts down and casts the LongTensor containing the token idxs # into a HalfTensor if isinstance(device, str) or is_torch_device(device) or isinstance(device, int): self.data = { k: v.to(device=device, non_blocking=non_blocking) if hasattr(v, "to") and callable(v.to) else v for k, v in self.data.items() } else:
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/trainer.py
src/transformers/trainer.py
# Copyright 2020-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. """ import contextlib import functools import glob import importlib.metadata import inspect import json import math import os import random import re import shutil import sys import tempfile import time import warnings from collections.abc import Callable, Iterator, Mapping from functools import partial from pathlib import Path from typing import TYPE_CHECKING, Any, Union # Integrations must be imported before ML frameworks: # ruff: isort: off from .integrations import ( get_reporting_integration_callbacks, ) # ruff: isort: on import huggingface_hub.utils as hf_hub_utils import numpy as np import safetensors.torch import torch import torch.distributed as dist from huggingface_hub import CommitInfo, ModelCard, create_repo, upload_folder from packaging import version from torch import nn from torch.utils.data import DataLoader, Dataset, IterableDataset, RandomSampler, SequentialSampler from . import __version__ from .configuration_utils import PreTrainedConfig from .data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator from .debug_utils import DebugOption, DebugUnderflowOverflow from .feature_extraction_sequence_utils import SequenceFeatureExtractor from .feature_extraction_utils import FeatureExtractionMixin from .hyperparameter_search import ALL_HYPERPARAMETER_SEARCH_BACKENDS, default_hp_search_backend from .image_processing_utils import BaseImageProcessor from .integrations.deepspeed import deepspeed_init, deepspeed_load_checkpoint, is_deepspeed_available from .integrations.peft import MIN_PEFT_VERSION from .integrations.tpu import tpu_spmd_dataloader from .modelcard import TrainingSummary from .modeling_utils import PreTrainedModel, unwrap_model from .models.auto.modeling_auto import ( MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_MAPPING_NAMES, ) from .optimization import Adafactor, get_scheduler from .processing_utils import ProcessorMixin from .pytorch_utils import ( is_torch_greater_or_equal_than_2_3, ) from .tokenization_utils_base import PreTrainedTokenizerBase from .trainer_callback import ( CallbackHandler, DefaultFlowCallback, ExportableState, PrinterCallback, ProgressCallback, TrainerCallback, TrainerControl, TrainerState, ) from .trainer_pt_utils import ( EvalLoopContainer, IterableDatasetShard, LabelSmoother, LayerWiseDummyOptimizer, LengthGroupedSampler, distributed_broadcast_scalars, distributed_concat, find_batch_size, get_model_param_count, get_module_class_from_name, get_parameter_names, nested_detach, nested_xla_mesh_reduce, reissue_pt_warnings, remove_dummy_checkpoint, set_rng_state_for_device, ) from .trainer_utils import ( PREFIX_CHECKPOINT_DIR, BestRun, EvalLoopOutput, EvalPrediction, HPSearchBackend, HubStrategy, PredictionOutput, RemoveColumnsCollator, SaveStrategy, TrainerMemoryTracker, TrainOutput, check_target_module_exists, default_compute_objective, denumpify_detensorize, enable_full_determinism, find_executable_batch_size, get_last_checkpoint, has_length, load_sharded_checkpoint, neftune_post_forward_hook, number_of_arguments, seed_worker, set_seed, speed_metrics, ) from .training_args import OptimizerNames, ParallelMode, TrainingArguments from .utils import ( ADAPTER_CONFIG_NAME, ADAPTER_SAFE_WEIGHTS_NAME, ADAPTER_WEIGHTS_NAME, CONFIG_NAME, GENERATION_CONFIG_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, XLA_FSDPV2_MIN_VERSION, PushInProgress, PushToHubMixin, can_return_loss, check_torch_load_is_safe, find_labels, is_accelerate_available, is_apollo_torch_available, is_bitsandbytes_available, is_datasets_available, is_galore_torch_available, is_grokadamw_available, is_in_notebook, is_liger_kernel_available, is_lomo_available, is_peft_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_schedulefree_available, is_torch_hpu_available, is_torch_mlu_available, is_torch_musa_available, is_torch_neuroncore_available, is_torch_npu_available, is_torch_optimi_available, is_torch_xla_available, is_torchao_available, logging, strtobool, ) from .utils.import_utils import requires from .utils.quantization_config import QuantizationMethod DEFAULT_CALLBACKS = [DefaultFlowCallback] DEFAULT_PROGRESS_CALLBACK = ProgressCallback if is_in_notebook(): from .utils.notebook import NotebookProgressCallback DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback if is_datasets_available(): import datasets if is_torch_xla_available(): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met import torch_xla.runtime as xr from torch_xla import __version__ as XLA_VERSION IS_XLA_FSDPV2_POST_2_2 = version.parse(XLA_VERSION) >= version.parse(XLA_FSDPV2_MIN_VERSION) if IS_XLA_FSDPV2_POST_2_2: import torch_xla.distributed.spmd as xs else: IS_XLA_FSDPV2_POST_2_2 = False if is_sagemaker_mp_enabled(): import smdistributed.modelparallel.torch as smp from .trainer_pt_utils import smp_forward_backward, smp_forward_only, smp_gather, smp_nested_concat if is_peft_available(): from peft import PeftMixedModel, PeftModel if is_accelerate_available(): from accelerate import Accelerator, skip_first_batches from accelerate.state import AcceleratorState from accelerate.utils import ( DataLoaderConfiguration, DistributedDataParallelKwargs, DistributedType, load_fsdp_model, load_fsdp_optimizer, release_memory, save_fsdp_model, save_fsdp_optimizer, ) from accelerate.utils.memory import clear_device_cache if is_deepspeed_available(): from accelerate.utils import DeepSpeedSchedulerWrapper def _is_peft_model(model): if is_peft_available(): classes_to_check = (PeftModel, PeftMixedModel) return isinstance(model, classes_to_check) return False def _get_fsdp_ckpt_kwargs(): if "adapter_only" in list(inspect.signature(save_fsdp_model).parameters): return {"adapter_only": True} else: return {} def safe_globals(): # Starting from version 2.4 PyTorch introduces a check for the objects loaded # with torch.load(weights_only=True). Starting from 2.6 weights_only=True becomes # a default and requires allowlisting of objects being loaded. # See: https://github.com/pytorch/pytorch/pull/137602 # See: https://pytorch.org/docs/stable/notes/serialization.html#torch.serialization.add_safe_globals # See: https://github.com/huggingface/accelerate/pull/3036 if version.parse(torch.__version__).release < version.parse("2.6").release: return contextlib.nullcontext() np_core = np._core if version.parse(np.__version__) >= version.parse("2.0.0") else np.core allowlist = [np_core.multiarray._reconstruct, np.ndarray, np.dtype] # numpy >1.25 defines numpy.dtypes.UInt32DType, but below works for # all versions of numpy allowlist += [type(np.dtype(np.uint32))] return torch.serialization.safe_globals(allowlist) if TYPE_CHECKING: import optuna logger = logging.get_logger(__name__) # Name of the files used for checkpointing TRAINING_ARGS_NAME = "training_args.bin" TRAINER_STATE_NAME = "trainer_state.json" OPTIMIZER_NAME = "optimizer.pt" SCALER_NAME = "scaler.pt" OPTIMIZER_NAME_BIN = "optimizer.bin" SCHEDULER_NAME = "scheduler.pt" FSDP_MODEL_NAME = "pytorch_model_fsdp" @requires( backends=( "torch", "accelerate", ) ) class Trainer: """ Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers. Args: model ([`PreTrainedModel`] or `torch.nn.Module`, *optional*): The model to train, evaluate or use for predictions. If not provided, a `model_init` must be passed. <Tip> [`Trainer`] is optimized to work with the [`PreTrainedModel`] provided by the library. You can still use your own models defined as `torch.nn.Module` as long as they work the same way as the 🤗 Transformers models. </Tip> args ([`TrainingArguments`], *optional*): The arguments to tweak for training. Will default to a basic instance of [`TrainingArguments`] with the `output_dir` set to a directory named *tmp_trainer* in the current directory if not provided. data_collator (`DataCollator`, *optional*): The function to use to form a batch from a list of elements of `train_dataset` or `eval_dataset`. Will default to [`default_data_collator`] if no `processing_class` is provided, an instance of [`DataCollatorWithPadding`] otherwise if the processing_class is a feature extractor or tokenizer. train_dataset (Union[`torch.utils.data.Dataset`, `torch.utils.data.IterableDataset`, `datasets.Dataset`], *optional*): The dataset to use for training. If it is a [`~datasets.Dataset`], columns not accepted by the `model.forward()` method are automatically removed. Note that if it's a `torch.utils.data.IterableDataset` with some randomization and you are training in a distributed fashion, your iterable dataset should either use a internal attribute `generator` that is a `torch.Generator` for the randomization that must be identical on all processes (and the Trainer will manually set the seed of this `generator` at each epoch) or have a `set_epoch()` method that internally sets the seed of the RNGs used. eval_dataset (Union[`torch.utils.data.Dataset`, dict[str, `torch.utils.data.Dataset`], `datasets.Dataset`]), *optional*): The dataset to use for evaluation. If it is a [`~datasets.Dataset`], columns not accepted by the `model.forward()` method are automatically removed. If it is a dictionary, it will evaluate on each dataset prepending the dictionary key to the metric name. processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*): Processing class used to process the data. If provided, will be used to automatically process the inputs for the model, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model. model_init (`Callable[[], PreTrainedModel]`, *optional*): A function that instantiates the model to be used. If provided, each call to [`~Trainer.train`] will start from a new instance of the model as given by this function. The function may have zero argument, or a single one containing the optuna/Ray Tune trial object, to be able to choose different architectures according to hyper parameters (such as layer count, sizes of inner layers, dropout probabilities etc). compute_loss_func (`Callable`, *optional*): A function that accepts the raw model outputs, labels, and the number of items in the entire accumulated batch (batch_size * gradient_accumulation_steps) and returns the loss. For example, see the default [loss function](https://github.com/huggingface/transformers/blob/052e652d6d53c2b26ffde87e039b723949a53493/src/transformers/trainer.py#L3618) used by [`Trainer`]. compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*): The function that will be used to compute metrics at evaluation. Must take a [`EvalPrediction`] and return a dictionary string to metric values. *Note* When passing TrainingArgs with `batch_eval_metrics` set to `True`, your compute_metrics function must take a boolean `compute_result` argument. This will be triggered after the last eval batch to signal that the function needs to calculate and return the global summary statistics rather than accumulating the batch-level statistics callbacks (List of [`TrainerCallback`], *optional*): A list of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in [here](callback). If you want to remove one of the default callbacks used, use the [`Trainer.remove_callback`] method. optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`): A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`. optimizer_cls_and_kwargs (`tuple[Type[torch.optim.Optimizer], dict[str, Any]]`, *optional*): A tuple containing the optimizer class and keyword arguments to use. Overrides `optim` and `optim_args` in `args`. Incompatible with the `optimizers` argument. Unlike `optimizers`, this argument avoids the need to place model parameters on the correct devices before initializing the Trainer. preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*): A function that preprocess the logits right before caching them at each evaluation step. Must take two tensors, the logits and the labels, and return the logits once processed as desired. The modifications made by this function will be reflected in the predictions received by `compute_metrics`. Note that the labels (second parameter) will be `None` if the dataset does not have them. Important attributes: - **model** -- Always points to the core model. If using a transformers model, it will be a [`PreTrainedModel`] subclass. - **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the original model. This is the model that should be used for the forward pass. For example, under `DeepSpeed`, the inner model is wrapped in `DeepSpeed` and then again in `torch.nn.DistributedDataParallel`. If the inner model hasn't been wrapped, then `self.model_wrapped` is the same as `self.model`. - **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from data parallelism, this means some of the model layers are split on different GPUs). - **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set to `False` if model parallel or deepspeed is used, or if the default `TrainingArguments.place_model_on_device` is overridden to return `False` . - **is_in_train** -- Whether or not a model is currently running `train` (e.g. when `evaluate` is called while in `train`) """ # Those are used as methods of the Trainer in examples. from .trainer_pt_utils import _get_learning_rate, log_metrics, metrics_format, save_metrics, save_state def __init__( self, model: PreTrainedModel | nn.Module | None = None, args: TrainingArguments | None = None, data_collator: DataCollator | None = None, train_dataset: Union[Dataset, IterableDataset, "datasets.Dataset"] | None = None, eval_dataset: Union[Dataset, dict[str, Dataset], "datasets.Dataset"] | None = None, processing_class: PreTrainedTokenizerBase | BaseImageProcessor | FeatureExtractionMixin | ProcessorMixin | None = None, model_init: Callable[..., PreTrainedModel] | None = None, compute_loss_func: Callable | None = None, compute_metrics: Callable[[EvalPrediction], dict] | None = None, callbacks: list[TrainerCallback] | None = None, optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None), optimizer_cls_and_kwargs: tuple[type[torch.optim.Optimizer], dict[str, Any]] | None = None, preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None, ): if args is None: output_dir = "tmp_trainer" logger.info(f"No `TrainingArguments` passed, using `output_dir={output_dir}`.") args = TrainingArguments(output_dir=output_dir) if args.batch_eval_metrics and compute_metrics is not None: if "compute_result" not in inspect.signature(compute_metrics).parameters: raise ValueError( "When using `batch_eval_metrics`, your `compute_metrics` function must take a `compute_result`" " boolean argument which will be triggered after the last batch of the eval set to signal that the" " summary statistics should be returned by the function." ) if args.eval_strategy is not None and args.eval_strategy != "no" and eval_dataset is None: raise ValueError( f"You have set `args.eval_strategy` to {args.eval_strategy} but you didn't pass an `eval_dataset` to `Trainer`. Either set `args.eval_strategy` to `no` or pass an `eval_dataset`. " ) if args.save_strategy == SaveStrategy.BEST or args.load_best_model_at_end: if args.metric_for_best_model is None: raise ValueError( "`args.metric_for_best_model` must be provided when using 'best' save_strategy or if `args.load_best_model_at_end` is set to `True`." ) self.args = args self.compute_loss_func = compute_loss_func # Seed must be set before instantiating the model when using model enable_full_determinism(self.args.seed) if self.args.full_determinism else set_seed(self.args.seed) self.hp_name = None self.deepspeed = None self.is_in_train = False self.model = model self.create_accelerator_and_postprocess() # memory metrics - must set up as early as possible self._memory_tracker = TrainerMemoryTracker(self.args.skip_memory_metrics) self._memory_tracker.start() # set the correct log level depending on the node log_level = args.get_process_log_level() logging.set_verbosity(log_level) # force device and distributed setup init explicitly args._setup_devices if model is None: if model_init is not None: self.model_init = model_init model = self.call_model_init() else: raise RuntimeError("`Trainer` requires either a `model` or `model_init` argument") else: if model_init is not None: warnings.warn( "`Trainer` requires either a `model` or `model_init` argument, but not both. `model_init` will" " overwrite your model when calling the `train` method. This will become a fatal error in the next" " release.", FutureWarning, ) self.model_init = model_init if model.__class__.__name__ in MODEL_MAPPING_NAMES: raise ValueError( f"The model you have picked ({model.__class__.__name__}) cannot be used as is for training: it only " "computes hidden states and does not accept any labels. You should choose a model with a head " "suitable for your task like any of the `AutoModelForXxx` listed at " "https://huggingface.co/docs/transformers/model_doc/auto" ) self.is_model_parallel = False if getattr(model, "hf_device_map", None) is not None: devices = [device for device in set(model.hf_device_map.values()) if device not in ["cpu", "disk"]] if len(devices) > 1: self.is_model_parallel = True elif len(devices) == 1: self.is_model_parallel = self.args.device != torch.device(devices[0]) if self.args.use_liger_kernel: if is_liger_kernel_available(): from liger_kernel.transformers import _apply_liger_kernel_to_instance # Prepare kernel config - use provided config or default (empty dict for default behavior) kernel_config = self.args.liger_kernel_config if self.args.liger_kernel_config is not None else {} if isinstance(model, PreTrainedModel): # Patch the model with liger kernels. Use the specified or default kernel configurations. _apply_liger_kernel_to_instance(model=model, **kernel_config) elif hasattr(model, "get_base_model") and isinstance(model.get_base_model(), PreTrainedModel): # Patch the base model with liger kernels where model is a PeftModel. Use the specified or default kernel configurations. _apply_liger_kernel_to_instance(model=model.get_base_model(), **kernel_config) else: logger.warning( "The model is not an instance of PreTrainedModel. No liger kernels will be applied." ) else: raise ImportError( "You have set `use_liger_kernel` to `True` but liger-kernel >= 0.3.0 is not available. " "Please install it with `pip install liger-kernel`" ) _is_quantized_and_base_model = getattr(model, "is_quantized", False) and not getattr( model, "_hf_peft_config_loaded", False ) _quantization_method_supports_training = ( getattr(model, "hf_quantizer", None) is not None and model.hf_quantizer.is_trainable ) _is_model_quantized_and_qat_trainable = getattr(model, "hf_quantizer", None) is not None and getattr( model.hf_quantizer, "is_qat_trainable", False ) # Filter out quantized + compiled models if _is_quantized_and_base_model and hasattr(model, "_orig_mod"): raise ValueError( "You cannot fine-tune quantized model with `torch.compile()` make sure to pass a non-compiled model when fine-tuning a quantized model with PEFT" ) # At this stage the model is already loaded if _is_quantized_and_base_model and not _is_peft_model(model) and not _is_model_quantized_and_qat_trainable: raise ValueError( "You cannot perform fine-tuning on purely quantized models. Please attach trainable adapters on top of" " the quantized model to correctly perform fine-tuning. Please see: https://huggingface.co/docs/transformers/peft" " for more details" ) elif _is_quantized_and_base_model and not _quantization_method_supports_training: raise ValueError( f"The model you are trying to fine-tune is quantized with {model.hf_quantizer.quantization_config.quant_method}" " but that quantization method do not support training. Please open an issue on GitHub: https://github.com/huggingface/transformers" f" to request the support for training support for {model.hf_quantizer.quantization_config.quant_method}" ) self.is_fsdp_xla_enabled = args.fsdp_config["xla"] if len(args.fsdp) > 0: if self.is_deepspeed_enabled: raise ValueError( "Using --fsdp xxx together with --deepspeed is not possible, deactivate one of those flags." ) if not args.fsdp_config["xla"] and args.parallel_mode != ParallelMode.DISTRIBUTED: raise ValueError("Using fsdp only works in distributed training.") # one place to sort out whether to place the model on device or not # postpone switching model to cuda when: # 1. MP - since we are trying to fit a much bigger than 1 gpu model # 2. fp16-enabled DeepSpeed loads the model in half the size and it doesn't need .to() anyway, # and we only use deepspeed for training at the moment # 3. full bf16 or fp16 eval - since the model needs to be cast to the right dtype first # 4. FSDP - same as MP self.place_model_on_device = args.place_model_on_device if ( self.is_model_parallel or self.is_deepspeed_enabled or ((args.fp16_full_eval or args.bf16_full_eval) and not args.do_train) or self.is_fsdp_xla_enabled or self.is_fsdp_enabled ): self.place_model_on_device = False default_collator = ( DataCollatorWithPadding(processing_class) if processing_class is not None and isinstance(processing_class, (PreTrainedTokenizerBase, SequenceFeatureExtractor)) else default_data_collator ) self.data_collator = data_collator if data_collator is not None else default_collator self.train_dataset = train_dataset self.eval_dataset = eval_dataset self.processing_class = processing_class # Bnb Quantized models doesn't support `.to` operation. if ( self.place_model_on_device and getattr(model, "quantization_method", None) != QuantizationMethod.BITS_AND_BYTES ): self._move_model_to_device(model, args.device) # Force n_gpu to 1 to avoid DataParallel as MP will manage the GPUs if self.is_model_parallel: self.args._n_gpu = 1 # later use `self.model is self.model_wrapped` to check if it's wrapped or not self.model_wrapped = model self.model = model # Just in case the model was wrapped outside of the `Trainer` unwrapped_model = self.accelerator.unwrap_model(model) # We also unwrap peft model if _is_peft_model(unwrapped_model): if hasattr(unwrapped_model, "get_base_model"): unwrapped_model = unwrapped_model.get_base_model() elif hasattr(unwrapped_model, "base_model") and hasattr(unwrapped_model.base_model, "model"): unwrapped_model = unwrapped_model.base_model.model else: raise AttributeError("Cannot extract base model safely from this PEFT wrapper.") # Check if the model has explicit setup for loss kwargs, # if not, check if `**kwargs` are in model.forward if hasattr(unwrapped_model, "accepts_loss_kwargs"): self.model_accepts_loss_kwargs = unwrapped_model.accepts_loss_kwargs else: forward_params = inspect.signature(unwrapped_model.forward).parameters self.model_accepts_loss_kwargs = any( k.kind == inspect.Parameter.VAR_KEYWORD for k in forward_params.values() ) # Override for Sequence Parallelism: SP computes its own good_tokens count, so skip num_items_in_batch calculation pc = getattr(self.accelerator, "parallelism_config", None) if pc is not None and pc.sp_backend == "deepspeed" and pc.sp_enabled: self.model_accepts_loss_kwargs = False self.neftune_noise_alpha = args.neftune_noise_alpha self.compute_metrics = compute_metrics self.preprocess_logits_for_metrics = preprocess_logits_for_metrics self.optimizer, self.lr_scheduler = optimizers self.optimizer_cls_and_kwargs = optimizer_cls_and_kwargs if self.optimizer_cls_and_kwargs is not None and self.optimizer is not None: raise RuntimeError("Passing both `optimizers` and `optimizer_cls_and_kwargs` arguments is incompatible.") if model_init is not None and (self.optimizer is not None or self.lr_scheduler is not None): raise RuntimeError( "Passing a `model_init` is incompatible with providing the `optimizers` argument. " "You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method." ) if is_torch_xla_available() and self.optimizer is not None: for param in self.model.parameters(): model_device = param.device break for param_group in self.optimizer.param_groups: if len(param_group["params"]) > 0: optimizer_device = param_group["params"][0].device break if model_device != optimizer_device: raise ValueError( "The model and the optimizer parameters are not on the same device, which probably means you" " created an optimizer around your model **before** putting on the device and passing it to the" " `Trainer`. Make sure the lines `import torch_xla.core.xla_model as xm` and" " `model.to(xm.xla_device())` is performed before the optimizer creation in your script." ) if (self.is_fsdp_xla_enabled or self.is_fsdp_enabled) and ( self.optimizer is not None or self.lr_scheduler is not None ): raise RuntimeError( "Passing `optimizers` is not allowed if PyTorch FSDP is enabled. " "You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method." ) default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to) # Add JIT checkpoint callback if enabled if self.args.enable_jit_checkpoint: from .trainer_jit_checkpoint import JITCheckpointCallback jit_callback = JITCheckpointCallback() default_callbacks = default_callbacks + [jit_callback] # Set trainer reference for JIT callback after initialization jit_callback.set_trainer(self) callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks self.callback_handler = CallbackHandler( callbacks, self.model, self.processing_class, self.optimizer, self.lr_scheduler ) self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK) # Will be set to True by `self._setup_loggers()` on first call to `self.log()`. self._loggers_initialized = False # Create distant repo and output directory if needed self.hub_model_id = None if self.args.push_to_hub: self.init_hf_repo() if self.args.should_save: os.makedirs(self.args.output_dir, exist_ok=True) if not callable(self.data_collator) and callable(getattr(self.data_collator, "collate_batch", None)): raise TypeError("The `data_collator` should be a simple callable (function, class with `__call__`).") if args.max_steps > 0 and args.num_train_epochs > 0: logger.info("max_steps is given, it will override any value given in num_train_epochs") if train_dataset is not None and not has_length(train_dataset) and args.max_steps <= 0: raise ValueError( "The train_dataset does not implement __len__, max_steps has to be specified. " "The number of steps needs to be known in advance for the learning rate scheduler." ) if ( train_dataset is not None and isinstance(train_dataset, torch.utils.data.IterableDataset) and args.group_by_length ): raise ValueError("the `--group_by_length` option is only available for `Dataset`, not `IterableDataset") self._signature_columns = None
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/modeling_outputs.py
src/transformers/modeling_outputs.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from dataclasses import dataclass from typing import Optional import torch from .cache_utils import Cache, EncoderDecoderCache from .utils import ModelOutput @dataclass class BaseModelOutput(ModelOutput): """ Base class for model's outputs, with potential hidden states and attentions. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ last_hidden_state: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass class BaseModelOutputWithNoAttention(ModelOutput): """ Base class for model's outputs, with potential hidden states. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Sequence of hidden-states at the output of the last layer of the model. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, num_channels, height, width)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. """ last_hidden_state: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass class BaseModelOutputWithPooling(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`): Last layer hidden-state of the first token of the sequence (classification token) after further processing through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns the classification token after processing through a linear layer and a tanh activation function. The linear layer weights are trained from the next sentence prediction (classification) objective during pretraining. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ last_hidden_state: Optional[torch.FloatTensor] = None pooler_output: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass class BaseModelOutputWithPoolingAndNoAttention(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Sequence of hidden-states at the output of the last layer of the model. pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`): Last layer hidden-state after a pooling operation on the spatial dimensions. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, num_channels, height, width)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. """ last_hidden_state: Optional[torch.FloatTensor] = None pooler_output: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass class BaseModelOutputWithPast(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, hidden_size)` is output. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ last_hidden_state: Optional[torch.FloatTensor] = None past_key_values: Optional[Cache] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass class BaseModelOutputWithCrossAttentions(ModelOutput): """ Base class for model's outputs, with potential hidden states and attentions. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. """ last_hidden_state: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None cross_attentions: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass class BaseModelOutputWithPoolingAndCrossAttentions(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`): Last layer hidden-state of the first token of the sequence (classification token) after further processing through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns the classification token after processing through a linear layer and a tanh activation function. The linear layer weights are trained from the next sentence prediction (classification) objective during pretraining. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. """ last_hidden_state: Optional[torch.FloatTensor] = None pooler_output: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None past_key_values: Optional[Cache] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None cross_attentions: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass class BaseModelOutputWithPastAndCrossAttentions(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, hidden_size)` is output. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. """ last_hidden_state: Optional[torch.FloatTensor] = None past_key_values: Optional[Cache] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None cross_attentions: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass class MoECausalLMOutputWithPast(ModelOutput): """ Base class for causal language model (or autoregressive) outputs as well as Mixture of Expert's router hidden states terms, to train a MoE model. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. z_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided): z_loss for the sparse modules. aux_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided): aux_loss for the sparse modules. router_logits (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_logits=True` is passed or when `config.add_router_probs=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`. Router logits of the encoder model, useful to compute the auxiliary loss and the z_loss for the sparse modules. """ loss: Optional[torch.FloatTensor] = None logits: Optional[torch.FloatTensor] = None past_key_values: Optional[Cache] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None z_loss: Optional[torch.FloatTensor] = None aux_loss: Optional[torch.FloatTensor] = None router_logits: Optional[tuple[torch.FloatTensor]] = None @dataclass class MoEModelOutput(ModelOutput): """ Base class for model's outputs, with potential hidden states and attentions. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. router_probs (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_probs=True` and `config.add_router_probs=True` is passed or when `config.output_router_probs=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`. Raw router probabilities that are computed by MoE routers, these terms are used to compute the auxiliary loss and the z_loss for Mixture of Experts models. """ last_hidden_state: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None router_probs: Optional[tuple[torch.FloatTensor]] = None router_logits: Optional[tuple[torch.FloatTensor]] = None @dataclass class MoeModelOutputWithPast(ModelOutput): """ Base class for model's outputs, with potential hidden states and attentions. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. router_logits (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_probs=True` and `config.add_router_probs=True` is passed or when `config.output_router_probs=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`. Raw router logtis (post-softmax) that are computed by MoE routers, these terms are used to compute the auxiliary loss for Mixture of Experts models. """ last_hidden_state: Optional[torch.FloatTensor] = None past_key_values: Optional[Cache] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None router_logits: Optional[tuple[torch.FloatTensor]] = None @dataclass class MoeCausalLMOutputWithPast(ModelOutput): """ Base class for causal language model (or autoregressive) with mixture of experts outputs. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). aux_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided): aux_loss for the sparse modules. router_logits (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_probs=True` and `config.add_router_probs=True` is passed or when `config.output_router_probs=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`. Raw router logtis (post-softmax) that are computed by MoE routers, these terms are used to compute the auxiliary loss for Mixture of Experts models. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ loss: Optional[torch.FloatTensor] = None aux_loss: Optional[torch.FloatTensor] = None logits: Optional[torch.FloatTensor] = None past_key_values: Optional[Cache] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None router_logits: Optional[tuple[torch.FloatTensor]] = None @dataclass class MoEModelOutputWithPastAndCrossAttentions(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding) as well as Mixture of Expert's router hidden states terms, to train a MoE model. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, hidden_size)` is output. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. router_probs (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_probs=True` and `config.add_router_probs=True` is passed or when `config.output_router_probs=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`. Raw router probabilities that are computed by MoE routers, these terms are used to compute the auxiliary loss and the z_loss for Mixture of Experts models. """ last_hidden_state: Optional[torch.FloatTensor] = None past_key_values: Optional[Cache] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None cross_attentions: Optional[tuple[torch.FloatTensor, ...]] = None router_probs: Optional[tuple[torch.FloatTensor]] = None router_logits: Optional[tuple[torch.FloatTensor]] = None @dataclass class Seq2SeqModelOutput(ModelOutput): """ Base class for model encoder's outputs that also contains : pre-computed hidden states that can speed up sequential decoding. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the decoder of the model. If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, hidden_size)` is output. past_key_values (`EncoderDecoderCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.EncoderDecoderCache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/testing_utils.py
src/transformers/testing_utils.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import ast import collections import contextlib import copy import doctest import functools import gc import importlib import inspect import json import logging import multiprocessing import os import re import shlex import shutil import subprocess import sys import tempfile import threading import time import traceback import types import unittest from collections import UserDict, defaultdict from collections.abc import Callable, Generator, Iterable, Iterator, Mapping from contextlib import contextmanager from dataclasses import MISSING, fields from functools import cache, wraps from io import StringIO from pathlib import Path from typing import TYPE_CHECKING, Any from unittest import mock from unittest.mock import patch import httpx import urllib3 from huggingface_hub import create_repo, delete_repo from packaging import version from transformers import logging as transformers_logging if TYPE_CHECKING: from .trainer import Trainer else: Trainer = Any # type: ignore from .integrations import ( is_clearml_available, is_optuna_available, is_ray_available, is_swanlab_available, is_tensorboard_available, is_trackio_available, is_wandb_available, ) from .integrations.deepspeed import is_deepspeed_available from .utils import ( ACCELERATE_MIN_VERSION, GGUF_MIN_VERSION, SAFE_WEIGHTS_INDEX_NAME, TRITON_MIN_VERSION, WEIGHTS_INDEX_NAME, is_accelerate_available, is_apex_available, is_apollo_torch_available, is_aqlm_available, is_auto_round_available, is_av_available, is_bitsandbytes_available, is_bs4_available, is_compressed_tensors_available, is_cv2_available, is_cython_available, is_decord_available, is_detectron2_available, is_essentia_available, is_faiss_available, is_fbgemm_gpu_available, is_flash_attn_2_available, is_flash_attn_3_available, is_flute_available, is_fp_quant_available, is_fsdp_available, is_ftfy_available, is_g2p_en_available, is_galore_torch_available, is_gguf_available, is_gptqmodel_available, is_grokadamw_available, is_hadamard_available, is_hqq_available, is_huggingface_hub_greater_or_equal, is_ipex_available, is_jinja_available, is_jmespath_available, is_jumanpp_available, is_kernels_available, is_levenshtein_available, is_librosa_available, is_liger_kernel_available, is_lomo_available, is_mistral_common_available, is_natten_available, is_nltk_available, is_numba_available, is_onnx_available, is_openai_available, is_optimum_available, is_optimum_quanto_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_pretty_midi_available, is_psutil_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_quark_available, is_qutlass_available, is_rjieba_available, is_sacremoses_available, is_schedulefree_available, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_spacy_available, is_speech_available, is_spqr_available, is_sudachi_available, is_sudachi_projection_available, is_tiktoken_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bf16_available_on_device, is_torch_fp16_available_on_device, is_torch_greater_or_equal, is_torch_hpu_available, is_torch_mlu_available, is_torch_neuroncore_available, is_torch_npu_available, is_torch_optimi_available, is_torch_tensorrt_fx_available, is_torch_tf32_available, is_torch_xla_available, is_torch_xpu_available, is_torchao_available, is_torchaudio_available, is_torchcodec_available, is_torchvision_available, is_triton_available, is_vision_available, is_vptq_available, strtobool, ) if is_accelerate_available(): from accelerate.state import AcceleratorState, PartialState from accelerate.utils.imports import is_fp8_available if is_pytest_available(): from _pytest.doctest import ( Module, _get_checker, _get_continue_on_failure, _get_runner, _is_mocked, _patch_unwrap_mock_aware, get_optionflags, ) from _pytest.outcomes import skip from _pytest.pathlib import import_path from pytest import DoctestItem else: Module = object DoctestItem = object SMALL_MODEL_IDENTIFIER = "julien-c/bert-xsmall-dummy" DUMMY_UNKNOWN_IDENTIFIER = "julien-c/dummy-unknown" DUMMY_DIFF_TOKENIZER_IDENTIFIER = "julien-c/dummy-diff-tokenizer" # Used to test Auto{Config, Model, Tokenizer} model_type detection. # Used to test the hub USER = "__DUMMY_TRANSFORMERS_USER__" ENDPOINT_STAGING = "https://hub-ci.huggingface.co" # Not critical, only usable on the sandboxed CI instance. TOKEN = "hf_94wBhPGp6KrrTH3KDchhKpRxZwd6dmHWLL" # Used in CausalLMModelTester (and related classes/methods) to infer the common model classes from the base model class _COMMON_MODEL_NAMES_MAP = { "config_class": "Config", "causal_lm_class": "ForCausalLM", "question_answering_class": "ForQuestionAnswering", "sequence_classification_class": "ForSequenceClassification", "token_classification_class": "ForTokenClassification", } if is_torch_available(): import torch from safetensors.torch import load_file from .modeling_utils import FLASH_ATTN_KERNEL_FALLBACK, PreTrainedModel IS_ROCM_SYSTEM = torch.version.hip is not None IS_CUDA_SYSTEM = torch.version.cuda is not None IS_XPU_SYSTEM = getattr(torch.version, "xpu", None) is not None IS_NPU_SYSTEM = getattr(torch, "npu", None) is not None else: IS_ROCM_SYSTEM = False IS_CUDA_SYSTEM = False IS_XPU_SYSTEM = False IS_NPU_SYSTEM = False logger = transformers_logging.get_logger(__name__) def parse_flag_from_env(key, default=False): try: value = os.environ[key] except KeyError: # KEY isn't set, default to `default`. _value = default else: # KEY is set, convert it to True or False. try: _value = strtobool(value) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f"If set, {key} must be yes or no.") return _value def parse_int_from_env(key, default=None): try: value = os.environ[key] except KeyError: _value = default else: try: _value = int(value) except ValueError: raise ValueError(f"If set, {key} must be a int.") return _value _run_slow_tests = parse_flag_from_env("RUN_SLOW", default=False) _run_flaky_tests = parse_flag_from_env("RUN_FLAKY", default=True) _run_custom_tokenizers = parse_flag_from_env("RUN_CUSTOM_TOKENIZERS", default=False) _run_staging = parse_flag_from_env("HUGGINGFACE_CO_STAGING", default=False) _run_pipeline_tests = parse_flag_from_env("RUN_PIPELINE_TESTS", default=True) _run_agent_tests = parse_flag_from_env("RUN_AGENT_TESTS", default=False) _run_training_tests = parse_flag_from_env("RUN_TRAINING_TESTS", default=True) def is_staging_test(test_case): """ Decorator marking a test as a staging test. Those tests will run using the staging environment of huggingface.co instead of the real model hub. """ if not _run_staging: return unittest.skip(reason="test is staging test")(test_case) else: try: import pytest # We don't need a hard dependency on pytest in the main library except ImportError: return test_case else: return pytest.mark.is_staging_test()(test_case) def is_pipeline_test(test_case): """ Decorator marking a test as a pipeline test. If RUN_PIPELINE_TESTS is set to a falsy value, those tests will be skipped. """ if not _run_pipeline_tests: return unittest.skip(reason="test is pipeline test")(test_case) else: try: import pytest # We don't need a hard dependency on pytest in the main library except ImportError: return test_case else: return pytest.mark.is_pipeline_test()(test_case) def is_agent_test(test_case): """ Decorator marking a test as an agent test. If RUN_TOOL_TESTS is set to a falsy value, those tests will be skipped. """ if not _run_agent_tests: return unittest.skip(reason="test is an agent test")(test_case) else: try: import pytest # We don't need a hard dependency on pytest in the main library except ImportError: return test_case else: return pytest.mark.is_agent_test()(test_case) def is_training_test(test_case): """ Decorator marking a test as a training test. If RUN_TRAINING_TESTS is set to a falsy value, those tests will be skipped. """ if not _run_training_tests: return unittest.skip(reason="test is training test")(test_case) else: try: import pytest # We don't need a hard dependency on pytest in the main library except ImportError: return test_case else: return pytest.mark.is_training_test()(test_case) def slow(test_case): """ Decorator marking a test as slow. Slow tests are skipped by default. Set the RUN_SLOW environment variable to a truthy value to run them. """ return unittest.skipUnless(_run_slow_tests, "test is slow")(test_case) def tooslow(test_case): """ Decorator marking a test as too slow. Slow tests are skipped while they're in the process of being fixed. No test should stay tagged as "tooslow" as these will not be tested by the CI. """ return unittest.skip(reason="test is too slow")(test_case) def skip_if_not_implemented(test_func): @functools.wraps(test_func) def wrapper(*args, **kwargs): try: return test_func(*args, **kwargs) except NotImplementedError as e: raise unittest.SkipTest(f"Test skipped due to NotImplementedError: {e}") return wrapper def apply_skip_if_not_implemented(cls): """ Class decorator to apply @skip_if_not_implemented to all test methods. """ for attr_name in dir(cls): if attr_name.startswith("test_"): attr = getattr(cls, attr_name) if callable(attr): setattr(cls, attr_name, skip_if_not_implemented(attr)) return cls def custom_tokenizers(test_case): """ Decorator marking a test for a custom tokenizer. Custom tokenizers require additional dependencies, and are skipped by default. Set the RUN_CUSTOM_TOKENIZERS environment variable to a truthy value to run them. """ return unittest.skipUnless(_run_custom_tokenizers, "test of custom tokenizers")(test_case) def require_bs4(test_case): """ Decorator marking a test that requires BeautifulSoup4. These tests are skipped when BeautifulSoup4 isn't installed. """ return unittest.skipUnless(is_bs4_available(), "test requires BeautifulSoup4")(test_case) def require_galore_torch(test_case): """ Decorator marking a test that requires GaLore. These tests are skipped when GaLore isn't installed. https://github.com/jiaweizzhao/GaLore """ return unittest.skipUnless(is_galore_torch_available(), "test requires GaLore")(test_case) def require_apollo_torch(test_case): """ Decorator marking a test that requires GaLore. These tests are skipped when APOLLO isn't installed. https://github.com/zhuhanqing/APOLLO """ return unittest.skipUnless(is_apollo_torch_available(), "test requires APOLLO")(test_case) def require_torch_optimi(test_case): """ Decorator marking a test that requires torch-optimi. These tests are skipped when torch-optimi isn't installed. https://github.com/jxnl/torch-optimi """ return unittest.skipUnless(is_torch_optimi_available(), "test requires torch-optimi")(test_case) def require_lomo(test_case): """ Decorator marking a test that requires LOMO. These tests are skipped when LOMO-optim isn't installed. https://github.com/OpenLMLab/LOMO """ return unittest.skipUnless(is_lomo_available(), "test requires LOMO")(test_case) def require_grokadamw(test_case): """ Decorator marking a test that requires GrokAdamW. These tests are skipped when GrokAdamW isn't installed. """ return unittest.skipUnless(is_grokadamw_available(), "test requires GrokAdamW")(test_case) def require_schedulefree(test_case): """ Decorator marking a test that requires schedulefree. These tests are skipped when schedulefree isn't installed. https://github.com/facebookresearch/schedule_free """ return unittest.skipUnless(is_schedulefree_available(), "test requires schedulefree")(test_case) def require_cv2(test_case): """ Decorator marking a test that requires OpenCV. These tests are skipped when OpenCV isn't installed. """ return unittest.skipUnless(is_cv2_available(), "test requires OpenCV")(test_case) def require_levenshtein(test_case): """ Decorator marking a test that requires Levenshtein. These tests are skipped when Levenshtein isn't installed. """ return unittest.skipUnless(is_levenshtein_available(), "test requires Levenshtein")(test_case) def require_nltk(test_case): """ Decorator marking a test that requires NLTK. These tests are skipped when NLTK isn't installed. """ return unittest.skipUnless(is_nltk_available(), "test requires NLTK")(test_case) def require_accelerate(test_case, min_version: str = ACCELERATE_MIN_VERSION): """ Decorator marking a test that requires accelerate. These tests are skipped when accelerate isn't installed. """ return unittest.skipUnless( is_accelerate_available(min_version), f"test requires accelerate version >= {min_version}" )(test_case) def require_triton(min_version: str = TRITON_MIN_VERSION): """ Decorator marking a test that requires triton. These tests are skipped when triton isn't installed. """ def decorator(test_case): return unittest.skipUnless(is_triton_available(min_version), f"test requires triton version >= {min_version}")( test_case ) return decorator def require_gguf(test_case, min_version: str = GGUF_MIN_VERSION): """ Decorator marking a test that requires ggguf. These tests are skipped when gguf isn't installed. """ return unittest.skipUnless(is_gguf_available(min_version), f"test requires gguf version >= {min_version}")( test_case ) def require_fsdp(test_case, min_version: str = "1.12.0"): """ Decorator marking a test that requires fsdp. These tests are skipped when fsdp isn't installed. """ return unittest.skipUnless(is_fsdp_available(min_version), f"test requires torch version >= {min_version}")( test_case ) def require_g2p_en(test_case): """ Decorator marking a test that requires g2p_en. These tests are skipped when SentencePiece isn't installed. """ return unittest.skipUnless(is_g2p_en_available(), "test requires g2p_en")(test_case) def require_rjieba(test_case): """ Decorator marking a test that requires rjieba. These tests are skipped when rjieba isn't installed. """ return unittest.skipUnless(is_rjieba_available(), "test requires rjieba")(test_case) def require_jinja(test_case): """ Decorator marking a test that requires jinja. These tests are skipped when jinja isn't installed. """ return unittest.skipUnless(is_jinja_available(), "test requires jinja")(test_case) def require_jmespath(test_case): """ Decorator marking a test that requires jmespath. These tests are skipped when jmespath isn't installed. """ return unittest.skipUnless(is_jmespath_available(), "test requires jmespath")(test_case) def require_onnx(test_case): return unittest.skipUnless(is_onnx_available(), "test requires ONNX")(test_case) def require_timm(test_case): """ Decorator marking a test that requires Timm. These tests are skipped when Timm isn't installed. """ return unittest.skipUnless(is_timm_available(), "test requires Timm")(test_case) def require_natten(test_case): """ Decorator marking a test that requires NATTEN. These tests are skipped when NATTEN isn't installed. """ return unittest.skipUnless(is_natten_available(), "test requires natten")(test_case) def require_torch(test_case): """ Decorator marking a test that requires PyTorch. These tests are skipped when PyTorch isn't installed. """ return unittest.skipUnless(is_torch_available(), "test requires PyTorch")(test_case) def require_torch_greater_or_equal(version: str): """ Decorator marking a test that requires PyTorch version >= `version`. These tests are skipped when PyTorch version is less than `version`. """ def decorator(test_case): return unittest.skipUnless(is_torch_greater_or_equal(version), f"test requires PyTorch version >= {version}")( test_case ) return decorator def require_huggingface_hub_greater_or_equal(version: str): """ Decorator marking a test that requires huggingface_hub version >= `version`. These tests are skipped when huggingface_hub version is less than `version`. """ def decorator(test_case): return unittest.skipUnless( is_huggingface_hub_greater_or_equal(version), f"test requires huggingface_hub version >= {version}" )(test_case) return decorator def require_flash_attn(test_case): """ Decorator marking a test that requires Flash Attention. These tests are skipped when Flash Attention isn't installed. """ flash_attn_available = is_flash_attn_2_available() kernels_available = is_kernels_available() try: from kernels import get_kernel get_kernel(FLASH_ATTN_KERNEL_FALLBACK["flash_attention_2"]) except Exception as _: kernels_available = False return unittest.skipUnless(kernels_available | flash_attn_available, "test requires Flash Attention")(test_case) def require_kernels(test_case): """ Decorator marking a test that requires the kernels library. These tests are skipped when the kernels library isn't installed. """ return unittest.skipUnless(is_kernels_available(), "test requires the kernels library")(test_case) def require_flash_attn_3(test_case): """ Decorator marking a test that requires Flash Attention 3. These tests are skipped when Flash Attention 3 isn't installed. """ return unittest.skipUnless(is_flash_attn_3_available(), "test requires Flash Attention 3")(test_case) def require_read_token(test_case): """ A decorator that loads the HF token for tests that require to load gated models. """ token = os.getenv("HF_HUB_READ_TOKEN") if isinstance(test_case, type): for attr_name in dir(test_case): attr = getattr(test_case, attr_name) if isinstance(attr, types.FunctionType): if getattr(attr, "__require_read_token__", False): continue wrapped = require_read_token(attr) if isinstance(inspect.getattr_static(test_case, attr_name), staticmethod): # Don't accidentally bind staticmethods to `self` wrapped = staticmethod(wrapped) setattr(test_case, attr_name, wrapped) return test_case else: if getattr(test_case, "__require_read_token__", False): return test_case @functools.wraps(test_case) def wrapper(*args, **kwargs): if token is not None: with patch("huggingface_hub.utils._headers.get_token", return_value=token): return test_case(*args, **kwargs) else: # Allow running locally with the default token env variable return test_case(*args, **kwargs) wrapper.__require_read_token__ = True return wrapper def require_peft(test_case): """ Decorator marking a test that requires PEFT. These tests are skipped when PEFT isn't installed. """ return unittest.skipUnless(is_peft_available(), "test requires PEFT")(test_case) def require_torchvision(test_case): """ Decorator marking a test that requires Torchvision. These tests are skipped when Torchvision isn't installed. """ return unittest.skipUnless(is_torchvision_available(), "test requires Torchvision")(test_case) def require_torchcodec(test_case): """ Decorator marking a test that requires Torchcodec. These tests are skipped when Torchcodec isn't installed. """ return unittest.skipUnless(is_torchcodec_available(), "test requires Torchcodec")(test_case) def require_intel_extension_for_pytorch(test_case): """ Decorator marking a test that requires Intel Extension for PyTorch. These tests are skipped when Intel Extension for PyTorch isn't installed or it does not match current PyTorch version. """ return unittest.skipUnless( is_ipex_available(), "test requires Intel Extension for PyTorch to be installed and match current PyTorch version, see" " https://github.com/intel/intel-extension-for-pytorch", )(test_case) def require_torchaudio(test_case): """ Decorator marking a test that requires torchaudio. These tests are skipped when torchaudio isn't installed. """ return unittest.skipUnless(is_torchaudio_available(), "test requires torchaudio")(test_case) def require_sentencepiece(test_case): """ Decorator marking a test that requires SentencePiece. These tests are skipped when SentencePiece isn't installed. """ return unittest.skipUnless(is_sentencepiece_available(), "test requires SentencePiece")(test_case) def require_sacremoses(test_case): """ Decorator marking a test that requires Sacremoses. These tests are skipped when Sacremoses isn't installed. """ return unittest.skipUnless(is_sacremoses_available(), "test requires Sacremoses")(test_case) def require_seqio(test_case): """ Decorator marking a test that requires SentencePiece. These tests are skipped when SentencePiece isn't installed. """ return unittest.skipUnless(is_seqio_available(), "test requires Seqio")(test_case) def require_scipy(test_case): """ Decorator marking a test that requires Scipy. These tests are skipped when SentencePiece isn't installed. """ return unittest.skipUnless(is_scipy_available(), "test requires Scipy")(test_case) def require_tokenizers(test_case): """ Decorator marking a test that requires 🤗 Tokenizers. These tests are skipped when 🤗 Tokenizers isn't installed. """ return unittest.skipUnless(is_tokenizers_available(), "test requires tokenizers")(test_case) def require_pandas(test_case): """ Decorator marking a test that requires pandas. These tests are skipped when pandas isn't installed. """ return unittest.skipUnless(is_pandas_available(), "test requires pandas")(test_case) def require_pytesseract(test_case): """ Decorator marking a test that requires PyTesseract. These tests are skipped when PyTesseract isn't installed. """ return unittest.skipUnless(is_pytesseract_available(), "test requires PyTesseract")(test_case) def require_pytorch_quantization(test_case): """ Decorator marking a test that requires PyTorch Quantization Toolkit. These tests are skipped when PyTorch Quantization Toolkit isn't installed. """ return unittest.skipUnless(is_pytorch_quantization_available(), "test requires PyTorch Quantization Toolkit")( test_case ) def require_vision(test_case): """ Decorator marking a test that requires the vision dependencies. These tests are skipped when torchaudio isn't installed. """ return unittest.skipUnless(is_vision_available(), "test requires vision")(test_case) def require_ftfy(test_case): """ Decorator marking a test that requires ftfy. These tests are skipped when ftfy isn't installed. """ return unittest.skipUnless(is_ftfy_available(), "test requires ftfy")(test_case) def require_spacy(test_case): """ Decorator marking a test that requires SpaCy. These tests are skipped when SpaCy isn't installed. """ return unittest.skipUnless(is_spacy_available(), "test requires spacy")(test_case) def require_torch_multi_gpu(test_case): """ Decorator marking a test that requires a multi-GPU CUDA setup (in PyTorch). These tests are skipped on a machine without multiple CUDA GPUs. To run *only* the multi_gpu tests, assuming all test names contain multi_gpu: $ pytest -sv ./tests -k "multi_gpu" """ if not is_torch_available(): return unittest.skip(reason="test requires PyTorch")(test_case) import torch return unittest.skipUnless(torch.cuda.device_count() > 1, "test requires multiple CUDA GPUs")(test_case) def require_torch_multi_accelerator(test_case): """ Decorator marking a test that requires a multi-accelerator (in PyTorch). These tests are skipped on a machine without multiple accelerators. To run *only* the multi_accelerator tests, assuming all test names contain multi_accelerator: $ pytest -sv ./tests -k "multi_accelerator" """ if not is_torch_available(): return unittest.skip(reason="test requires PyTorch")(test_case) return unittest.skipUnless(backend_device_count(torch_device) > 1, "test requires multiple accelerators")( test_case ) def require_torch_non_multi_gpu(test_case): """ Decorator marking a test that requires 0 or 1 GPU setup (in PyTorch). """ if not is_torch_available(): return unittest.skip(reason="test requires PyTorch")(test_case) import torch return unittest.skipUnless(torch.cuda.device_count() < 2, "test requires 0 or 1 GPU")(test_case) def require_torch_non_multi_accelerator(test_case): """ Decorator marking a test that requires 0 or 1 accelerator setup (in PyTorch). """ if not is_torch_available(): return unittest.skip(reason="test requires PyTorch")(test_case) return unittest.skipUnless(backend_device_count(torch_device) < 2, "test requires 0 or 1 accelerator")(test_case) def require_torch_up_to_2_gpus(test_case): """ Decorator marking a test that requires 0 or 1 or 2 GPU setup (in PyTorch). """ if not is_torch_available(): return unittest.skip(reason="test requires PyTorch")(test_case) import torch return unittest.skipUnless(torch.cuda.device_count() < 3, "test requires 0 or 1 or 2 GPUs")(test_case) def require_torch_up_to_2_accelerators(test_case): """ Decorator marking a test that requires 0 or 1 or 2 accelerator setup (in PyTorch). """ if not is_torch_available(): return unittest.skip(reason="test requires PyTorch")(test_case) return unittest.skipUnless(backend_device_count(torch_device) < 3, "test requires 0 or 1 or 2 accelerators")( test_case ) def require_torch_xla(test_case): """ Decorator marking a test that requires TorchXLA (in PyTorch). """ return unittest.skipUnless(is_torch_xla_available(), "test requires TorchXLA")(test_case) def require_torch_neuroncore(test_case): """ Decorator marking a test that requires NeuronCore (in PyTorch). """ return unittest.skipUnless(is_torch_neuroncore_available(check_device=False), "test requires PyTorch NeuronCore")( test_case ) def require_torch_npu(test_case): """ Decorator marking a test that requires NPU (in PyTorch). """ return unittest.skipUnless(is_torch_npu_available(), "test requires PyTorch NPU")(test_case) def require_torch_multi_npu(test_case): """ Decorator marking a test that requires a multi-NPU setup (in PyTorch). These tests are skipped on a machine without multiple NPUs. To run *only* the multi_npu tests, assuming all test names contain multi_npu: $ pytest -sv ./tests -k "multi_npu" """ if not is_torch_npu_available(): return unittest.skip(reason="test requires PyTorch NPU")(test_case) return unittest.skipUnless(torch.npu.device_count() > 1, "test requires multiple NPUs")(test_case) def require_non_hpu(test_case): """ Decorator marking a test that should be skipped for HPU. """ return unittest.skipUnless(torch_device != "hpu", "test requires a non-HPU")(test_case) def require_torch_xpu(test_case): """ Decorator marking a test that requires XPU (in PyTorch). These tests are skipped when XPU backend is not available. XPU backend might be available either via stock PyTorch (>=2.4) or via Intel Extension for PyTorch. In the latter case, if IPEX is installed, its version must match match current PyTorch version. """ return unittest.skipUnless(is_torch_xpu_available(), "test requires XPU device")(test_case) def require_non_xpu(test_case): """ Decorator marking a test that should be skipped for XPU. """ return unittest.skipUnless(torch_device != "xpu", "test requires a non-XPU")(test_case) def require_torch_multi_xpu(test_case): """ Decorator marking a test that requires a multi-XPU setup (in PyTorch). These tests are skipped on a machine without multiple XPUs. To run *only* the multi_xpu tests, assuming all test names contain multi_xpu: $ pytest -sv ./tests -k "multi_xpu" """ if not is_torch_xpu_available(): return unittest.skip(reason="test requires PyTorch XPU")(test_case) return unittest.skipUnless(torch.xpu.device_count() > 1, "test requires multiple XPUs")(test_case) def require_torch_multi_hpu(test_case): """ Decorator marking a test that requires a multi-HPU setup (in PyTorch). These tests are skipped on a machine without multiple HPUs. To run *only* the multi_hpu tests, assuming all test names contain multi_hpu: $ pytest -sv ./tests -k "multi_hpu" """ if not is_torch_hpu_available(): return unittest.skip(reason="test requires PyTorch HPU")(test_case) return unittest.skipUnless(torch.hpu.device_count() > 1, "test requires multiple HPUs")(test_case) if is_torch_available(): # Set env var CUDA_VISIBLE_DEVICES="" to force cpu-mode import torch if "TRANSFORMERS_TEST_BACKEND" in os.environ: backend = os.environ["TRANSFORMERS_TEST_BACKEND"] try: _ = importlib.import_module(backend) except ModuleNotFoundError as e: raise ModuleNotFoundError( f"Failed to import `TRANSFORMERS_TEST_BACKEND` '{backend}'! This should be the name of an installed module. The original error (look up to see its" f" traceback):\n{e}" ) from e if "TRANSFORMERS_TEST_DEVICE" in os.environ: torch_device = os.environ["TRANSFORMERS_TEST_DEVICE"] if torch_device == "cuda" and not torch.cuda.is_available(): raise ValueError( f"TRANSFORMERS_TEST_DEVICE={torch_device}, but CUDA is unavailable. Please double-check your testing environment." ) if torch_device == "xpu" and not is_torch_xpu_available(): raise ValueError( f"TRANSFORMERS_TEST_DEVICE={torch_device}, but XPU is unavailable. Please double-check your testing environment." ) if torch_device == "npu" and not is_torch_npu_available(): raise ValueError( f"TRANSFORMERS_TEST_DEVICE={torch_device}, but NPU is unavailable. Please double-check your testing environment." ) if torch_device == "mlu" and not is_torch_mlu_available():
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/__init__.py
src/transformers/__init__.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # When adding a new object to this init, remember to add it twice: once inside the `_import_structure` dictionary and # once inside the `if TYPE_CHECKING` branch. The `TYPE_CHECKING` should have import statements as usual, but they are # only there for type checking. The `_import_structure` is a dictionary submodule to list of object names, and is used # to defer the actual importing for when the objects are requested. This way `import transformers` provides the names # in the namespace without actually importing anything (and especially none of the backends). __version__ = "5.0.0.dev0" import importlib import sys import types from pathlib import Path from typing import TYPE_CHECKING # Check the dependencies satisfy the minimal versions required. from . import dependency_versions_check from .utils import ( OptionalDependencyNotAvailable, _LazyModule, is_essentia_available, is_g2p_en_available, is_librosa_available, is_mistral_common_available, is_mlx_available, is_numba_available, is_pretty_midi_available, ) # Note: the following symbols are deliberately exported with `as` # so that mypy, pylint or other static linters can recognize them, # given that they are not exported using `__all__` in this file. from .utils import is_bitsandbytes_available as is_bitsandbytes_available from .utils import is_scipy_available as is_scipy_available from .utils import is_sentencepiece_available as is_sentencepiece_available from .utils import is_speech_available as is_speech_available from .utils import is_timm_available as is_timm_available from .utils import is_tokenizers_available as is_tokenizers_available from .utils import is_torch_available as is_torch_available from .utils import is_torchaudio_available as is_torchaudio_available from .utils import is_torchvision_available as is_torchvision_available from .utils import is_vision_available as is_vision_available from .utils import logging as logging from .utils.import_utils import define_import_structure logger = logging.get_logger(__name__) # pylint: disable=invalid-name # Base objects, independent of any specific backend _import_structure = { "audio_utils": [], "cli": [], "configuration_utils": ["PreTrainedConfig", "PretrainedConfig"], "convert_slow_tokenizers_checkpoints_to_fast": [], "data": [ "DataProcessor", "InputExample", "InputFeatures", "SingleSentenceClassificationProcessor", "SquadExample", "SquadFeatures", "SquadV1Processor", "SquadV2Processor", "glue_compute_metrics", "glue_convert_examples_to_features", "glue_output_modes", "glue_processors", "glue_tasks_num_labels", "squad_convert_examples_to_features", "xnli_compute_metrics", "xnli_output_modes", "xnli_processors", "xnli_tasks_num_labels", ], "data.data_collator": [ "DataCollator", "DataCollatorForLanguageModeling", "DataCollatorForMultipleChoice", "DataCollatorForPermutationLanguageModeling", "DataCollatorForSeq2Seq", "DataCollatorForSOP", "DataCollatorForTokenClassification", "DataCollatorForWholeWordMask", "DataCollatorWithFlattening", "DataCollatorWithPadding", "DefaultDataCollator", "default_data_collator", ], "data.metrics": [], "data.processors": [], "debug_utils": [], "dependency_versions_check": [], "dependency_versions_table": [], "dynamic_module_utils": [], "feature_extraction_sequence_utils": ["SequenceFeatureExtractor"], "feature_extraction_utils": ["BatchFeature", "FeatureExtractionMixin"], "file_utils": [], "generation": [ "AsyncTextIteratorStreamer", "CompileConfig", "GenerationConfig", "TextIteratorStreamer", "TextStreamer", "WatermarkingConfig", ], "hf_argparser": ["HfArgumentParser"], "hyperparameter_search": [], "image_transforms": [], "integrations": [ "is_clearml_available", "is_comet_available", "is_dvclive_available", "is_neptune_available", "is_optuna_available", "is_ray_available", "is_ray_tune_available", "is_swanlab_available", "is_tensorboard_available", "is_trackio_available", "is_wandb_available", ], "loss": [], "modelcard": ["ModelCard"], "pipelines": [ "AnyToAnyPipeline", "AudioClassificationPipeline", "AutomaticSpeechRecognitionPipeline", "CsvPipelineDataFormat", "DepthEstimationPipeline", "DocumentQuestionAnsweringPipeline", "FeatureExtractionPipeline", "FillMaskPipeline", "ImageClassificationPipeline", "ImageFeatureExtractionPipeline", "ImageSegmentationPipeline", "ImageTextToTextPipeline", "ImageToImagePipeline", "ImageToTextPipeline", "JsonPipelineDataFormat", "KeypointMatchingPipeline", "MaskGenerationPipeline", "NerPipeline", "ObjectDetectionPipeline", "PipedPipelineDataFormat", "Pipeline", "PipelineDataFormat", "QuestionAnsweringPipeline", "SummarizationPipeline", "TableQuestionAnsweringPipeline", "Text2TextGenerationPipeline", "TextClassificationPipeline", "TextGenerationPipeline", "TextToAudioPipeline", "TokenClassificationPipeline", "TranslationPipeline", "VideoClassificationPipeline", "VisualQuestionAnsweringPipeline", "ZeroShotAudioClassificationPipeline", "ZeroShotClassificationPipeline", "ZeroShotImageClassificationPipeline", "ZeroShotObjectDetectionPipeline", "pipeline", ], "processing_utils": ["ProcessorMixin"], "quantizers": [], "testing_utils": [], "tokenization_python": ["PreTrainedTokenizer", "PythonBackend"], "tokenization_utils": [], "tokenization_utils_fast": [], "tokenization_utils_sentencepiece": ["SentencePieceBackend"], "tokenization_utils_base": [ "AddedToken", "BatchEncoding", "CharSpan", "PreTrainedTokenizerBase", "TokenSpan", ], "trainer_callback": [ "DefaultFlowCallback", "EarlyStoppingCallback", "PrinterCallback", "ProgressCallback", "TrainerCallback", "TrainerControl", "TrainerState", ], "trainer_utils": [ "EvalPrediction", "IntervalStrategy", "SchedulerType", "enable_full_determinism", "set_seed", ], "training_args": ["TrainingArguments"], "training_args_seq2seq": ["Seq2SeqTrainingArguments"], "utils": [ "CONFIG_NAME", "MODEL_CARD_NAME", "SPIECE_UNDERLINE", "WEIGHTS_NAME", "TensorType", "add_end_docstrings", "add_start_docstrings", "is_apex_available", "is_av_available", "is_bitsandbytes_available", "is_datasets_available", "is_faiss_available", "is_matplotlib_available", "is_mlx_available", "is_phonemizer_available", "is_psutil_available", "is_py3nvml_available", "is_pyctcdecode_available", "is_sacremoses_available", "is_scipy_available", "is_sentencepiece_available", "is_sklearn_available", "is_speech_available", "is_timm_available", "is_tokenizers_available", "is_torch_available", "is_torch_hpu_available", "is_torch_mlu_available", "is_torch_musa_available", "is_torch_neuroncore_available", "is_torch_npu_available", "is_torchvision_available", "is_torch_xla_available", "is_torch_xpu_available", "is_vision_available", "logging", ], "utils.quantization_config": [ "AqlmConfig", "AutoRoundConfig", "AwqConfig", "BitNetQuantConfig", "BitsAndBytesConfig", "CompressedTensorsConfig", "EetqConfig", "FbgemmFp8Config", "FineGrainedFP8Config", "GPTQConfig", "HiggsConfig", "HqqConfig", "Mxfp4Config", "QuantoConfig", "QuarkConfig", "FPQuantConfig", "SpQRConfig", "TorchAoConfig", "VptqConfig", ], "video_utils": [], "utils.kernel_config": ["KernelConfig"], "utils.import_utils": ["requires_backends"], } # tokenizers-backed objects try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_tokenizers_objects _import_structure["utils.dummy_tokenizers_objects"] = [ name for name in dir(dummy_tokenizers_objects) if not name.startswith("_") ] else: # Fast tokenizers structure _import_structure["tokenization_utils_tokenizers"] = [ "TokenizersBackend", "PreTrainedTokenizerFast", ] try: if not (is_sentencepiece_available() and is_tokenizers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_sentencepiece_and_tokenizers_objects _import_structure["utils.dummy_sentencepiece_and_tokenizers_objects"] = [ name for name in dir(dummy_sentencepiece_and_tokenizers_objects) if not name.startswith("_") ] else: _import_structure["convert_slow_tokenizer"] = [ "SLOW_TO_FAST_CONVERTERS", "convert_slow_tokenizer", ] try: if not (is_mistral_common_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_mistral_common_objects _import_structure["utils.dummy_mistral_common_objects"] = [ name for name in dir(dummy_mistral_common_objects) if not name.startswith("_") ] else: _import_structure["tokenization_mistral_common"] = ["MistralCommonBackend"] # Vision-specific objects try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_vision_objects _import_structure["utils.dummy_vision_objects"] = [ name for name in dir(dummy_vision_objects) if not name.startswith("_") ] else: _import_structure["image_processing_base"] = ["ImageProcessingMixin"] _import_structure["image_processing_utils"] = ["BaseImageProcessor"] _import_structure["image_utils"] = ["ImageFeatureExtractionMixin"] try: if not is_torchvision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_torchvision_objects _import_structure["utils.dummy_torchvision_objects"] = [ name for name in dir(dummy_torchvision_objects) if not name.startswith("_") ] else: _import_structure["image_processing_utils_fast"] = ["BaseImageProcessorFast"] _import_structure["video_processing_utils"] = ["BaseVideoProcessor"] # PyTorch-backed objects try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_pt_objects _import_structure["utils.dummy_pt_objects"] = [name for name in dir(dummy_pt_objects) if not name.startswith("_")] else: _import_structure["model_debugging_utils"] = [ "model_addition_debugger_context", ] _import_structure["activations"] = [] _import_structure["cache_utils"] = [ "CacheLayerMixin", "DynamicLayer", "StaticLayer", "StaticSlidingWindowLayer", "QuantoQuantizedLayer", "HQQQuantizedLayer", "SlidingWindowLayer", "ChunkedSlidingLayer", "HQQQuantizedCache", "HybridCache", "HybridChunkedCache", "OffloadedCache", "OffloadedStaticCache", "QuantoQuantizedCache", "SlidingWindowCache", "Cache", "DynamicCache", "EncoderDecoderCache", "QuantizedCache", "StaticCache", ] _import_structure["data.datasets"] = [ "GlueDataset", "GlueDataTrainingArguments", "SquadDataset", "SquadDataTrainingArguments", ] _import_structure["generation"].extend( [ "AlternatingCodebooksLogitsProcessor", "BayesianDetectorConfig", "BayesianDetectorModel", "ClassifierFreeGuidanceLogitsProcessor", "ContinuousBatchingManager", "ContinuousMixin", "EncoderNoRepeatNGramLogitsProcessor", "EncoderRepetitionPenaltyLogitsProcessor", "EosTokenCriteria", "EpsilonLogitsWarper", "EtaLogitsWarper", "ExponentialDecayLengthPenalty", "ForcedBOSTokenLogitsProcessor", "ForcedEOSTokenLogitsProcessor", "GenerationMixin", "InfNanRemoveLogitsProcessor", "LogitNormalization", "LogitsProcessor", "LogitsProcessorList", "MaxLengthCriteria", "MaxTimeCriteria", "MinLengthLogitsProcessor", "MinNewTokensLengthLogitsProcessor", "MinPLogitsWarper", "NoBadWordsLogitsProcessor", "NoRepeatNGramLogitsProcessor", "PrefixConstrainedLogitsProcessor", "RepetitionPenaltyLogitsProcessor", "SequenceBiasLogitsProcessor", "StoppingCriteria", "StoppingCriteriaList", "StopStringCriteria", "SuppressTokensAtBeginLogitsProcessor", "SuppressTokensLogitsProcessor", "SynthIDTextWatermarkDetector", "SynthIDTextWatermarkingConfig", "SynthIDTextWatermarkLogitsProcessor", "TemperatureLogitsWarper", "TopHLogitsWarper", "TopKLogitsWarper", "TopPLogitsWarper", "TypicalLogitsWarper", "UnbatchedClassifierFreeGuidanceLogitsProcessor", "WatermarkDetector", "WatermarkLogitsProcessor", "WhisperTimeStampLogitsProcessor", ] ) # PyTorch domain libraries integration _import_structure["integrations.executorch"] = [ "TorchExportableModuleWithStaticCache", "convert_and_export_with_cache", ] _import_structure["core_model_loading"] = [ "Chunk", "Concatenate", "ConversionOps", "MergeModulelist", "PermuteForRope", "SplitModulelist", "WeightConverter", ] _import_structure["modeling_flash_attention_utils"] = [] _import_structure["modeling_layers"] = ["GradientCheckpointingLayer"] _import_structure["modeling_outputs"] = [] _import_structure["modeling_rope_utils"] = ["ROPE_INIT_FUNCTIONS", "dynamic_rope_update", "RopeParameters"] _import_structure["modeling_utils"] = ["PreTrainedModel", "AttentionInterface"] _import_structure["masking_utils"] = ["AttentionMaskInterface"] _import_structure["optimization"] = [ "Adafactor", "get_constant_schedule", "get_constant_schedule_with_warmup", "get_cosine_schedule_with_warmup", "get_cosine_with_hard_restarts_schedule_with_warmup", "get_cosine_with_min_lr_schedule_with_warmup", "get_cosine_with_min_lr_schedule_with_warmup_lr_rate", "get_inverse_sqrt_schedule", "get_linear_schedule_with_warmup", "get_polynomial_decay_schedule_with_warmup", "get_scheduler", "get_wsd_schedule", "get_reduce_on_plateau_schedule", ] _import_structure["pytorch_utils"] = ["Conv1D", "apply_chunking_to_forward"] _import_structure["time_series_utils"] = [] _import_structure["trainer"] = ["Trainer"] _import_structure["trainer_pt_utils"] = ["torch_distributed_zero_first"] _import_structure["trainer_seq2seq"] = ["Seq2SeqTrainer"] # Direct imports for type-checking if TYPE_CHECKING: # All modeling imports from .cache_utils import Cache as Cache from .cache_utils import ChunkedSlidingLayer as ChunkedSlidingLayer from .cache_utils import DynamicCache as DynamicCache from .cache_utils import DynamicLayer as DynamicLayer from .cache_utils import EncoderDecoderCache as EncoderDecoderCache from .cache_utils import HQQQuantizedCache as HQQQuantizedCache from .cache_utils import HQQQuantizedLayer as HQQQuantizedLayer from .cache_utils import HybridCache as HybridCache from .cache_utils import OffloadedCache as OffloadedCache from .cache_utils import OffloadedStaticCache as OffloadedStaticCache from .cache_utils import QuantizedCache as QuantizedCache from .cache_utils import QuantoQuantizedCache as QuantoQuantizedCache from .cache_utils import QuantoQuantizedLayer as QuantoQuantizedLayer from .cache_utils import SlidingWindowCache as SlidingWindowCache from .cache_utils import SlidingWindowLayer as SlidingWindowLayer from .cache_utils import StaticCache as StaticCache from .cache_utils import StaticLayer as StaticLayer from .cache_utils import StaticSlidingWindowLayer as StaticSlidingWindowLayer from .configuration_utils import PreTrainedConfig as PreTrainedConfig from .configuration_utils import PretrainedConfig as PretrainedConfig from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS as SLOW_TO_FAST_CONVERTERS from .convert_slow_tokenizer import convert_slow_tokenizer as convert_slow_tokenizer from .core_model_loading import Chunk as Chunk from .core_model_loading import Concatenate as Concatenate from .core_model_loading import ConversionOps as ConversionOps from .core_model_loading import MergeModulelist as MergeModulelist from .core_model_loading import PermuteForRope as PermuteForRope from .core_model_loading import SplitModulelist as SplitModulelist from .core_model_loading import WeightConverter as WeightConverter # Data from .data import DataProcessor as DataProcessor from .data import InputExample as InputExample from .data import InputFeatures as InputFeatures from .data import SingleSentenceClassificationProcessor as SingleSentenceClassificationProcessor from .data import SquadExample as SquadExample from .data import SquadFeatures as SquadFeatures from .data import SquadV1Processor as SquadV1Processor from .data import SquadV2Processor as SquadV2Processor from .data import glue_compute_metrics as glue_compute_metrics from .data import glue_convert_examples_to_features as glue_convert_examples_to_features from .data import glue_output_modes as glue_output_modes from .data import glue_processors as glue_processors from .data import glue_tasks_num_labels as glue_tasks_num_labels from .data import squad_convert_examples_to_features as squad_convert_examples_to_features from .data import xnli_compute_metrics as xnli_compute_metrics from .data import xnli_output_modes as xnli_output_modes from .data import xnli_processors as xnli_processors from .data import xnli_tasks_num_labels as xnli_tasks_num_labels from .data.data_collator import DataCollator as DataCollator from .data.data_collator import DataCollatorForLanguageModeling as DataCollatorForLanguageModeling from .data.data_collator import DataCollatorForMultipleChoice as DataCollatorForMultipleChoice from .data.data_collator import ( DataCollatorForPermutationLanguageModeling as DataCollatorForPermutationLanguageModeling, ) from .data.data_collator import DataCollatorForSeq2Seq as DataCollatorForSeq2Seq from .data.data_collator import DataCollatorForSOP as DataCollatorForSOP from .data.data_collator import DataCollatorForTokenClassification as DataCollatorForTokenClassification from .data.data_collator import DataCollatorForWholeWordMask as DataCollatorForWholeWordMask from .data.data_collator import DataCollatorWithFlattening as DataCollatorWithFlattening from .data.data_collator import DataCollatorWithPadding as DataCollatorWithPadding from .data.data_collator import DefaultDataCollator as DefaultDataCollator from .data.data_collator import default_data_collator as default_data_collator from .data.datasets import GlueDataset as GlueDataset from .data.datasets import GlueDataTrainingArguments as GlueDataTrainingArguments from .data.datasets import SquadDataset as SquadDataset from .data.datasets import SquadDataTrainingArguments as SquadDataTrainingArguments from .feature_extraction_sequence_utils import SequenceFeatureExtractor as SequenceFeatureExtractor # Feature Extractor from .feature_extraction_utils import BatchFeature as BatchFeature from .feature_extraction_utils import FeatureExtractionMixin as FeatureExtractionMixin # Generation from .generation import AlternatingCodebooksLogitsProcessor as AlternatingCodebooksLogitsProcessor from .generation import AsyncTextIteratorStreamer as AsyncTextIteratorStreamer from .generation import BayesianDetectorConfig as BayesianDetectorConfig from .generation import BayesianDetectorModel as BayesianDetectorModel from .generation import ClassifierFreeGuidanceLogitsProcessor as ClassifierFreeGuidanceLogitsProcessor from .generation import CompileConfig as CompileConfig from .generation import ContinuousBatchingManager as ContinuousBatchingManager from .generation import ContinuousMixin as ContinuousMixin from .generation import EncoderNoRepeatNGramLogitsProcessor as EncoderNoRepeatNGramLogitsProcessor from .generation import EncoderRepetitionPenaltyLogitsProcessor as EncoderRepetitionPenaltyLogitsProcessor from .generation import EosTokenCriteria as EosTokenCriteria from .generation import EpsilonLogitsWarper as EpsilonLogitsWarper from .generation import EtaLogitsWarper as EtaLogitsWarper from .generation import ExponentialDecayLengthPenalty as ExponentialDecayLengthPenalty from .generation import ForcedBOSTokenLogitsProcessor as ForcedBOSTokenLogitsProcessor from .generation import ForcedEOSTokenLogitsProcessor as ForcedEOSTokenLogitsProcessor from .generation import GenerationConfig as GenerationConfig from .generation import GenerationMixin as GenerationMixin from .generation import InfNanRemoveLogitsProcessor as InfNanRemoveLogitsProcessor from .generation import LogitNormalization as LogitNormalization from .generation import LogitsProcessor as LogitsProcessor from .generation import LogitsProcessorList as LogitsProcessorList from .generation import MaxLengthCriteria as MaxLengthCriteria from .generation import MaxTimeCriteria as MaxTimeCriteria from .generation import MinLengthLogitsProcessor as MinLengthLogitsProcessor from .generation import MinNewTokensLengthLogitsProcessor as MinNewTokensLengthLogitsProcessor from .generation import MinPLogitsWarper as MinPLogitsWarper from .generation import NoBadWordsLogitsProcessor as NoBadWordsLogitsProcessor from .generation import NoRepeatNGramLogitsProcessor as NoRepeatNGramLogitsProcessor from .generation import PrefixConstrainedLogitsProcessor as PrefixConstrainedLogitsProcessor from .generation import RepetitionPenaltyLogitsProcessor as RepetitionPenaltyLogitsProcessor from .generation import SequenceBiasLogitsProcessor as SequenceBiasLogitsProcessor from .generation import StoppingCriteria as StoppingCriteria from .generation import StoppingCriteriaList as StoppingCriteriaList from .generation import StopStringCriteria as StopStringCriteria from .generation import SuppressTokensAtBeginLogitsProcessor as SuppressTokensAtBeginLogitsProcessor from .generation import SuppressTokensLogitsProcessor as SuppressTokensLogitsProcessor from .generation import SynthIDTextWatermarkDetector as SynthIDTextWatermarkDetector from .generation import SynthIDTextWatermarkingConfig as SynthIDTextWatermarkingConfig from .generation import SynthIDTextWatermarkLogitsProcessor as SynthIDTextWatermarkLogitsProcessor from .generation import TemperatureLogitsWarper as TemperatureLogitsWarper from .generation import TextIteratorStreamer as TextIteratorStreamer from .generation import TextStreamer as TextStreamer from .generation import TopHLogitsWarper as TopHLogitsWarper from .generation import TopKLogitsWarper as TopKLogitsWarper from .generation import TopPLogitsWarper as TopPLogitsWarper from .generation import TypicalLogitsWarper as TypicalLogitsWarper from .generation import ( UnbatchedClassifierFreeGuidanceLogitsProcessor as UnbatchedClassifierFreeGuidanceLogitsProcessor, ) from .generation import WatermarkDetector as WatermarkDetector from .generation import WatermarkingConfig as WatermarkingConfig from .generation import WatermarkLogitsProcessor as WatermarkLogitsProcessor from .generation import WhisperTimeStampLogitsProcessor as WhisperTimeStampLogitsProcessor from .hf_argparser import HfArgumentParser as HfArgumentParser from .image_processing_base import ImageProcessingMixin as ImageProcessingMixin from .image_processing_utils import BaseImageProcessor as BaseImageProcessor from .image_processing_utils_fast import BaseImageProcessorFast as BaseImageProcessorFast from .image_utils import ImageFeatureExtractionMixin as ImageFeatureExtractionMixin # Integrations from .integrations import is_clearml_available as is_clearml_available from .integrations import is_comet_available as is_comet_available from .integrations import is_dvclive_available as is_dvclive_available from .integrations import is_neptune_available as is_neptune_available from .integrations import is_optuna_available as is_optuna_available from .integrations import is_ray_available as is_ray_available from .integrations import is_ray_tune_available as is_ray_tune_available from .integrations import is_swanlab_available as is_swanlab_available from .integrations import is_tensorboard_available as is_tensorboard_available from .integrations import is_trackio_available as is_trackio_available from .integrations import is_wandb_available as is_wandb_available from .integrations.executorch import TorchExportableModuleWithStaticCache as TorchExportableModuleWithStaticCache from .integrations.executorch import convert_and_export_with_cache as convert_and_export_with_cache from .masking_utils import AttentionMaskInterface as AttentionMaskInterface from .model_debugging_utils import model_addition_debugger_context as model_addition_debugger_context # Model Cards from .modelcard import ModelCard as ModelCard from .modeling_layers import GradientCheckpointingLayer as GradientCheckpointingLayer from .modeling_rope_utils import ROPE_INIT_FUNCTIONS as ROPE_INIT_FUNCTIONS from .modeling_rope_utils import RopeParameters as RopeParameters from .modeling_rope_utils import dynamic_rope_update as dynamic_rope_update from .modeling_utils import AttentionInterface as AttentionInterface from .modeling_utils import PreTrainedModel as PreTrainedModel from .models import * from .models.mamba.modeling_mamba import MambaCache as MambaCache from .models.timm_wrapper import TimmWrapperImageProcessor as TimmWrapperImageProcessor # Optimization from .optimization import Adafactor as Adafactor from .optimization import get_constant_schedule as get_constant_schedule from .optimization import get_constant_schedule_with_warmup as get_constant_schedule_with_warmup from .optimization import get_cosine_schedule_with_warmup as get_cosine_schedule_with_warmup from .optimization import ( get_cosine_with_hard_restarts_schedule_with_warmup as get_cosine_with_hard_restarts_schedule_with_warmup, ) from .optimization import ( get_cosine_with_min_lr_schedule_with_warmup as get_cosine_with_min_lr_schedule_with_warmup, ) from .optimization import ( get_cosine_with_min_lr_schedule_with_warmup_lr_rate as get_cosine_with_min_lr_schedule_with_warmup_lr_rate, ) from .optimization import get_inverse_sqrt_schedule as get_inverse_sqrt_schedule from .optimization import get_linear_schedule_with_warmup as get_linear_schedule_with_warmup from .optimization import get_polynomial_decay_schedule_with_warmup as get_polynomial_decay_schedule_with_warmup from .optimization import get_scheduler as get_scheduler from .optimization import get_wsd_schedule as get_wsd_schedule # Pipelines from .pipelines import AnyToAnyPipeline as AnyToAnyPipeline from .pipelines import AudioClassificationPipeline as AudioClassificationPipeline from .pipelines import AutomaticSpeechRecognitionPipeline as AutomaticSpeechRecognitionPipeline from .pipelines import CsvPipelineDataFormat as CsvPipelineDataFormat from .pipelines import DepthEstimationPipeline as DepthEstimationPipeline from .pipelines import DocumentQuestionAnsweringPipeline as DocumentQuestionAnsweringPipeline from .pipelines import FeatureExtractionPipeline as FeatureExtractionPipeline from .pipelines import FillMaskPipeline as FillMaskPipeline from .pipelines import ImageClassificationPipeline as ImageClassificationPipeline from .pipelines import ImageFeatureExtractionPipeline as ImageFeatureExtractionPipeline from .pipelines import ImageSegmentationPipeline as ImageSegmentationPipeline from .pipelines import ImageTextToTextPipeline as ImageTextToTextPipeline from .pipelines import ImageToImagePipeline as ImageToImagePipeline from .pipelines import ImageToTextPipeline as ImageToTextPipeline from .pipelines import JsonPipelineDataFormat as JsonPipelineDataFormat from .pipelines import KeypointMatchingPipeline as KeypointMatchingPipeline from .pipelines import MaskGenerationPipeline as MaskGenerationPipeline from .pipelines import NerPipeline as NerPipeline from .pipelines import ObjectDetectionPipeline as ObjectDetectionPipeline from .pipelines import PipedPipelineDataFormat as PipedPipelineDataFormat from .pipelines import Pipeline as Pipeline from .pipelines import PipelineDataFormat as PipelineDataFormat from .pipelines import QuestionAnsweringPipeline as QuestionAnsweringPipeline from .pipelines import SummarizationPipeline as SummarizationPipeline from .pipelines import TableQuestionAnsweringPipeline as TableQuestionAnsweringPipeline from .pipelines import Text2TextGenerationPipeline as Text2TextGenerationPipeline from .pipelines import TextClassificationPipeline as TextClassificationPipeline from .pipelines import TextGenerationPipeline as TextGenerationPipeline from .pipelines import TextToAudioPipeline as TextToAudioPipeline from .pipelines import TokenClassificationPipeline as TokenClassificationPipeline from .pipelines import TranslationPipeline as TranslationPipeline from .pipelines import VideoClassificationPipeline as VideoClassificationPipeline from .pipelines import VisualQuestionAnsweringPipeline as VisualQuestionAnsweringPipeline from .pipelines import ZeroShotAudioClassificationPipeline as ZeroShotAudioClassificationPipeline from .pipelines import ZeroShotClassificationPipeline as ZeroShotClassificationPipeline from .pipelines import ZeroShotImageClassificationPipeline as ZeroShotImageClassificationPipeline from .pipelines import ZeroShotObjectDetectionPipeline as ZeroShotObjectDetectionPipeline from .pipelines import pipeline as pipeline from .processing_utils import ProcessorMixin as ProcessorMixin from .pytorch_utils import Conv1D as Conv1D from .pytorch_utils import apply_chunking_to_forward as apply_chunking_to_forward # Tokenization
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/conversion_mapping.py
src/transformers/conversion_mapping.py
# coding=utf-8 # Copyright (C) 2025 the HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from copy import deepcopy from typing import TYPE_CHECKING from .core_model_loading import ( Chunk, Concatenate, ErnieFuseAndSplitTextVisionExperts, MergeModulelist, Transpose, WeightConverter, WeightRenaming, ) from .utils import is_torch_available if is_torch_available(): import torch if TYPE_CHECKING: from .modeling_utils import PreTrainedModel from .quantizers import HfQuantizer def _build_checkpoint_conversion_mapping(): mapping = { "mixtral": [ WeightRenaming(".block_sparse_moe.gate", ".mlp.gate"), WeightConverter( source_patterns=[ "block_sparse_moe.experts.*.w1.weight", "block_sparse_moe.experts.*.w3.weight", ], # you give me a list of 2 keys, I collect a list of a list of tensors target_patterns="mlp.experts.gate_up_proj", # target key gets the list of two tensors operations=[ MergeModulelist( dim=0 ), # each process has two lists of tensors, we cat each list. -> we end up with 2 tensors Concatenate(dim=1), # each process has 2 tensors, gate and up, we concat them into gate_up ], # we want the loading to add this shard operation here. Though we can't shard after concats and merge, needs to be first ), WeightConverter( source_patterns=[ "block_sparse_moe.experts.*.w2.weight", ], target_patterns="mlp.experts.down_proj", # target key gets the list of two tensors operations=[ MergeModulelist( dim=0 ), # each process has two lists of tensors, we cat each list. -> we end up with 2 tensors ], # we want the loading to add this shard operation here. Though we can't shard after concats and merge, needs to be first ), ], "qwen2_moe": [ WeightConverter( source_patterns=[ "mlp.experts.*.gate_proj.weight", "mlp.experts.*.up_proj.weight", ], target_patterns="mlp.experts.gate_up_proj", operations=[MergeModulelist(dim=0), Concatenate(dim=1)], ), WeightConverter( source_patterns="mlp.experts.*.down_proj.weight", target_patterns="mlp.experts.down_proj", operations=[MergeModulelist(dim=0)], ), ], "phimoe": [ WeightConverter( source_patterns=[ "mlp.experts.*.w1.weight", "mlp.experts.*.w3.weight", ], target_patterns="mlp.experts.gate_up_proj", operations=[MergeModulelist(dim=0), Concatenate(dim=1)], ), WeightConverter( source_patterns="mlp.experts.*.w2.weight", target_patterns="mlp.experts.down_proj", operations=[MergeModulelist(dim=0)], ), ], "lfm2_moe": [ WeightConverter( source_patterns=[ "feed_forward.experts.*.w1.weight", "feed_forward.experts.*.w3.weight", ], target_patterns="feed_forward.experts.gate_up_proj", operations=[MergeModulelist(dim=0), Concatenate(dim=1)], ), WeightConverter( source_patterns="feed_forward.experts.*.w2.weight", target_patterns="feed_forward.experts.down_proj", operations=[MergeModulelist(dim=0)], ), ], "ernie4_5_vl_moe": [ # vision WeightRenaming("vision_model", "vision_tower"), # resampler WeightRenaming("spatial_linear.0", "spatial_linear.fc1"), WeightRenaming("spatial_linear.2", "spatial_linear.fc2"), WeightRenaming("spatial_linear.3", "spatial_linear.ln"), WeightRenaming("temporal_linear.0", "temporal_linear.fc1"), WeightRenaming("temporal_linear.2", "temporal_linear.fc2"), WeightRenaming("temporal_linear.3", "temporal_linear.ln"), # language model WeightRenaming(r"(?<!language_model\.)embed_tokens", "language_model.embed_tokens"), WeightRenaming(r"(?<!language_model\.)layers", "language_model.layers"), WeightConverter( source_patterns="mlp.gate.weight_1", target_patterns="mlp.vision_moe.gate.weight", operations=[Transpose(dim0=0, dim1=1)], ), WeightConverter( source_patterns="mlp.gate.weight", target_patterns="mlp.text_moe.gate.weight", operations=[Transpose(dim0=0, dim1=1)], ), WeightConverter( source_patterns=["mlp.moe_statics.e_score_correction_bias"], target_patterns=[ "mlp.text_moe.gate.moe_statics.e_score_correction_bias", "mlp.vision_moe.gate.moe_statics.e_score_correction_bias", ], operations=[Chunk(dim=0)], ), WeightConverter( source_patterns=["experts.*.down_proj.weight"], target_patterns=[ "text_moe.experts.down_proj", "vision_moe.experts.down_proj", ], operations=[ErnieFuseAndSplitTextVisionExperts(stack_dim=0, concat_dim=1)], ), WeightConverter( source_patterns=[ "experts.*.gate_proj.weight", "experts.*.up_proj.weight", ], target_patterns=[ "text_moe.experts.gate_up_proj", "vision_moe.experts.gate_up_proj", ], operations=[ErnieFuseAndSplitTextVisionExperts(stack_dim=0, concat_dim=1)], ), ], "jamba": [ WeightConverter( source_patterns=[ "feed_forward.experts.*.gate_proj.weight", "feed_forward.experts.*.up_proj.weight", ], target_patterns="feed_forward.experts.gate_up_proj", operations=[MergeModulelist(dim=0), Concatenate(dim=1)], ), WeightConverter( source_patterns="feed_forward.experts.*.down_proj.weight", target_patterns="feed_forward.experts.down_proj", operations=[MergeModulelist(dim=0)], ), ], "timm_wrapper": [ # Simply add the prefix `timm_model` # TODO: Would be probably much cleaner with a `add_prefix` argument in WeightRenaming WeightRenaming( source_patterns=r"(.+)", target_patterns=r"timm_model.\1", ) ], "legacy": [ WeightRenaming( source_patterns="LayerNorm.gamma", target_patterns="LayerNorm.weight", ), WeightRenaming( source_patterns="LayerNorm.beta", target_patterns="LayerNorm.bias", ), ], } if hasattr(torch.nn.utils.parametrizations, "weight_norm"): mapping["legacy"] += [ WeightRenaming( source_patterns=".weight_g$", target_patterns=".parametrizations.weight.original0", ), WeightRenaming( source_patterns=".weight_v$", target_patterns=".parametrizations.weight.original1", ), ] else: mapping["legacy"] += [ WeightRenaming( source_patterns="parametrizations.weight.original0", target_patterns="weight_g", ), WeightRenaming( source_patterns="parametrizations.weight.original1", target_patterns="weight_v", ), ] mapping["deepseek_v2"] = mapping["qwen2_moe"].copy() mapping["deepseek_v3"] = mapping["qwen2_moe"].copy() mapping["dots1"] = mapping["qwen2_moe"].copy() mapping["ernie4_5_moe"] = mapping["qwen2_moe"].copy() mapping["ernie4_5_moe"] += [ WeightRenaming("mlp.moe_statics.e_score_correction_bias", "mlp.gate.moe_statics.e_score_correction_bias") ] mapping["glm4_moe"] = mapping["qwen2_moe"].copy() mapping["glm4v_moe"] = mapping["qwen2_moe"].copy() mapping["longcat_flash"] = mapping["qwen2_moe"].copy() mapping["qwen3_moe"] = mapping["qwen2_moe"].copy() mapping["qwen3_omni_moe"] = mapping["qwen2_moe"].copy() mapping["qwen3_next"] = mapping["qwen2_moe"].copy() mapping["qwen3_vl_moe"] = mapping["qwen2_moe"].copy() mapping["hunyuan_v1_moe"] = mapping["qwen2_moe"].copy() mapping["minimax"] = mapping["mixtral"].copy() mapping["flex_olmo"] = mapping["qwen2_moe"].copy() mapping["olmoe"] = mapping["qwen2_moe"].copy() return mapping _checkpoint_conversion_mapping_cache = None def get_checkpoint_conversion_mapping(model_type): global _checkpoint_conversion_mapping_cache if _checkpoint_conversion_mapping_cache is None: _checkpoint_conversion_mapping_cache = _build_checkpoint_conversion_mapping() return deepcopy(_checkpoint_conversion_mapping_cache.get(model_type)) def register_checkpoint_conversion_mapping( model_type: str, mapping: list[WeightConverter | WeightRenaming], overwrite: bool = False ) -> None: global _checkpoint_conversion_mapping_cache if _checkpoint_conversion_mapping_cache is None: _checkpoint_conversion_mapping_cache = _build_checkpoint_conversion_mapping() if model_type in _checkpoint_conversion_mapping_cache and not overwrite: raise ValueError(f"Model type {model_type} already exists in the checkpoint conversion mapping.") _checkpoint_conversion_mapping_cache[model_type] = mapping # DO NOT MODIFY, KEPT FOR BC ONLY VLMS = [ "aria", "ayavision", "colpali", "emu3", "fuyu", "gotocr2", "gemma3", "internvl", "llava", # all llava prefixed models fall under this check "mistral3", "mllama", "paligemma", "shieldgemma2", "qwen2vl", "qwen2_5_vl", "videollava", "vipllava", "sam3_video", "sam3", "sam3_tracker", "sam3_tracker_video", "paddleocrvl", "ernie4_5_vl_moe", ] def get_model_conversion_mapping( model: PreTrainedModel, key_mapping: dict[str, str] | None = None, hf_quantizer: HfQuantizer | None = None, add_legacy: bool = True, ) -> list[WeightConverter | WeightRenaming]: """ For a given `model`, obtain the weight conversion mapping if any are registered either as a simple renaming `_checkpoint_conversion_mapping` class argument, or in the general WeightConverter mapping. """ weight_conversions = [] # Load models with explicit, user-provided key mapping if key_mapping is not None: weight_conversions = [WeightRenaming(source_patterns=k, target_patterns=v) for k, v in key_mapping.items()] elif any( allowed_name in class_name.__name__.lower() for class_name in model.__class__.__mro__[:-1] for allowed_name in VLMS ): weight_conversions = [ WeightRenaming(source_patterns=k, target_patterns=v) for k, v in model._checkpoint_conversion_mapping.items() ] # TODO: should be checked recursively on submodels!! model_type = getattr(model.config, "model_type", None) if model_type is not None: model_specific_conversions = get_checkpoint_conversion_mapping(model_type) if model_specific_conversions is not None: weight_conversions.extend(model_specific_conversions) if add_legacy: weight_conversions.extend(get_checkpoint_conversion_mapping("legacy")) # Add the ones from the quantizer as well if provided if hf_quantizer is not None: weight_conversions.extend(hf_quantizer.get_weight_conversions()) return weight_conversions
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/video_utils.py
src/transformers/video_utils.py
# coding=utf-8 # Copyright 2025 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import warnings from collections.abc import Callable, Iterable, Mapping from contextlib import redirect_stdout from dataclasses import dataclass, fields from io import BytesIO from typing import NewType, Optional, Union from urllib.parse import urlparse import httpx import numpy as np from .image_transforms import PaddingMode, to_channel_dimension_format from .image_utils import ChannelDimension, infer_channel_dimension_format, is_valid_image from .utils import ( is_av_available, is_cv2_available, is_decord_available, is_numpy_array, is_torch_available, is_torch_tensor, is_torchcodec_available, is_torchvision_available, is_vision_available, is_yt_dlp_available, logging, requires_backends, ) if is_vision_available(): import PIL.Image import PIL.ImageOps if is_torchvision_available(): from torchvision import io as torchvision_io if is_torch_available(): import torch logger = logging.get_logger(__name__) URL = NewType("URL", str) Path = NewType("Path", str) VideoInput = Union[ list["PIL.Image.Image"], np.ndarray, "torch.Tensor", list[np.ndarray], list["torch.Tensor"], list[list["PIL.Image.Image"]], list[list[np.ndarray]], list[list["torch.Tensor"]], URL, list[URL], list[list[URL]], Path, list[Path], list[list[Path]], ] @dataclass class VideoMetadata(Mapping): total_num_frames: int fps: Optional[float] = None width: Optional[int] = None height: Optional[int] = None duration: Optional[float] = None video_backend: Optional[str] = None frames_indices: Optional[list[int]] = None def __iter__(self): return (f.name for f in fields(self)) def __len__(self): return len(fields(self)) def __getitem__(self, item): return getattr(self, item) def __setitem__(self, key, value): return setattr(self, key, value) @property def timestamps(self) -> list[float]: "Timestamps of the sampled frames in seconds." if self.fps is None or self.frames_indices is None: raise ValueError("Cannot infer video `timestamps` when `fps` or `frames_indices` is None.") return [frame_idx / self.fps for frame_idx in self.frames_indices] @property def sampled_fps(self) -> float: "FPS of the sampled video." if self.frames_indices is None or self.total_num_frames is None or self.fps is None: return self.fps or 24 return len(self.frames_indices) / self.total_num_frames * self.fps def update(self, dictionary): for key, value in dictionary.items(): if hasattr(self, key): setattr(self, key, value) VideoMetadataType = Union[ VideoMetadata, dict, list[Union[dict, VideoMetadata]], list[list[Union[dict, VideoMetadata]]] ] def is_valid_video_frame(frame): return isinstance(frame, PIL.Image.Image) or ( (is_numpy_array(frame) or is_torch_tensor(frame)) and frame.ndim == 3 ) def is_valid_video(video): if not isinstance(video, (list, tuple)): return (is_numpy_array(video) or is_torch_tensor(video)) and video.ndim == 4 return video and all(is_valid_video_frame(frame) for frame in video) def valid_videos(videos): # If we have a list of videos, it could be either one video as list of frames or a batch if isinstance(videos, (list, tuple)): for video_or_frame in videos: if not (is_valid_video(video_or_frame) or is_valid_video_frame(video_or_frame)): return False # If not a list, then we have a single 4D video or 5D batched tensor elif not is_valid_video(videos) or videos.ndim == 5: return False return True def is_batched_video(videos): if isinstance(videos, (list, tuple)): return is_valid_video(videos[0]) elif (is_numpy_array(videos) or is_torch_tensor(videos)) and videos.ndim == 5: return True return False def is_scaled_video(video: np.ndarray) -> bool: """ Checks to see whether the pixel values have already been rescaled to [0, 1]. """ # It's possible the video has pixel values in [0, 255] but is of floating type return np.min(video) >= 0 and np.max(video) <= 1 def convert_pil_frames_to_video(videos: list[VideoInput]) -> list[Union[np.ndarray, "torch.Tensor"]]: """ Given a batch of videos, converts each video to a 4D array. If video is already in array type, it is simply returned. We assume that all inputs in the list are in the same format, based on the type of the first element. Args: videos (`VideoInput`): Video inputs to turn into a list of videos. """ if not (isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0])): return videos video_converted = [] for video in videos: video = [np.array(frame) for frame in video] video = np.stack(video) video_converted.append(video) return video_converted def make_batched_videos(videos) -> list[Union[np.ndarray, "torch.Tensor", "URL", "Path"]]: """ Ensure that the input is a list of videos. If the input is a single video, it is converted to a list of length 1. If the input is a batch of videos, it is converted to a list of 4D video arrays. Videos passed as list `PIL.Image` frames are converted to 4D arrays. We assume that all inputs in the list are in the same format, based on the type of the first element. Args: videos (`VideoInput`): Video inputs to turn into a list of videos. """ # Early exit for deeply nested list of image frame paths. We shouldn't flatten them try: if isinstance(videos[0][0], list) and isinstance(videos[0][0][0], str): return [image_paths for sublist in videos for image_paths in sublist] except (IndexError, TypeError): pass if isinstance(videos, str) or is_valid_video(videos): return convert_pil_frames_to_video([videos]) # only one frame passed, thus we unsqueeze time dim elif is_valid_image(videos): if isinstance(videos, PIL.Image.Image): videos = np.array(videos) return [videos[None, ...]] elif not isinstance(videos, list): raise ValueError( f"Invalid video input. Expected either a list of video frames or an input of 4 or 5 dimensions, but got" f" type {type(videos)}." ) # Recursively flatten any nested structure flat_videos_list = [] for item in videos: if isinstance(item, str) or is_valid_video(item): flat_videos_list.append(item) elif isinstance(item, list) and item: flat_videos_list.extend(make_batched_videos(item)) flat_videos_list = convert_pil_frames_to_video(flat_videos_list) return flat_videos_list def make_batched_metadata(videos: VideoInput, video_metadata: VideoMetadataType) -> list[VideoMetadata]: if video_metadata is None: # Create default metadata and fill attributes we can infer from given video video_metadata = [ { "total_num_frames": len(video), "fps": None, "duration": None, "frames_indices": list(range(len(video))), "height": get_video_size(video)[0] if is_valid_video(video) else None, "width": get_video_size(video)[1] if is_valid_video(video) else None, } for video in videos ] if isinstance(video_metadata, list): # Flatten if nested list if isinstance(video_metadata[0], list): video_metadata = [ VideoMetadata(**metadata) for metadata_list in video_metadata for metadata in metadata_list ] # Simply wrap in VideoMetadata if simple dict elif isinstance(video_metadata[0], dict): video_metadata = [VideoMetadata(**metadata) for metadata in video_metadata] else: # Create a batched list from single object video_metadata = [VideoMetadata(**video_metadata)] return video_metadata def get_video_size(video: np.ndarray, channel_dim: Optional[ChannelDimension] = None) -> tuple[int, int]: """ Returns the (height, width) dimensions of the video. Args: video (`np.ndarray`): The video to get the dimensions of. channel_dim (`ChannelDimension`, *optional*): Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the video. Returns: A tuple of the video's height and width. """ if channel_dim is None: channel_dim = infer_channel_dimension_format(video, num_channels=(1, 3, 4)) if channel_dim == ChannelDimension.FIRST: return video.shape[-2], video.shape[-1] elif channel_dim == ChannelDimension.LAST: return video.shape[-3], video.shape[-2] else: raise ValueError(f"Unsupported data format: {channel_dim}") def get_uniform_frame_indices(total_num_frames: int, num_frames: Optional[int] = None): """ Creates a numpy array for uniform sampling of `num_frame` frames from `total_num_frames` when loading a video. Args: total_num_frames (`int`): Total number of frames that a video has. num_frames (`int`, *optional*): Number of frames to sample uniformly. If not specified, all frames are sampled. Returns: np.ndarray: np array of frame indices that will be sampled. """ if num_frames is not None: indices = np.arange(0, total_num_frames, total_num_frames / num_frames).astype(int) else: indices = np.arange(0, total_num_frames).astype(int) return indices def default_sample_indices_fn(metadata: VideoMetadata, num_frames=None, fps=None, **kwargs): """ A default sampling function that replicates the logic used in get_uniform_frame_indices, while optionally handling `fps` if `num_frames` is not provided. Args: metadata (`VideoMetadata`): `VideoMetadata` object containing metadata about the video, such as "total_num_frames" or "fps". num_frames (`int`, *optional*): Number of frames to sample uniformly. fps (`int` or `float`, *optional*): Desired frames per second. Takes priority over num_frames if both are provided. Returns: `np.ndarray`: Array of frame indices to sample. """ total_num_frames = metadata.total_num_frames video_fps = metadata.fps # If num_frames is not given but fps is, calculate num_frames from fps if num_frames is None and fps is not None: num_frames = int(total_num_frames / video_fps * fps) if num_frames > total_num_frames: raise ValueError( f"When loading the video with fps={fps}, we computed num_frames={num_frames} " f"which exceeds total_num_frames={total_num_frames}. Check fps or video metadata." ) if num_frames is not None: indices = np.arange(0, total_num_frames, total_num_frames / num_frames, dtype=int) else: indices = np.arange(0, total_num_frames, dtype=int) return indices def read_video_opencv( video_path: Union["URL", "Path"], sample_indices_fn: Callable, **kwargs, ) -> tuple[np.ndarray, VideoMetadata]: """ Decode a video using the OpenCV backend. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`): A callable function that will return indices at which the video should be sampled. If the video has to be loaded using by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`. If not provided, simple uniform sampling with fps is performed. Example: def sample_indices_fn(metadata, **kwargs): return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int) Returns: tuple[`np.ndarray`, `VideoMetadata`]: A tuple containing: - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]). - `VideoMetadata` object. """ # Lazy import cv2 requires_backends(read_video_opencv, ["cv2"]) import cv2 video = cv2.VideoCapture(video_path) total_num_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) video_fps = video.get(cv2.CAP_PROP_FPS) duration = total_num_frames / video_fps if video_fps else 0 metadata = VideoMetadata( total_num_frames=int(total_num_frames), fps=float(video_fps), duration=float(duration), video_backend="opencv", height=int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)), width=int(video.get(cv2.CAP_PROP_FRAME_WIDTH)), ) indices = sample_indices_fn(metadata=metadata, **kwargs) index = 0 frames = [] while video.isOpened(): success, frame = video.read() if not success: break if index in indices: height, width, channel = frame.shape frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frames.append(frame[0:height, 0:width, 0:channel]) if success: index += 1 if index >= total_num_frames: break video.release() metadata.frames_indices = indices return np.stack(frames), metadata def read_video_decord( video_path: Union["URL", "Path"], sample_indices_fn: Callable, **kwargs, ): """ Decode a video using the Decord backend. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`): A callable function that will return indices at which the video should be sampled. If the video has to be loaded using by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`. If not provided, simple uniform sampling with fps is performed. Example: def sample_indices_fn(metadata, **kwargs): return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int) Returns: tuple[`np.array`, `VideoMetadata`]: A tuple containing: - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]). - `VideoMetadata` object. """ # Lazy import from decord requires_backends(read_video_decord, ["decord"]) from decord import VideoReader, cpu vr = VideoReader(uri=video_path, ctx=cpu(0)) # decord has problems with gpu video_fps = vr.get_avg_fps() total_num_frames = len(vr) duration = total_num_frames / video_fps if video_fps else 0 metadata = VideoMetadata( total_num_frames=int(total_num_frames), fps=float(video_fps), duration=float(duration), video_backend="decord", ) indices = sample_indices_fn(metadata=metadata, **kwargs) video = vr.get_batch(indices).asnumpy() metadata.update( { "frames_indices": indices, "height": video.shape[1], "width": video.shape[2], } ) return video, metadata def read_video_pyav( video_path: Union["URL", "Path"], sample_indices_fn: Callable, **kwargs, ): """ Decode the video with PyAV decoder. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`, *optional*): A callable function that will return indices at which the video should be sampled. If the video has to be loaded using by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`. If not provided, simple uniform sampling with fps is performed. Example: def sample_indices_fn(metadata, **kwargs): return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int) Returns: tuple[`np.array`, `VideoMetadata`]: A tuple containing: - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]). - `VideoMetadata` object. """ # Lazy import av requires_backends(read_video_pyav, ["av"]) import av container = av.open(video_path) total_num_frames = container.streams.video[0].frames video_fps = container.streams.video[0].average_rate # should we better use `av_guess_frame_rate`? duration = total_num_frames / video_fps if video_fps else 0 metadata = VideoMetadata( total_num_frames=int(total_num_frames), fps=float(video_fps), duration=float(duration), video_backend="pyav", height=container.streams.video[0].height, width=container.streams.video[0].width, ) indices = sample_indices_fn(metadata=metadata, **kwargs) frames = [] container.seek(0) end_index = indices[-1] for i, frame in enumerate(container.decode(video=0)): if i > end_index: break if i >= 0 and i in indices: frames.append(frame) video = np.stack([x.to_ndarray(format="rgb24") for x in frames]) metadata.frames_indices = indices return video, metadata def read_video_torchvision( video_path: Union["URL", "Path"], sample_indices_fn: Callable, **kwargs, ): """ Decode the video with torchvision decoder. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`, *optional*): A callable function that will return indices at which the video should be sampled. If the video has to be loaded using by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`. If not provided, simple uniform sampling with fps is performed. Example: def sample_indices_fn(metadata, **kwargs): return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int) Returns: tuple[`torch.Tensor`, `VideoMetadata`]: A tuple containing: - Torch tensor of frames in RGB (shape: [num_frames, height, width, 3]). - `VideoMetadata` object. """ warnings.warn( "Using `torchvision` for video decoding is deprecated and will be removed in future versions. " "Please use `torchcodec` instead." ) video, _, info = torchvision_io.read_video( video_path, start_pts=0.0, end_pts=None, pts_unit="sec", output_format="TCHW", ) video_fps = info["video_fps"] total_num_frames = video.size(0) duration = total_num_frames / video_fps if video_fps else 0 metadata = VideoMetadata( total_num_frames=int(total_num_frames), fps=float(video_fps), duration=float(duration), video_backend="torchvision", ) indices = sample_indices_fn(metadata=metadata, **kwargs) video = video[indices].contiguous() metadata.update( { "frames_indices": indices, "height": video.shape[2], "width": video.shape[3], } ) return video, metadata def read_video_torchcodec( video_path: Union["URL", "Path"], sample_indices_fn: Callable, **kwargs, ): """ Decode the video with torchcodec decoder. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`): A callable function that will return indices at which the video should be sampled. If the video has to be loaded using by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`. If not provided, simple uniform sampling with fps is performed. Example: def sample_indices_fn(metadata, **kwargs): return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int) Returns: Tuple[`torch.Tensor`, `VideoMetadata`]: A tuple containing: - Torch tensor of frames in RGB (shape: [num_frames, height, width, 3]). - `VideoMetadata` object. """ # Lazy import torchcodec requires_backends(read_video_torchcodec, ["torchcodec"]) from torchcodec.decoders import VideoDecoder # VideoDecoder expects a string for device, default to "cpu" if None decoder = VideoDecoder( video_path, # Interestingly `exact` mode takes less than approximate when we load the whole video seek_mode="exact", # Allow FFmpeg decide on the number of threads for efficiency num_ffmpeg_threads=0, device=kwargs.get("device", "cpu"), ) total_num_frames = decoder.metadata.num_frames video_fps = decoder.metadata.average_fps metadata = VideoMetadata( total_num_frames=total_num_frames, fps=video_fps, duration=decoder.metadata.duration_seconds, video_backend="torchcodec", height=decoder.metadata.height, width=decoder.metadata.width, ) indices = sample_indices_fn(metadata=metadata, **kwargs) video = decoder.get_frames_at(indices=indices).data.contiguous() metadata.frames_indices = indices return video, metadata VIDEO_DECODERS = { "decord": read_video_decord, "opencv": read_video_opencv, "pyav": read_video_pyav, "torchvision": read_video_torchvision, "torchcodec": read_video_torchcodec, } def load_video( video: VideoInput, num_frames: Optional[int] = None, fps: Optional[Union[int, float]] = None, backend: str = "pyav", sample_indices_fn: Optional[Callable] = None, **kwargs, ) -> np.ndarray: """ Loads `video` to a numpy array. Args: video (`VideoInput`): The video to convert to the numpy array format. Can be a link to video or local path. num_frames (`int`, *optional*): Number of frames to sample uniformly. If not passed, the whole video is loaded. fps (`int` or `float`, *optional*): Number of frames to sample per second. Should be passed only when `num_frames=None`. If not specified and `num_frames==None`, all frames are sampled. backend (`str`, *optional*, defaults to `"pyav"`): The backend to use when loading the video. Can be any of ["decord", "pyav", "opencv", "torchvision", "torchcodec"]. Defaults to "pyav". sample_indices_fn (`Callable`, *optional*): A callable function that will return indices at which the video should be sampled. If the video has to be loaded using by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`. If not provided, simple uniformt sampling with fps is performed, otherwise `sample_indices_fn` has priority over other args. The function expects at input the all args along with all kwargs passed to `load_video` and should output valid indices at which the video should be sampled. For example: Example: def sample_indices_fn(metadata, **kwargs): return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int) Returns: tuple[`np.ndarray`, Dict]: A tuple containing: - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]). - Metadata dictionary. """ # If `sample_indices_fn` is given, we can accept any args as those might be needed by custom `sample_indices_fn` if fps is not None and num_frames is not None and sample_indices_fn is None: raise ValueError( "`num_frames`, `fps`, and `sample_indices_fn` are mutually exclusive arguments, please use only one!" ) # If user didn't pass a sampling function, create one on the fly with default logic if sample_indices_fn is None: def sample_indices_fn_func(metadata, **fn_kwargs): return default_sample_indices_fn(metadata, num_frames=num_frames, fps=fps, **fn_kwargs) sample_indices_fn = sample_indices_fn_func # Early exit if provided an array or `PIL` frames if not isinstance(video, str): metadata = [None] * len(video) return video, metadata if urlparse(video).netloc in ["www.youtube.com", "youtube.com"]: if not is_yt_dlp_available(): raise ImportError("To load a video from YouTube url you have to install `yt_dlp` first.") # Lazy import from yt_dlp requires_backends(load_video, ["yt_dlp"]) from yt_dlp import YoutubeDL buffer = BytesIO() with redirect_stdout(buffer), YoutubeDL() as f: f.download([video]) bytes_obj = buffer.getvalue() file_obj = BytesIO(bytes_obj) elif video.startswith("http://") or video.startswith("https://"): file_obj = BytesIO(httpx.get(video, follow_redirects=True).content) elif os.path.isfile(video): file_obj = video else: raise TypeError("Incorrect format used for video. Should be an url linking to an video or a local path.") # can also load with decord, but not cv2/torchvision # both will fail in case of url links video_is_url = video.startswith("http://") or video.startswith("https://") if video_is_url and backend == "opencv": raise ValueError("If you are trying to load a video from URL, you cannot use 'opencv' as backend") if ( (not is_decord_available() and backend == "decord") or (not is_av_available() and backend == "pyav") or (not is_cv2_available() and backend == "opencv") or (not is_torchvision_available() and backend == "torchvision") or (not is_torchcodec_available() and backend == "torchcodec") ): raise ImportError( f"You chose backend={backend} for loading the video but the required library is not found in your environment " f"Make sure to install {backend} before loading the video." ) video_decoder = VIDEO_DECODERS[backend] video, metadata = video_decoder(file_obj, sample_indices_fn, **kwargs) return video, metadata def convert_to_rgb( video: np.ndarray, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """ Convert video to RGB by blending the transparency layer if it's in RGBA format, otherwise simply returns it. Args: video (`np.ndarray`): The video to convert. input_data_format (`ChannelDimension`, *optional*): The channel dimension format of the input video. If unset, will use the inferred format from the input. """ if not isinstance(video, np.ndarray): raise TypeError(f"Video has to be a numpy array to convert to RGB format, but found {type(video)}") # np.array usually comes with ChannelDimension.LAST so let's convert it if input_data_format is None: input_data_format = infer_channel_dimension_format(video) video = to_channel_dimension_format(video, ChannelDimension.FIRST, input_channel_dim=input_data_format) # 3 channels for RGB already if video.shape[-3] == 3: return video # Grayscale video so we repeat it 3 times for each channel if video.shape[-3] == 1: return video.repeat(3, -3) if not (video[..., 3, :, :] < 255).any(): return video # There is a transparency layer, blend it with a white background. # Calculate the alpha proportion for blending. alpha = video[..., 3, :, :] / 255.0 video = (1 - alpha[..., None, :, :]) * 255 + alpha[..., None, :, :] * video[..., 3, :, :] return video def pad( video: np.ndarray, padding: Union[int, tuple[int, int], Iterable[tuple[int, int]]], mode: PaddingMode = PaddingMode.CONSTANT, constant_values: Union[float, Iterable[float]] = 0.0, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """ Pads the `video` with the specified (height, width) `padding` and `mode`. Args: video (`np.ndarray`): The video to pad. padding (`int` or `tuple[int, int]` or `Iterable[tuple[int, int]]`): Padding to apply to the edges of the height, width axes. Can be one of three formats: - `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis. - `((before, after),)` yields same before and after pad for height and width. - `(pad,)` or int is a shortcut for before = after = pad width for all axes. mode (`PaddingMode`): The padding mode to use. Can be one of: - `"constant"`: pads with a constant value. - `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the vector along each axis. - `"replicate"`: pads with the replication of the last value on the edge of the array along each axis. - `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array. constant_values (`float` or `Iterable[float]`, *optional*): The value to use for the padding if `mode` is `"constant"`. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the output video. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: video in (num_frames, num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: video in (num_frames, height, width, num_channels) format. If unset, will use same as the input video. input_data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the input video. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: video in (num_frames, num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: video in (num_frames, height, width, num_channels) format. If unset, will use the inferred format of the input video. Returns: `np.ndarray`: The padded video. """ if input_data_format is None: input_data_format = infer_channel_dimension_format(video) def _expand_for_data_format(values): """ Convert values to be in the format expected by np.pad based on the data format. """ if isinstance(values, (int, float)): values = ((values, values), (values, values)) elif isinstance(values, tuple) and len(values) == 1: values = ((values[0], values[0]), (values[0], values[0])) elif isinstance(values, tuple) and len(values) == 2 and isinstance(values[0], int): values = (values, values) elif isinstance(values, tuple) and len(values) == 2 and isinstance(values[0], tuple): pass else: raise ValueError(f"Unsupported format: {values}") # add 0 for channel dimension values = ( ((0, 0), (0, 0), *values) if input_data_format == ChannelDimension.FIRST else ((0, 0), *values, (0, 0)) ) # Add additional padding if there's a batch dimension values = (0, *values) if video.ndim == 5 else values return values padding_map = { PaddingMode.CONSTANT: "constant", PaddingMode.REFLECT: "reflect", PaddingMode.REPLICATE: "replicate", PaddingMode.SYMMETRIC: "symmetric", } padding = _expand_for_data_format(padding) pad_kwargs = {} if mode not in padding_map: raise ValueError(f"Invalid padding mode: {mode}") elif mode == PaddingMode.CONSTANT:
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/modelcard.py
src/transformers/modelcard.py
# Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Configuration base class and utilities.""" import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Optional, Union import httpx import yaml from huggingface_hub import is_offline_mode, model_info from huggingface_hub.errors import OfflineModeIsEnabled from huggingface_hub.utils import HFValidationError from . import __version__ from .models.auto.modeling_auto import ( MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_FOR_CTC_MAPPING_NAMES, MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES, MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES, ) from .training_args import ParallelMode from .utils import ( MODEL_CARD_NAME, cached_file, is_datasets_available, is_tokenizers_available, is_torch_available, logging, ) TASK_MAPPING = { "text-generation": MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, "image-classification": MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, "image-segmentation": MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, "fill-mask": MODEL_FOR_MASKED_LM_MAPPING_NAMES, "object-detection": MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, "question-answering": MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, "text2text-generation": MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, "text-classification": MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, "table-question-answering": MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES, "token-classification": MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, "audio-classification": MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, "automatic-speech-recognition": {**MODEL_FOR_CTC_MAPPING_NAMES, **MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES}, "zero-shot-image-classification": MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES, "image-text-to-text": MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES, } logger = logging.get_logger(__name__) class ModelCard: r""" Structured Model Card class. Store model card as well as methods for loading/downloading/saving model cards. Please read the following paper for details and explanation on the sections: "Model Cards for Model Reporting" by Margaret Mitchell, Simone Wu, Andrew Zaldivar, Parker Barnes, Lucy Vasserman, Ben Hutchinson, Elena Spitzer, Inioluwa Deborah Raji and Timnit Gebru for the proposal behind model cards. Link: https://huggingface.co/papers/1810.03993 Note: A model card can be loaded and saved to disk. """ def __init__(self, **kwargs): warnings.warn( "The class `ModelCard` is deprecated and will be removed in version 5 of Transformers", FutureWarning ) # Recommended attributes from https://huggingface.co/papers/1810.03993 (see papers) self.model_details = kwargs.pop("model_details", {}) self.intended_use = kwargs.pop("intended_use", {}) self.factors = kwargs.pop("factors", {}) self.metrics = kwargs.pop("metrics", {}) self.evaluation_data = kwargs.pop("evaluation_data", {}) self.training_data = kwargs.pop("training_data", {}) self.quantitative_analyses = kwargs.pop("quantitative_analyses", {}) self.ethical_considerations = kwargs.pop("ethical_considerations", {}) self.caveats_and_recommendations = kwargs.pop("caveats_and_recommendations", {}) # Open additional attributes for key, value in kwargs.items(): try: setattr(self, key, value) except AttributeError as err: logger.error(f"Can't set {key} with value {value} for {self}") raise err def save_pretrained(self, save_directory_or_file): """Save a model card object to the directory or file `save_directory_or_file`.""" if os.path.isdir(save_directory_or_file): # If we save using the predefined names, we can load using `from_pretrained` output_model_card_file = os.path.join(save_directory_or_file, MODEL_CARD_NAME) else: output_model_card_file = save_directory_or_file self.to_json_file(output_model_card_file) logger.info(f"Model card saved in {output_model_card_file}") @classmethod def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): r""" Instantiate a [`ModelCard`] from a pre-trained model model card. Parameters: pretrained_model_name_or_path: either: - a string, the *model id* of a pretrained model card hosted inside a model repo on huggingface.co. - a path to a *directory* containing a model card file saved using the [`~ModelCard.save_pretrained`] method, e.g.: `./my_model_directory/`. - a path or url to a saved model card JSON *file*, e.g.: `./my_model_directory/modelcard.json`. cache_dir: (*optional*) string: Path to a directory in which a downloaded pre-trained model card should be cached if the standard cache should not be used. kwargs: (*optional*) dict: key/value pairs with which to update the ModelCard object after loading. - The values in kwargs of any keys which are model card attributes will be used to override the loaded values. - Behavior concerning key/value pairs whose keys are *not* model card attributes is controlled by the *return_unused_kwargs* keyword parameter. proxies: (*optional*) dict, default None: A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request. return_unused_kwargs: (*optional*) bool: - If False, then this function returns just the final model card object. - If True, then this functions returns a tuple *(model card, unused_kwargs)* where *unused_kwargs* is a dictionary consisting of the key/value pairs whose keys are not model card attributes: ie the part of kwargs which has not been used to update *ModelCard* and is otherwise ignored. Examples: ```python # Download model card from huggingface.co and cache. modelcard = ModelCard.from_pretrained("google-bert/bert-base-uncased") # Model card was saved using *save_pretrained('./test/saved_model/')* modelcard = ModelCard.from_pretrained("./test/saved_model/") modelcard = ModelCard.from_pretrained("./test/saved_model/modelcard.json") modelcard = ModelCard.from_pretrained("google-bert/bert-base-uncased", output_attentions=True, foo=False) ```""" cache_dir = kwargs.pop("cache_dir", None) proxies = kwargs.pop("proxies", None) return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) from_pipeline = kwargs.pop("_from_pipeline", None) user_agent = {"file_type": "model_card"} if from_pipeline is not None: user_agent["using_pipeline"] = from_pipeline is_local = os.path.isdir(pretrained_model_name_or_path) if os.path.isfile(pretrained_model_name_or_path): resolved_model_card_file = pretrained_model_name_or_path is_local = True else: try: # Load from URL or cache if already cached resolved_model_card_file = cached_file( pretrained_model_name_or_path, filename=MODEL_CARD_NAME, cache_dir=cache_dir, proxies=proxies, user_agent=user_agent, ) if is_local: logger.info(f"loading model card file {resolved_model_card_file}") else: logger.info(f"loading model card file {MODEL_CARD_NAME} from cache at {resolved_model_card_file}") # Load model card modelcard = cls.from_json_file(resolved_model_card_file) except (OSError, json.JSONDecodeError): # We fall back on creating an empty model card modelcard = cls() # Update model card with kwargs if needed to_remove = [] for key, value in kwargs.items(): if hasattr(modelcard, key): setattr(modelcard, key, value) to_remove.append(key) for key in to_remove: kwargs.pop(key, None) logger.info(f"Model card: {modelcard}") if return_unused_kwargs: return modelcard, kwargs else: return modelcard @classmethod def from_dict(cls, json_object): """Constructs a `ModelCard` from a Python dictionary of parameters.""" return cls(**json_object) @classmethod def from_json_file(cls, json_file): """Constructs a `ModelCard` from a json file of parameters.""" with open(json_file, encoding="utf-8") as reader: text = reader.read() dict_obj = json.loads(text) return cls(**dict_obj) def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return str(self.to_json_string()) def to_dict(self): """Serializes this instance to a Python dictionary.""" output = copy.deepcopy(self.__dict__) return output def to_json_string(self): """Serializes this instance to a JSON string.""" return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" def to_json_file(self, json_file_path): """Save this instance to a json file.""" with open(json_file_path, "w", encoding="utf-8") as writer: writer.write(self.to_json_string()) AUTOGENERATED_TRAINER_COMMENT = """ <!-- This model card has been generated automatically according to the information the Trainer had access to. You should probably proofread and complete it, then remove this comment. --> """ TASK_TAG_TO_NAME_MAPPING = { "fill-mask": "Masked Language Modeling", "image-classification": "Image Classification", "image-segmentation": "Image Segmentation", "multiple-choice": "Multiple Choice", "object-detection": "Object Detection", "question-answering": "Question Answering", "summarization": "Summarization", "table-question-answering": "Table Question Answering", "text-classification": "Text Classification", "text-generation": "Causal Language Modeling", "text2text-generation": "Sequence-to-sequence Language Modeling", "token-classification": "Token Classification", "translation": "Translation", "zero-shot-classification": "Zero Shot Classification", "automatic-speech-recognition": "Automatic Speech Recognition", "audio-classification": "Audio Classification", } METRIC_TAGS = [ "accuracy", "bleu", "f1", "matthews_correlation", "pearsonr", "precision", "recall", "rouge", "sacrebleu", "spearmanr", "wer", ] def _listify(obj): if obj is None: return [] elif isinstance(obj, str): return [obj] else: return obj def _insert_values_as_list(metadata, name, values): if values is None: return metadata if isinstance(values, str): values = [values] values = [v for v in values if v is not None] if len(values) == 0: return metadata metadata[name] = values return metadata def infer_metric_tags_from_eval_results(eval_results): if eval_results is None: return {} result = {} for key in eval_results: if key.lower().replace(" ", "_") in METRIC_TAGS: result[key.lower().replace(" ", "_")] = key elif key.lower() == "rouge1": result["rouge"] = key return result def _insert_value(metadata, name, value): if value is None: return metadata metadata[name] = value return metadata def is_hf_dataset(dataset): if not is_datasets_available(): return False from datasets import Dataset, IterableDataset return isinstance(dataset, (Dataset, IterableDataset)) def _get_mapping_values(mapping): result = [] for v in mapping.values(): if isinstance(v, (tuple, list)): result += list(v) else: result.append(v) return result @dataclass class TrainingSummary: model_name: str language: Optional[Union[str, list[str]]] = None license: Optional[str] = None tags: Optional[Union[str, list[str]]] = None finetuned_from: Optional[str] = None tasks: Optional[Union[str, list[str]]] = None dataset: Optional[Union[str, list[str]]] = None dataset_tags: Optional[Union[str, list[str]]] = None dataset_args: Optional[Union[str, list[str]]] = None dataset_metadata: Optional[dict[str, Any]] = None eval_results: Optional[dict[str, float]] = None eval_lines: Optional[list[str]] = None hyperparameters: Optional[dict[str, Any]] = None source: Optional[str] = "trainer" def __post_init__(self): # Infer default license from the checkpoint used, if possible. if ( self.license is None and not is_offline_mode() and self.finetuned_from is not None and len(self.finetuned_from) > 0 ): try: info = model_info(self.finetuned_from) for tag in info.tags: if tag.startswith("license:"): self.license = tag[8:] except (httpx.HTTPError, HFValidationError, OfflineModeIsEnabled): pass def create_model_index(self, metric_mapping): model_index = {"name": self.model_name} # Dataset mapping tag -> name dataset_names = _listify(self.dataset) dataset_tags = _listify(self.dataset_tags) dataset_args = _listify(self.dataset_args) dataset_metadata = _listify(self.dataset_metadata) if len(dataset_args) < len(dataset_tags): dataset_args = dataset_args + [None] * (len(dataset_tags) - len(dataset_args)) dataset_mapping = dict(zip(dataset_tags, dataset_names)) dataset_arg_mapping = dict(zip(dataset_tags, dataset_args)) dataset_metadata_mapping = dict(zip(dataset_tags, dataset_metadata)) task_mapping = { task: TASK_TAG_TO_NAME_MAPPING[task] for task in _listify(self.tasks) if task in TASK_TAG_TO_NAME_MAPPING } model_index["results"] = [] if len(task_mapping) == 0 and len(dataset_mapping) == 0: return [model_index] if len(task_mapping) == 0: task_mapping = {None: None} if len(dataset_mapping) == 0: dataset_mapping = {None: None} # One entry per dataset and per task all_possibilities = [(task_tag, ds_tag) for task_tag in task_mapping for ds_tag in dataset_mapping] for task_tag, ds_tag in all_possibilities: result = {} if task_tag is not None: result["task"] = {"name": task_mapping[task_tag], "type": task_tag} if ds_tag is not None: metadata = dataset_metadata_mapping.get(ds_tag, {}) result["dataset"] = { "name": dataset_mapping[ds_tag], "type": ds_tag, **metadata, } if dataset_arg_mapping[ds_tag] is not None: result["dataset"]["args"] = dataset_arg_mapping[ds_tag] if len(metric_mapping) > 0: result["metrics"] = [] for metric_tag, metric_name in metric_mapping.items(): result["metrics"].append( { "name": metric_name, "type": metric_tag, "value": self.eval_results[metric_name], } ) # Remove partial results to avoid the model card being rejected. if "task" in result and "dataset" in result and "metrics" in result: model_index["results"].append(result) else: logger.info(f"Dropping the following result as it does not have all the necessary fields:\n{result}") return [model_index] def create_metadata(self): metric_mapping = infer_metric_tags_from_eval_results(self.eval_results) metadata = {} metadata = _insert_value(metadata, "library_name", "transformers") metadata = _insert_values_as_list(metadata, "language", self.language) metadata = _insert_value(metadata, "license", self.license) if self.finetuned_from is not None and isinstance(self.finetuned_from, str) and len(self.finetuned_from) > 0: metadata = _insert_value(metadata, "base_model", self.finetuned_from) metadata = _insert_values_as_list(metadata, "tags", self.tags) metadata = _insert_values_as_list(metadata, "datasets", self.dataset_tags) metadata = _insert_values_as_list(metadata, "metrics", list(metric_mapping.keys())) metadata["model-index"] = self.create_model_index(metric_mapping) return metadata def to_model_card(self): model_card = "" metadata = yaml.dump(self.create_metadata(), sort_keys=False) if len(metadata) > 0: model_card = f"---\n{metadata}---\n" # Now the model card for realsies. if self.source == "trainer": model_card += AUTOGENERATED_TRAINER_COMMENT model_card += f"\n# {self.model_name}\n\n" if self.finetuned_from is None: model_card += "This model was trained from scratch on " else: model_card += ( "This model is a fine-tuned version of" f" [{self.finetuned_from}](https://huggingface.co/{self.finetuned_from}) on " ) if self.dataset is None or (isinstance(self.dataset, list) and len(self.dataset) == 0): model_card += "an unknown dataset." else: if isinstance(self.dataset, str): model_card += f"the {self.dataset} dataset." elif isinstance(self.dataset, (tuple, list)) and len(self.dataset) == 1: model_card += f"the {self.dataset[0]} dataset." else: model_card += ( ", ".join([f"the {ds}" for ds in self.dataset[:-1]]) + f" and the {self.dataset[-1]} datasets." ) if self.eval_results is not None: model_card += "\nIt achieves the following results on the evaluation set:\n" model_card += "\n".join([f"- {name}: {_maybe_round(value)}" for name, value in self.eval_results.items()]) model_card += "\n" model_card += "\n## Model description\n\nMore information needed\n" model_card += "\n## Intended uses & limitations\n\nMore information needed\n" model_card += "\n## Training and evaluation data\n\nMore information needed\n" model_card += "\n## Training procedure\n" model_card += "\n### Training hyperparameters\n" if self.hyperparameters is not None: model_card += "\nThe following hyperparameters were used during training:\n" model_card += "\n".join([f"- {name}: {value}" for name, value in self.hyperparameters.items()]) model_card += "\n" else: model_card += "\nMore information needed\n" if self.eval_lines is not None: model_card += "\n### Training results\n\n" model_card += make_markdown_table(self.eval_lines) model_card += "\n" model_card += "\n### Framework versions\n\n" model_card += f"- Transformers {__version__}\n" if self.source == "trainer" and is_torch_available(): import torch model_card += f"- Pytorch {torch.__version__}\n" if is_datasets_available(): import datasets model_card += f"- Datasets {datasets.__version__}\n" if is_tokenizers_available(): import tokenizers model_card += f"- Tokenizers {tokenizers.__version__}\n" return model_card @classmethod def from_trainer( cls, trainer, language=None, license=None, tags=None, model_name=None, finetuned_from=None, tasks=None, dataset_tags=None, dataset_metadata=None, dataset=None, dataset_args=None, ): # Infer default from dataset one_dataset = trainer.eval_dataset if trainer.eval_dataset is not None else trainer.train_dataset if is_hf_dataset(one_dataset) and (dataset_tags is None or dataset_args is None or dataset_metadata is None): default_tag = one_dataset.builder_name # Those are not real datasets from the Hub so we exclude them. if default_tag not in ["csv", "json", "pandas", "parquet", "text"]: if dataset_metadata is None: dataset_metadata = [{"config": one_dataset.config_name, "split": str(one_dataset.split)}] if dataset_tags is None: dataset_tags = [default_tag] if dataset_args is None: dataset_args = [one_dataset.config_name] if dataset is None and dataset_tags is not None: dataset = dataset_tags # Infer default finetuned_from if ( finetuned_from is None and hasattr(trainer.model.config, "_name_or_path") and not os.path.isdir(trainer.model.config._name_or_path) ): finetuned_from = trainer.model.config._name_or_path # Infer default task tag: if tasks is None: model_class_name = trainer.model.__class__.__name__ for task, mapping in TASK_MAPPING.items(): if model_class_name in _get_mapping_values(mapping): tasks = task if model_name is None: model_name = Path(trainer.args.output_dir).name if len(model_name) == 0: model_name = finetuned_from # Add `generated_from_trainer` to the tags if tags is None: tags = ["generated_from_trainer"] elif isinstance(tags, str) and tags != "generated_from_trainer": tags = [tags, "generated_from_trainer"] elif "generated_from_trainer" not in tags: tags.append("generated_from_trainer") _, eval_lines, eval_results = parse_log_history(trainer.state.log_history) hyperparameters = extract_hyperparameters_from_trainer(trainer) return cls( language=language, license=license, tags=tags, model_name=model_name, finetuned_from=finetuned_from, tasks=tasks, dataset=dataset, dataset_tags=dataset_tags, dataset_args=dataset_args, dataset_metadata=dataset_metadata, eval_results=eval_results, eval_lines=eval_lines, hyperparameters=hyperparameters, ) def parse_log_history(log_history): """ Parse the `log_history` of a Trainer to get the intermediate and final evaluation results. """ idx = 0 while idx < len(log_history) and "train_runtime" not in log_history[idx]: idx += 1 # If there are no training logs if idx == len(log_history): idx -= 1 while idx >= 0 and "eval_loss" not in log_history[idx]: idx -= 1 if idx >= 0: return None, None, log_history[idx] else: return None, None, None # From now one we can assume we have training logs: train_log = log_history[idx] lines = [] training_loss = "No log" for i in range(idx): if "loss" in log_history[i]: training_loss = log_history[i]["loss"] if "eval_loss" in log_history[i]: metrics = log_history[i].copy() _ = metrics.pop("total_flos", None) epoch = metrics.pop("epoch", None) step = metrics.pop("step", None) _ = metrics.pop("eval_runtime", None) _ = metrics.pop("eval_samples_per_second", None) _ = metrics.pop("eval_steps_per_second", None) values = {"Training Loss": training_loss, "Epoch": epoch, "Step": step} for k, v in metrics.items(): if k == "eval_loss": values["Validation Loss"] = v else: splits = k.split("_") name = " ".join([part.capitalize() for part in splits[1:]]) values[name] = v lines.append(values) idx = len(log_history) - 1 while idx >= 0 and "eval_loss" not in log_history[idx]: idx -= 1 if idx > 0: eval_results = {} for key, value in log_history[idx].items(): key = key.removeprefix("eval_") if key not in ["runtime", "samples_per_second", "steps_per_second", "epoch", "step"]: camel_cased_key = " ".join([part.capitalize() for part in key.split("_")]) eval_results[camel_cased_key] = value return train_log, lines, eval_results else: return train_log, lines, None def _maybe_round(v, decimals=4): if isinstance(v, float) and len(str(v).split(".")) > 1 and len(str(v).split(".")[1]) > decimals: return f"{v:.{decimals}f}" return str(v) def _regular_table_line(values, col_widths): values_with_space = [f"| {v}" + " " * (w - len(v) + 1) for v, w in zip(values, col_widths)] return "".join(values_with_space) + "|\n" def _second_table_line(col_widths): values = ["|:" + "-" * w + ":" for w in col_widths] return "".join(values) + "|\n" def make_markdown_table(lines): """ Create a nice Markdown table from the results in `lines`. """ if lines is None or len(lines) == 0: return "" col_widths = {key: len(str(key)) for key in lines[0]} for line in lines: for key, value in line.items(): if col_widths[key] < len(_maybe_round(value)): col_widths[key] = len(_maybe_round(value)) table = _regular_table_line(list(lines[0].keys()), list(col_widths.values())) table += _second_table_line(list(col_widths.values())) for line in lines: table += _regular_table_line([_maybe_round(v) for v in line.values()], list(col_widths.values())) return table _TRAINING_ARGS_KEYS = [ "learning_rate", "train_batch_size", "eval_batch_size", "seed", ] def extract_hyperparameters_from_trainer(trainer): hyperparameters = {k: getattr(trainer.args, k) for k in _TRAINING_ARGS_KEYS} if trainer.args.parallel_mode not in [ParallelMode.NOT_PARALLEL, ParallelMode.NOT_DISTRIBUTED]: hyperparameters["distributed_type"] = ( "multi-GPU" if trainer.args.parallel_mode == ParallelMode.DISTRIBUTED else trainer.args.parallel_mode.value ) if trainer.args.world_size > 1: hyperparameters["num_devices"] = trainer.args.world_size if trainer.args.gradient_accumulation_steps > 1: hyperparameters["gradient_accumulation_steps"] = trainer.args.gradient_accumulation_steps total_train_batch_size = ( trainer.args.train_batch_size * trainer.args.world_size * trainer.args.gradient_accumulation_steps ) if total_train_batch_size != hyperparameters["train_batch_size"]: hyperparameters["total_train_batch_size"] = total_train_batch_size total_eval_batch_size = trainer.args.eval_batch_size * trainer.args.world_size if total_eval_batch_size != hyperparameters["eval_batch_size"]: hyperparameters["total_eval_batch_size"] = total_eval_batch_size if trainer.args.optim: optimizer_name = trainer.args.optim optimizer_args = trainer.args.optim_args if trainer.args.optim_args else "No additional optimizer arguments" if "adam" in optimizer_name.lower(): hyperparameters["optimizer"] = ( f"Use {optimizer_name} with betas=({trainer.args.adam_beta1},{trainer.args.adam_beta2}) and" f" epsilon={trainer.args.adam_epsilon} and optimizer_args={optimizer_args}" ) else: hyperparameters["optimizer"] = f"Use {optimizer_name} and the args are:\n{optimizer_args}" hyperparameters["lr_scheduler_type"] = trainer.args.lr_scheduler_type.value if trainer.args.warmup_steps != 0.0: hyperparameters["lr_scheduler_warmup_steps"] = trainer.args.warmup_steps if trainer.args.max_steps != -1: hyperparameters["training_steps"] = trainer.args.max_steps else: hyperparameters["num_epochs"] = trainer.args.num_train_epochs if trainer.args.fp16: hyperparameters["mixed_precision_training"] = "Native AMP" if trainer.args.label_smoothing_factor != 0.0: hyperparameters["label_smoothing_factor"] = trainer.args.label_smoothing_factor return hyperparameters
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/pytorch_utils.py
src/transformers/pytorch_utils.py
# Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import inspect from collections.abc import Callable from functools import lru_cache, wraps import torch from safetensors.torch import storage_ptr, storage_size from torch import nn from .utils import ( is_torch_greater_or_equal, is_torch_xla_available, is_torchdynamo_compiling, logging, ) ALL_LAYERNORM_LAYERS = [nn.LayerNorm] logger = logging.get_logger(__name__) is_torch_greater_or_equal_than_2_8 = is_torch_greater_or_equal("2.8", accept_dev=True) is_torch_greater_or_equal_than_2_6 = is_torch_greater_or_equal("2.6", accept_dev=True) is_torch_greater_or_equal_than_2_4 = is_torch_greater_or_equal("2.4", accept_dev=True) is_torch_greater_or_equal_than_2_3 = is_torch_greater_or_equal("2.3", accept_dev=True) # For backwards compatibility (e.g. some remote codes on Hub using those variables). is_torch_greater_or_equal_than_2_2 = is_torch_greater_or_equal("2.2", accept_dev=True) is_torch_greater_or_equal_than_2_1 = is_torch_greater_or_equal("2.1", accept_dev=True) is_torch_greater_or_equal_than_2_0 = is_torch_greater_or_equal("2.0", accept_dev=True) is_torch_greater_or_equal_than_1_13 = is_torch_greater_or_equal("1.13", accept_dev=True) is_torch_greater_or_equal_than_1_12 = is_torch_greater_or_equal("1.12", accept_dev=True) # Cache this result has it's a C FFI call which can be pretty time-consuming _torch_distributed_available = torch.distributed.is_available() def softmax_backward_data(parent, grad_output, output): """ A function that calls the internal `_softmax_backward_data` PyTorch method and that adjusts the arguments according to the torch version detected. """ from torch import _softmax_backward_data return _softmax_backward_data(grad_output, output, parent.dim, output.dtype) def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: int = 0) -> nn.Linear: """ Prune a linear layer to keep only entries in index. Used to remove heads. Args: layer (`torch.nn.Linear`): The layer to prune. index (`torch.LongTensor`): The indices to keep in the layer. dim (`int`, *optional*, defaults to 0): The dimension on which to keep the indices. Returns: `torch.nn.Linear`: The pruned layer as a new layer with `requires_grad=True`. """ index = index.to(layer.weight.device) W = layer.weight.index_select(dim, index).detach().clone() if layer.bias is not None: if dim == 1: b = layer.bias.detach().clone() else: b = layer.bias[index].detach().clone() new_size = list(layer.weight.size()) new_size[dim] = len(index) new_layer = nn.Linear(new_size[1], new_size[0], bias=layer.bias is not None).to(layer.weight.device) new_layer.weight.requires_grad = False new_layer.weight.copy_(W.contiguous()) new_layer.weight.requires_grad = True if layer.bias is not None: new_layer.bias.requires_grad = False new_layer.bias.copy_(b.contiguous()) new_layer.bias.requires_grad = True return new_layer class Conv1D(nn.Module): """ 1D-convolutional layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2). Basically works like a linear layer but the weights are transposed. Args: nf (`int`): The number of output features. nx (`int`): The number of input features. """ def __init__(self, nf, nx): super().__init__() self.nf = nf self.nx = nx self.weight = nn.Parameter(torch.empty(nx, nf)) self.bias = nn.Parameter(torch.zeros(nf)) nn.init.normal_(self.weight, std=0.02) def __repr__(self) -> str: return "Conv1D(nf={nf}, nx={nx})".format(**self.__dict__) def forward(self, x): size_out = x.size()[:-1] + (self.nf,) x = torch.addmm(self.bias, x.view(-1, x.size(-1)), self.weight) x = x.view(size_out) return x def apply_chunking_to_forward( forward_fn: Callable[..., torch.Tensor], chunk_size: int, chunk_dim: int, *input_tensors, ) -> torch.Tensor: """ This function chunks the `input_tensors` into smaller input tensor parts of size `chunk_size` over the dimension `chunk_dim`. It then applies a layer `forward_fn` to each chunk independently to save memory. If the `forward_fn` is independent across the `chunk_dim` this function will yield the same result as directly applying `forward_fn` to `input_tensors`. Args: forward_fn (`Callable[..., torch.Tensor]`): The forward function of the model. chunk_size (`int`): The chunk size of a chunked tensor: `num_chunks = len(input_tensors[0]) / chunk_size`. chunk_dim (`int`): The dimension over which the `input_tensors` should be chunked. input_tensors (`tuple[torch.Tensor]`): The input tensors of `forward_fn` which will be chunked Returns: `torch.Tensor`: A tensor with the same shape as the `forward_fn` would have given if applied`. Examples: ```python # rename the usual forward() fn to forward_chunk() def forward_chunk(self, hidden_states): hidden_states = self.decoder(hidden_states) return hidden_states # implement a chunked forward function def forward(self, hidden_states): return apply_chunking_to_forward(self.forward_chunk, self.chunk_size_lm_head, self.seq_len_dim, hidden_states) ```""" assert len(input_tensors) > 0, f"{input_tensors} has to be a tuple/list of tensors" # inspect.signature exist since python 3.5 and is a python method -> no problem with backward compatibility num_args_in_forward_chunk_fn = len(inspect.signature(forward_fn).parameters) if num_args_in_forward_chunk_fn != len(input_tensors): raise ValueError( f"forward_chunk_fn expects {num_args_in_forward_chunk_fn} arguments, but only {len(input_tensors)} input " "tensors are given" ) if chunk_size > 0: tensor_shape = input_tensors[0].shape[chunk_dim] for input_tensor in input_tensors: if input_tensor.shape[chunk_dim] != tensor_shape: raise ValueError( f"All input tenors have to be of the same shape: {tensor_shape}, " f"found shape {input_tensor.shape[chunk_dim]}" ) if input_tensors[0].shape[chunk_dim] % chunk_size != 0: raise ValueError( f"The dimension to be chunked {input_tensors[0].shape[chunk_dim]} has to be a multiple of the chunk " f"size {chunk_size}" ) num_chunks = input_tensors[0].shape[chunk_dim] // chunk_size # chunk input tensor into tuples input_tensors_chunks = tuple(input_tensor.chunk(num_chunks, dim=chunk_dim) for input_tensor in input_tensors) # apply forward fn to every tuple output_chunks = tuple(forward_fn(*input_tensors_chunk) for input_tensors_chunk in zip(*input_tensors_chunks)) # concatenate output at same dimension return torch.cat(output_chunks, dim=chunk_dim) return forward_fn(*input_tensors) def meshgrid(*tensors: torch.Tensor | list[torch.Tensor], indexing: str | None = None) -> tuple[torch.Tensor, ...]: """ Wrapper around torch.meshgrid to avoid warning messages about the introduced `indexing` argument. Reference: https://pytorch.org/docs/1.13/generated/torch.meshgrid.html """ return torch.meshgrid(*tensors, indexing=indexing) def id_tensor_storage(tensor: torch.Tensor) -> tuple[torch.device, int, int]: """ Unique identifier to a tensor storage. Multiple different tensors can share the same underlying storage. For example, "meta" tensors all share the same storage, and thus their identifier will all be equal. This identifier is guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with non-overlapping lifetimes may have the same id. """ if _torch_distributed_available and is_torch_greater_or_equal("2.5"): from torch.distributed.tensor import DTensor if isinstance(tensor, DTensor): local_tensor = tensor.to_local() return tensor.device, local_tensor.storage().data_ptr(), tensor.nbytes if tensor.device.type == "xla" and is_torch_xla_available(): # NOTE: xla tensors dont have storage # use some other unique id to distinguish. # this is a XLA tensor, it must be created using torch_xla's # device. So the following import is safe: import torch_xla unique_id = torch_xla._XLAC._xla_get_tensor_id(tensor) else: unique_id = storage_ptr(tensor) return tensor.device, unique_id, storage_size(tensor) def isin_mps_friendly(elements: torch.Tensor, test_elements: torch.Tensor | int) -> torch.Tensor: """ Same as `torch.isin` without flags, but MPS-friendly. We can remove this function when we stop supporting torch <= 2.3. See https://github.com/pytorch/pytorch/issues/77764#issuecomment-2067838075 Args: elements (`torch.Tensor`): Input elements test_elements (`torch.Tensor` or `int`): The elements to check against. Returns: `torch.Tensor`: A boolean tensor of the same shape as `elements` that is True for `elements` in `test_elements` and False otherwise """ if elements.device.type == "mps" and not is_torch_greater_or_equal_than_2_4: test_elements = torch.tensor(test_elements) if test_elements.ndim == 0: test_elements = test_elements.unsqueeze(0) return elements.tile(test_elements.shape[0], 1).eq(test_elements.unsqueeze(1)).sum(dim=0).bool().squeeze() else: # Note: don't use named arguments in `torch.isin`, see https://github.com/pytorch/pytorch/issues/126045 return torch.isin(elements, test_elements) @wraps(lru_cache) def compile_compatible_method_lru_cache(*lru_args, **lru_kwargs): """ LRU cache decorator from standard functools library, but with a workaround to disable caching when torchdynamo is compiling. Expected to work with class methods. """ def decorator(func): func_with_cache = lru_cache(*lru_args, **lru_kwargs)(func) @wraps(func) def wrapper(*args, **kwargs): if is_torchdynamo_compiling(): return func(*args, **kwargs) else: return func_with_cache(*args, **kwargs) return wrapper return decorator
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/modeling_rope_utils.py
src/transformers/modeling_rope_utils.py
# Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math import warnings from functools import wraps from typing import TYPE_CHECKING, Optional, TypedDict from .utils import is_torch_available, logging logger = logging.get_logger(__name__) if is_torch_available(): import torch if TYPE_CHECKING: from .configuration_utils import PreTrainedConfig def dynamic_rope_update(rope_forward): """ Decorator function to update the RoPE parameters in the forward pass, if the model is using a dynamic RoPE (i.e. a RoPE implementation that may recompute its frequencies in the forward pass). Args: rope_forward (Callable): The forward pass of the RoPE implementation. Returns: The decorated forward pass. """ def longrope_frequency_update(self, position_ids, device, layer_type=None): """Longrope uses long factor if sequence is larger than original pretraining length, short otherwise.""" seq_len = torch.max(position_ids) + 1 if layer_type is None: rope_type = self.rope_type original_inv_freq = self.original_inv_freq prefix = "" original_max_position_embeddings = self.config.rope_parameters["original_max_position_embeddings"] else: rope_type = self.rope_type[layer_type] original_inv_freq = getattr(self, f"{layer_type}_original_inv_freq") prefix = f"{layer_type}_" original_max_position_embeddings = self.config.rope_parameters[layer_type][ "original_max_position_embeddings" ] if seq_len > original_max_position_embeddings: if not hasattr(self, f"{layer_type}_long_inv_freq"): rope_init_fn = ROPE_INIT_FUNCTIONS[rope_type] long_inv_freq, _ = rope_init_fn( self.config, device, seq_len=original_max_position_embeddings + 1, layer_type=layer_type, ) self.register_buffer(f"{prefix}inv_freq", long_inv_freq, persistent=False) setattr(self, f"{prefix}long_inv_freq", long_inv_freq) else: # This .to() is needed if the model has been moved to a device after being initialized (because # the buffer is automatically moved, but not the original copy) original_inv_freq = original_inv_freq.to(device) self.register_buffer(f"{prefix}inv_freq", original_inv_freq, persistent=False) setattr(self, f"{prefix}original_inv_freq", original_inv_freq) def dynamic_frequency_update(self, position_ids, device, layer_type=None): """ dynamic RoPE layers should recompute `inv_freq` in the following situations: 1 - growing beyond the cached sequence length (allow scaling) 2 - the current sequence length is in the original scale (avoid losing precision with small sequences) """ seq_len = torch.max(position_ids) + 1 if layer_type is None: rope_type = self.rope_type max_seq_len_cached = self.max_seq_len_cached original_inv_freq = self.original_inv_freq prefix = "" else: rope_type = self.rope_type[layer_type] max_seq_len_cached = getattr(self, f"{layer_type}_max_seq_len_cached", self.max_seq_len_cached) original_inv_freq = getattr(self, f"{layer_type}_original_inv_freq") prefix = f"{layer_type}_" if seq_len > max_seq_len_cached: # growth rope_init_fn = ROPE_INIT_FUNCTIONS[rope_type] inv_freq, self.attention_scaling = rope_init_fn( self.config, device, seq_len=seq_len, layer_type=layer_type, ) # TODO joao: may break with compilation self.register_buffer(f"{prefix}inv_freq", inv_freq, persistent=False) setattr(self, f"{layer_type}_max_seq_len_cached", seq_len) if seq_len < self.original_max_seq_len and max_seq_len_cached > self.original_max_seq_len: # reset # This .to() is needed if the model has been moved to a device after being initialized (because # the buffer is automatically moved, but not the original copy) original_inv_freq = original_inv_freq.to(device) self.register_buffer(f"{prefix}inv_freq", original_inv_freq, persistent=False) setattr(self, f"{prefix}original_inv_freq", original_inv_freq) setattr(self, f"{layer_type}_max_seq_len_cached", self.original_max_seq_len) @wraps(rope_forward) def wrapper(self, x, position_ids, layer_type=None): rope_type = self.rope_type if layer_type is None else self.rope_type[layer_type] kwargs = {"layer_type": layer_type} if layer_type is not None else {} if "dynamic" in rope_type: dynamic_frequency_update(self, position_ids, device=x.device, **kwargs) elif rope_type == "longrope": longrope_frequency_update(self, position_ids, device=x.device, **kwargs) return rope_forward(self, x, position_ids, **kwargs) return wrapper def _compute_linear_scaling_rope_parameters( config: Optional["PreTrainedConfig"] = None, device: Optional["torch.device"] = None, seq_len: Optional[int] = None, layer_type: Optional[str] = None, ) -> tuple["torch.Tensor", float]: """ Computes the inverse frequencies with linear scaling. Credits to the Reddit user /u/kaiokendev Args: config ([`~transformers."PreTrainedConfig"`]): The model configuration. This function assumes that the config will provide at least the following properties: * rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived. * hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly. * num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly. Additionally, this function will make use of the following properties if they are found in the config: * head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be derived as hidden_size // num_attention_heads. * partial_rotary_factor (`float`, *optional*): If less than 1.0, inverse frequencies will be returned for the first fraction of the head_dim. Defaults to 1.0. device (`torch.device`): The device to use for initialization of the inverse frequencies. seq_len (`int`, *optional*): The current sequence length. Unused for this type of RoPE. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ # For backward compatibility standardize the `rope_parameters_dict` if it uses old format config.standardize_rope_params() rope_parameters_dict = config.rope_parameters[layer_type] if layer_type is not None else config.rope_parameters factor = rope_parameters_dict["factor"] # Gets the default RoPE parameters base = rope_parameters_dict["rope_theta"] partial_rotary_factor = rope_parameters_dict.get("partial_rotary_factor", 1.0) head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads dim = int(head_dim * partial_rotary_factor) attention_factor = 1.0 # Unused in this type of RoPE # Compute the inverse frequencies inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)) # Then applies linear scaling to the frequencies. # NOTE: originally, scaling was applied to the position_ids. However, we get `embs = inv_freq @ position_ids`, so # applying scaling to the inverse frequencies is equivalent. inv_freq /= factor return inv_freq, attention_factor def _compute_dynamic_ntk_parameters( config: Optional["PreTrainedConfig"] = None, device: Optional["torch.device"] = None, seq_len: Optional[int] = None, layer_type: Optional[str] = None, ) -> tuple["torch.Tensor", float]: """ Computes the inverse frequencies with NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla Args: config ([`~transformers."PreTrainedConfig"`]): The model configuration. This function assumes that the config will provide at least the following properties: * rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived. * hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly. * num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly. * max_position_embeddings (`int`): The default sequence length used to update the dynamic RoPE at inference time * rope_parameters (`dict[str, float]`): The standard RoPE scaling parameters, from which `factor` will be accessed. The value of `factor` is used to determine the new base frequency, along with the current sequence length (seq_len), the maximum positional embeddings (max_position_embeddings), and the computed dimensionality (dim) of the rotary embeddings. If seq_len <= max_position_embeddings, this factor has no effect. If seq_len <= max_position_embeddings, this factor effectively stretches the context window using an exponent derived from `dim`. Additionally, this function will make use of the following properties if they are found in the config: * head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be derived as hidden_size // num_attention_heads. * partial_rotary_factor (`float`, *optional*): If less than 1.0, inverse frequencies will be returned for the first fraction of the head_dim. Defaults to 1.0. device (`torch.device`): The device to use for initialization of the inverse frequencies. seq_len (`int`, *optional*): The current sequence length, used to update the dynamic RoPE at inference time. If `None` or shorter than max_position_embeddings, this value will be overridden by max_position_embeddings. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ # For backward compatibility standardize the `rope_parameters_dict` if it uses old format config.standardize_rope_params() rope_parameters_dict = config.rope_parameters[layer_type] if layer_type is not None else config.rope_parameters base = rope_parameters_dict["rope_theta"] partial_rotary_factor = rope_parameters_dict.get("partial_rotary_factor", 1.0) head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) dim = int(head_dim * partial_rotary_factor) factor = rope_parameters_dict["factor"] attention_factor = 1.0 # Unused in this type of RoPE # seq_len: default to max_position_embeddings, e.g. at init time if seq_len is None: seq_len = config.max_position_embeddings elif isinstance(seq_len, torch.Tensor): seq_len = torch.maximum( seq_len, torch.tensor(config.max_position_embeddings, dtype=seq_len.dtype, device=seq_len.device), ) else: seq_len = max(seq_len, config.max_position_embeddings) # Compute the inverse frequencies base = base * ((factor * seq_len / config.max_position_embeddings) - (factor - 1)) ** (dim / (dim - 2)) inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)) return inv_freq, attention_factor def _compute_yarn_parameters( config: "PreTrainedConfig", device: Optional["torch.device"] = None, seq_len: Optional[int] = None, layer_type: Optional[str] = None, ) -> tuple["torch.Tensor", float]: """ Computes the inverse frequencies with NTK scaling. Please refer to the [original paper](https://huggingface.co/papers/2309.00071) Args: config ([`~transformers."PreTrainedConfig"`]): The model configuration. This function assumes that the config will provide at least the following properties: * rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived. * hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly. * num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly. * max_position_embeddings (`int`): The maximum length of the positional embeddings. * rope_parameters (`dict[str, float | int]`): The standard RoPE scaling parameters, from which the following keys will be accessed: * `attention_factor` (`float`, *optional*): The scaling factor to be applied to the computed cos/sin. If None, the value is inferred from `factor`, `mscale`, and `mscale_all_dim` as avaialble. * `beta_fast` (`float`, *optional*, defaults to 32): Parameter to set the boundary for extrapolation (only) in the linear ramp function. * `beta_slow` (`float`, *optional*, defaults to 1): Parameter to set the boundary for interpolation (only) in the linear ramp function. * `factor` (`float`, *optional*): The scaling factor applied when interpolating the position IDs to extend the possible context length. Additionally, if `attention_factor` is None, the log of this value is used to compute a value for `attention_factor`, possibly in conjunciton with `mscale` and `mscale_all_dim`, if provided. * `mscale` (`float`, *optional*): If `attention_factor` is None and both `mscale` and `mscale_all_dim` are provided, `mscale` acts scalar augmenting `log(factor)` when computing the numerator for the inferred value of `attention_factor`. If not provided, `attention_factor` will be calculated based on `factor` only. * `mscale_all_dim` (`float`, *optional*): If `attention_factor` is None and both `mscale` and `mscale_all_dim` are provided, `mscale_all_dim` acts scalar augmenting `log(factor)` when computing the denominator for the inferred value of `attention_factor`. If not provided, `attention_factor` will be calculated based on `factor` only. * `original_max_position_embeddings` (`int`): The original max position embeddings used during pretraining. * `truncate` (`bool`, *optional*): Whether to truncate the correction range. Additionally, this function will make use of the following properties if they are found in the config: * head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be derived as hidden_size // num_attention_heads. * partial_rotary_factor (`float`, *optional*, defaults to 1.0): If less than 1.0, inverse frequencies will be returned for the first fraction of the head_dim. device (`torch.device`): The device to use for initialization of the inverse frequencies. seq_len (`int`, *optional*): The current sequence length. Unused for this type of RoPE. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin. """ # For backward compatibility standardize the `rope_parameters_dict` if it uses old format config.standardize_rope_params() rope_parameters_dict = config.rope_parameters[layer_type] if layer_type is not None else config.rope_parameters base = rope_parameters_dict["rope_theta"] partial_rotary_factor = rope_parameters_dict.get("partial_rotary_factor", 1.0) head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) dim = int(head_dim * partial_rotary_factor) factor = rope_parameters_dict["factor"] attention_factor = rope_parameters_dict.get("attention_factor") mscale = rope_parameters_dict.get("mscale") mscale_all_dim = rope_parameters_dict.get("mscale_all_dim") original_max_position_embeddings = rope_parameters_dict["original_max_position_embeddings"] # NOTE: DeekSeek-V3 (and potentially other models) have `original_max_position_embeddings` field # containing the pretrained value. They use the ratio between `max_position_embeddings` and this value # to compute the default attention scaling factor, instead of using `factor`. if factor is None: factor = config.max_position_embeddings / original_max_position_embeddings def get_mscale(scale, mscale=1): if scale <= 1: return 1.0 return 0.1 * mscale * math.log(scale) + 1.0 # Sets the attention factor as suggested in the paper if attention_factor is None: if mscale and mscale_all_dim: attention_factor = float(get_mscale(factor, mscale) / get_mscale(factor, mscale_all_dim)) else: attention_factor = get_mscale(factor) # Optional config options # beta_fast/beta_slow: as suggested in the paper, default to 32/1 (correspondingly) beta_fast = rope_parameters_dict.get("beta_fast") or 32 beta_slow = rope_parameters_dict.get("beta_slow") or 1 # Compute the inverse frequencies def find_correction_dim(num_rotations, dim, base, max_position_embeddings): """Inverse dimension formula to find the dimension based on the number of rotations""" return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (2 * math.log(base)) def find_correction_range(low_rot, high_rot, dim, base, max_position_embeddings, truncate): """Find dimension range bounds based on rotations""" low = find_correction_dim(low_rot, dim, base, max_position_embeddings) high = find_correction_dim(high_rot, dim, base, max_position_embeddings) if truncate: low = math.floor(low) high = math.ceil(high) return max(low, 0), min(high, dim - 1) def linear_ramp_factor(min, max, dim): if min == max: max += 0.001 # Prevent singularity linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min) ramp_func = torch.clamp(linear_func, 0, 1) return ramp_func # Note on variable naming: "interpolation" comes from the original technique, where we interpolate the position IDs # to expand the possible context length. In other words, interpolation = apply scaling factor. pos_freqs = base ** (torch.arange(0, dim, 2).to(device=device, dtype=torch.float) / dim) inv_freq_extrapolation = 1.0 / pos_freqs inv_freq_interpolation = 1.0 / (factor * pos_freqs) truncate = config.rope_parameters.get("truncate", True) low, high = find_correction_range(beta_fast, beta_slow, dim, base, original_max_position_embeddings, truncate) # Get n-dimensional rotational scaling corrected for extrapolation inv_freq_extrapolation_factor = 1 - linear_ramp_factor(low, high, dim // 2).to(device=device, dtype=torch.float) inv_freq = ( inv_freq_interpolation * (1 - inv_freq_extrapolation_factor) + inv_freq_extrapolation * inv_freq_extrapolation_factor ) return inv_freq, attention_factor def _compute_longrope_parameters( config: "PreTrainedConfig", device: Optional["torch.device"] = None, seq_len: Optional[int] = None, layer_type: Optional[str] = None, ) -> tuple["torch.Tensor", float]: """ Computes the inverse frequencies with LongRoPE scaling. Please refer to the [original implementation](https://github.com/microsoft/LongRoPE) Args: config ([`~transformers."PreTrainedConfig"`]): The model configuration. This function assumes that the config will provide at least the following properties: * rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived. * hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly. * num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly. * max_position_embeddings (`int`): The maximum length of the positional embeddings. * original_max_position_embeddings (`int`, *optional*): The original max position embeddings used during pretraining. If not provided, defaults to `max_position_embeddings`. * rope_parameters (`dict[str, float]`): The standard RoPE scaling parameters, from which the following keys will be accessed: * `attention_factor` (`float`, *optional*): The scaling factor to be applied on the attention computation. If unspecified, it defaults to value recommended by the implementation, inferred from the value of `factor`. * `factor` (`float`, *optional*): The scaling factor to apply to the RoPE embeddings. If both `max_position_embeddings` and `original_max_position_embeddings` are provided, this value will be overridden s the ratio between those values. * `long_factor` (`float`, *optional*): The scale factor applied when computing the inverse frequencies if `seq_len` is provided and greater than `original_max_position_embeddings`. * `short_factor` (`float`, *optional*): The scale factor applied when computing the inverse frequencies if `seq_len` is None or less-than-or-equal-to `original_max_position_embeddings`. Additionally, this function will make use of the following properties if they are found in the config: * head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be derived as hidden_size // num_attention_heads. * partial_rotary_factor (`float`, *optional*, defaults to 1.0): If less than 1.0, inverse frequencies will be returned for the first fraction of the head_dim. device (`torch.device`): The device to use for initialization of the inverse frequencies. seq_len (`int`, *optional*): The current sequence length. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin. """ # For backward compatibility standardize the `rope_parameters_dict` if it uses old format config.standardize_rope_params() rope_parameters_dict = config.rope_parameters[layer_type] if layer_type is not None else config.rope_parameters base = rope_parameters_dict["rope_theta"] partial_rotary_factor = rope_parameters_dict.get("partial_rotary_factor", 1.0) head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) dim = int(head_dim * partial_rotary_factor) long_factor = rope_parameters_dict["long_factor"] short_factor = rope_parameters_dict["short_factor"] factor = rope_parameters_dict.get("factor") attention_factor = rope_parameters_dict.get("attention_factor") original_max_position_embeddings = rope_parameters_dict["original_max_position_embeddings"] # NOTE: Phi3 (and potentially other models) modify `max_position_embeddings` and have a # `original_max_position_embeddings` field containing the pretrained value. They use the ratio between these two # values to compute the default attention scaling factor, instead of using `factor`. if factor is None: factor = config.max_position_embeddings / original_max_position_embeddings # Sets the attention factor as suggested in the paper if attention_factor is None: if factor <= 1.0: attention_factor = 1.0 else: attention_factor = math.sqrt(1 + math.log(factor) / math.log(original_max_position_embeddings)) # Compute the inverse frequencies -- scaled based on the target sequence length if seq_len and seq_len > original_max_position_embeddings: ext_factors = torch.tensor(long_factor, dtype=torch.float32, device=device) else: ext_factors = torch.tensor(short_factor, dtype=torch.float32, device=device) inv_freq_shape = torch.arange(0, dim, 2, dtype=torch.int64, device=device).float() / dim inv_freq = 1.0 / (ext_factors * base**inv_freq_shape) return inv_freq, attention_factor def _compute_llama3_parameters( config: "PreTrainedConfig", device: Optional["torch.device"] = None, seq_len: Optional[int] = None, layer_type: Optional[str] = None, ) -> tuple["torch.Tensor", float]: """ Computes the inverse frequencies for llama 3.1. Args: config ([`~transformers."PreTrainedConfig"`]): The model configuration. This function assumes that the config will provide at least the following properties: * rope_theta (`float`): The base wavelength from which the inverse frequencies will be derived. * hidden_size (`int`): The numerator when deriving a head_dim, if not provided directly. * num_attention_heads (`int`): The denominator when deriving a head_dim, if not provided directly. * rope_parameters (`dict[str, float | int]`): The standard RoPE scaling parameters, from which the following keys will be accessed: * `factor` (`float`, *optional*): The scaling factor applied to the inverse frequencies when 1) the wavelength is greater than `low_freq_wavelen` prior to smoothing, and 2) to all inverse frequencies during smoothing. * `high_freq_factor` (`float`): The scale factor used to compute `high_freq_wavelen` and the value for the denominator of the smoothing factor prior to the `low_freq_factor` shift. * `low_freq_factor` (`float`): The scale factor used to compute `low_freq_wavelen` and the shift applied to the numerator and denominator of the smoothing factor. frequencies if `seq_len` is None or less-than-or-equal-to `original_max_position_embeddings`. * `original_max_position_embeddings` (`int`): The original max position embeddings used during pretraining. If not provided, the function falls back to `max_position_embeddings`. Additionally, this function will make use of the following properties if they are found in the config: * head_dim (`int`, *optional*): The size of the key-value heads in the model. If None, this value will be derived as hidden_size // num_attention_heads. * partial_rotary_factor (`float`, *optional*): If less than 1.0, inverse frequencies will be returned for the first fraction of the head_dim. Defaults to 1.0. device (`torch.device`): The device to use for initialization of the inverse frequencies. seq_len (`int`, *optional*): The current sequence length. Unused for this type of RoPE. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin. """ # For backward compatibility standardize the `rope_parameters_dict` if it uses old format config.standardize_rope_params() rope_parameters_dict = config.rope_parameters[layer_type] if layer_type is not None else config.rope_parameters # Gets the default RoPE parameters base = rope_parameters_dict["rope_theta"] partial_rotary_factor = rope_parameters_dict.get("partial_rotary_factor", 1.0) head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads dim = int(head_dim * partial_rotary_factor) attention_factor = 1.0 # Unused in this type of RoPE # Compute the inverse frequencies inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)) factor = rope_parameters_dict["factor"] # `8` in the original implementation low_freq_factor = rope_parameters_dict["low_freq_factor"] # `1` in the original implementation high_freq_factor = rope_parameters_dict["high_freq_factor"] # `4` in the original implementation old_context_len = rope_parameters_dict["original_max_position_embeddings"] # `8192` in the original implementation low_freq_wavelen = old_context_len / low_freq_factor high_freq_wavelen = old_context_len / high_freq_factor wavelen = 2 * math.pi / inv_freq # wavelen < high_freq_wavelen: do nothing # wavelen > low_freq_wavelen: divide by factor inv_freq_llama = torch.where(wavelen > low_freq_wavelen, inv_freq / factor, inv_freq) # otherwise: interpolate between the two, using a smooth factor smooth_factor = (old_context_len / wavelen - low_freq_factor) / (high_freq_factor - low_freq_factor) smoothed_inv_freq = (1 - smooth_factor) * inv_freq_llama / factor + smooth_factor * inv_freq_llama is_medium_freq = ~(wavelen < high_freq_wavelen) * ~(wavelen > low_freq_wavelen) inv_freq_llama = torch.where(is_medium_freq, smoothed_inv_freq, inv_freq_llama) return inv_freq_llama, attention_factor # This maps the "rope_type" string field in rope config to the corresponding function to compute the RoPE parameters # from the model config. You can append new {'rope_type': callable} pairs to this rope_parameters to enable custom RoPE # parameterizations, as long as the callable has the same signature. ROPE_INIT_FUNCTIONS = { "linear": _compute_linear_scaling_rope_parameters, "dynamic": _compute_dynamic_ntk_parameters, "yarn": _compute_yarn_parameters, "longrope": _compute_longrope_parameters, "llama3": _compute_llama3_parameters, } class RopeParameters(TypedDict, total=False): """ Args: rope_theta (`float`): The base period of the RoPE embeddings. rope_type (`str`, *optional*, defaults to "default"): The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. partial_rotary_factor (`float`, *optional*): The percentage of the query and key head embedding on which RoPE will be applied. factor (`float`, *optional*): Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length. original_max_position_embeddings (`int`, *optional*): Used with 'yarn', 'longrope' and 'llama3'. The original max position embeddings used during pretraining. attention_factor (`float`, *optional*):
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/tokenization_utils_sentencepiece.py
src/transformers/tokenization_utils_sentencepiece.py
# Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ SentencePiece-based tokenization class for loading from sentencepiece.model files. """ import os from shutil import copyfile from typing import Optional, Union try: import sentencepiece as spm except ImportError: spm = None from .convert_slow_tokenizer import import_protobuf from .tokenization_python import PreTrainedTokenizer from .tokenization_utils_base import ( INIT_TOKENIZER_DOCSTRING, AddedToken, generate_merges, ) from .utils import add_end_docstrings, logging, requires_backends logger = logging.get_logger(__name__) VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"} SPIECE_UNDERLINE = "▁" @add_end_docstrings(INIT_TOKENIZER_DOCSTRING) class SentencePieceBackend(PreTrainedTokenizer): """ Base class for SentencePiece-based tokenizers that load from sentencepiece.model files. Inherits from [`~tokenization_utils.PreTrainedTokenizer`]. Handle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading pretrained tokenizers as well as adding tokens to the vocabulary. This class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...). """ vocab_files_names = VOCAB_FILES_NAMES def __init__(self, **kwargs): # Ensure optional dependency is available before loading requires_backends(self, "sentencepiece") # Extract sentencepiece-specific parameters self.vocab_file = kwargs.get("vocab_file") self.legacy = kwargs.get("legacy", True) self.sp_model_kwargs = kwargs.pop("sp_model_kwargs", {}) # Set backend to "sentencepiece" if not already set if "backend" not in kwargs: kwargs["backend"] = "sentencepiece" # Load the SentencePiece model before calling parent __init__ # This is needed because parent __init__ may call methods that depend on sp_model tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs) tokenizer.Load(self.vocab_file) if not self.legacy: model_pb2 = import_protobuf() proto = model_pb2.ModelProto.FromString(tokenizer.serialized_model_proto()) if proto.normalizer_spec.add_dummy_prefix: proto.normalizer_spec.add_dummy_prefix = False tokenizer.LoadFromSerializedProto(proto.SerializeToString()) self.sp_model = tokenizer # Initialize total_vocab_size before parent __init__ (which may call _add_tokens -> len(self)) self.total_vocab_size = self.sp_model.get_piece_size() # Add sp_model_kwargs back to kwargs so it gets stored in init_kwargs kwargs["sp_model_kwargs"] = self.sp_model_kwargs # Call parent class __init__ (PreTrainedTokenizer) # This handles tokens_trie, _added_tokens_decoder, _added_tokens_encoder, # token_type_ids_pattern, special_tokens_pattern, and adds special tokens super().__init__(**kwargs) self._update_trie() @property def vocab_size(self) -> int: """Returns vocab size""" return self.sp_model.get_piece_size() def get_vocab(self): """Returns vocab as a dict""" vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def _add_tokens(self, new_tokens: Union[list[str], list[AddedToken]], special_tokens: bool = False) -> int: """ Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to it with indices starting from length of the current vocabulary. Special tokens are sometimes already in the vocab which is why they have to be handled specifically. Args: new_tokens (`list[str]`or `list[tokenizers.AddedToken]`): Token(s) to add in vocabulary. A token is counted as added if it's not already in the vocabulary (tested by checking if the tokenizer assign the index of the `unk_token` to them). If a token is part of the vocabulary then we simply mark this token as an `AddedToken` which allows to control the stripping and normalization of this token. This is NOT possible in `tokenizers`. special_tokens (`bool`, *optional*, defaults to `False`): Whether or not the tokens should be added as special tokens. Returns: `int`: The number of tokens actually added to the vocabulary. Examples: ```python # Let's see how to increase the vocabulary of Bert model and tokenizer tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") model = BertModel.from_pretrained("google-bert/bert-base-uncased") num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"]) print("We have added", num_added_toks, "tokens") # Note: resize_token_embeddings expects to receive the full size of the new vocabulary, i.e. the length of the tokenizer. model.resize_token_embeddings(len(tokenizer)) ```""" if not new_tokens: return 0 next_index = len(self) # total size (base + added) num_added = 0 for token in new_tokens: if not isinstance(token, (str, AddedToken)): raise TypeError(f"Token {token} is not a string but a {type(token)}.") if str(token) == "": continue if isinstance(token, str): if token in self._added_tokens_encoder: continue is_special = token in self.all_special_tokens or special_tokens token = AddedToken(token, rstrip=False, lstrip=False, normalized=not is_special, special=is_special) elif special_tokens: # doing token.special=True changes the normalization! will fix in rust # this is important and the only reason why the AddedTokens in each class are normalized by default token.__setstate__({"special": True, "normalized": token.normalized}) if token in self._added_tokens_decoder.values(): continue if not token.special and token.normalized and getattr(self, "do_lower_case", False): token.content = token.content.lower() # Check if token already exists in the SentencePiece base vocab tok_id = self.sp_model.piece_to_id(token.content) in_base_vocab = ( tok_id < self.sp_model.get_piece_size() and self.sp_model.IdToPiece(tok_id) == token.content ) if in_base_vocab: token_index = tok_id else: token_index = next_index next_index += 1 num_added += 1 if token.special and str(token) not in self.all_special_tokens: self._extra_special_tokens.append(token) # the setter automatically updates the reverse map self._added_tokens_decoder[token_index] = token self._added_tokens_encoder[token.content] = token_index if self.verbose: logger.info(f"Adding {token} to the vocabulary") self._update_trie() self._update_total_vocab_size() return num_added def _update_trie(self, unique_no_split_tokens: Optional[list[str]] = None): # Add all added tokens for token in self._added_tokens_decoder.values(): if token.content not in self.tokens_trie._tokens: self.tokens_trie.add(token.content) # Also add all special tokens (even if they're in base vocab) so they get split during tokenization for token in self.all_special_tokens: if token not in self.tokens_trie._tokens: self.tokens_trie.add(token) # Add any additional no-split tokens for token in unique_no_split_tokens or []: if token not in self.tokens_trie._tokens: self.tokens_trie.add(token) def _tokenize(self, text, **kwargs): """ Returns a tokenized string. We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give `['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the `unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`. `self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`. """ if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")): return self.sp_model.encode(text, out_type=str) # 1. Encode string + prefix ex: "<unk> Hey" tokens = self.sp_model.encode(self.unk_token + text, out_type=str) # 2. Remove self.unk_token from ['<','unk','>', '▁Hey'] unk_token_length = len(self.sp_model.encode(str(self.unk_token))) return tokens[unk_token_length:] if len(tokens) >= unk_token_length else tokens def _convert_token_to_id(self, token): """Converts a token (str) to an id using the vocab.""" return self.sp_model.piece_to_id(token) def _convert_id_to_token(self, index): """Converts an index (integer) in a token (str) using the vocab.""" token = self.sp_model.IdToPiece(index) return token def convert_tokens_to_string(self, tokens: list[str]) -> str: """Converts a sequence of tokens (string) in a single string.""" out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip() return out_string def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]: """ Save the sentencepiece vocabulary (copy original file) to a directory. Args: save_directory (`str`): The directory in which to save the vocabulary. filename_prefix (`str`, *optional*): An optional prefix to add to the named of the saved files. Returns: `tuple(str)`: Paths to the files saved. """ if not os.path.isdir(save_directory): logger.error(f"Vocabulary path ({save_directory}) should be a directory") return out_vocab_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file, out_vocab_file) elif not os.path.isfile(self.vocab_file): with open(out_vocab_file, "wb") as fi: content_spiece_model = self.sp_model.serialized_model_proto() fi.write(content_spiece_model) return (out_vocab_file,) def _decode( self, token_ids: Union[int, list[int]], skip_special_tokens: bool = False, clean_up_tokenization_spaces: Optional[bool] = None, spaces_between_special_tokens: bool = False, **kwargs, ) -> str: """ Decode token ids to string. Uses the generic decode path from PreTrainedTokenizer which works for all vocabularies, including custom vocabularies that override _convert_id_to_token. """ # Use parent class's generic decode method - it's simpler and works for all cases return super()._decode( token_ids=token_ids, skip_special_tokens=skip_special_tokens, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs, ) class SentencePieceExtractor: """ Extractor implementation for SentencePiece trained models. https://github.com/google/sentencepiece """ def __init__(self, model: str): requires_backends(self, "sentencepiece") from sentencepiece import SentencePieceProcessor self.sp = SentencePieceProcessor() self.sp.Load(model) def extract(self, vocab_scores=None) -> tuple[dict[str, int], list[tuple[str, float]], list[tuple]]: """ By default will return vocab and merges with respect to their order, by sending `vocab_scores` we're going to order the merges with respect to the piece scores instead. """ sp = self.sp vocab_ids = {sp.id_to_piece(index): index for index in range(sp.GetPieceSize())} vocab_scores_dict = {sp.id_to_piece(i): sp.get_score(i) for i in range(sp.GetPieceSize())} merges = generate_merges(vocab_ids, vocab_scores_dict) vocab_scores_list = [(sp.id_to_piece(i), sp.get_score(i)) for i in range(sp.GetPieceSize())] return vocab_ids, vocab_scores_list, merges
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/image_transforms.py
src/transformers/image_transforms.py
# Copyright 2022 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections import defaultdict from collections.abc import Collection, Iterable from math import ceil from typing import Optional, Union import numpy as np from .image_utils import ( ChannelDimension, ImageInput, get_channel_dimension_axis, get_image_size, infer_channel_dimension_format, ) from .utils import ExplicitEnum, TensorType, is_torch_tensor from .utils.import_utils import ( is_torch_available, is_vision_available, requires_backends, ) if is_vision_available(): import PIL from .image_utils import PILImageResampling if is_torch_available(): import torch def to_channel_dimension_format( image: np.ndarray, channel_dim: Union[ChannelDimension, str], input_channel_dim: Optional[Union[ChannelDimension, str]] = None, ) -> np.ndarray: """ Converts `image` to the channel dimension format specified by `channel_dim`. The input can have arbitrary number of leading dimensions. Only last three dimension will be permuted to format the `image`. Args: image (`numpy.ndarray`): The image to have its channel dimension set. channel_dim (`ChannelDimension`): The channel dimension format to use. input_channel_dim (`ChannelDimension`, *optional*): The channel dimension format of the input image. If not provided, it will be inferred from the input image. Returns: `np.ndarray`: The image with the channel dimension set to `channel_dim`. """ if not isinstance(image, np.ndarray): raise TypeError(f"Input image must be of type np.ndarray, got {type(image)}") if input_channel_dim is None: input_channel_dim = infer_channel_dimension_format(image) target_channel_dim = ChannelDimension(channel_dim) if input_channel_dim == target_channel_dim: return image if target_channel_dim == ChannelDimension.FIRST: axes = list(range(image.ndim - 3)) + [image.ndim - 1, image.ndim - 3, image.ndim - 2] image = image.transpose(axes) elif target_channel_dim == ChannelDimension.LAST: axes = list(range(image.ndim - 3)) + [image.ndim - 2, image.ndim - 1, image.ndim - 3] image = image.transpose(axes) else: raise ValueError(f"Unsupported channel dimension format: {channel_dim}") return image def rescale( image: np.ndarray, scale: float, data_format: Optional[ChannelDimension] = None, dtype: np.dtype = np.float32, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """ Rescales `image` by `scale`. Args: image (`np.ndarray`): The image to rescale. scale (`float`): The scale to use for rescaling the image. data_format (`ChannelDimension`, *optional*): The channel dimension format of the image. If not provided, it will be the same as the input image. dtype (`np.dtype`, *optional*, defaults to `np.float32`): The dtype of the output image. Defaults to `np.float32`. Used for backwards compatibility with feature extractors. input_data_format (`ChannelDimension`, *optional*): The channel dimension format of the input image. If not provided, it will be inferred from the input image. Returns: `np.ndarray`: The rescaled image. """ if not isinstance(image, np.ndarray): raise TypeError(f"Input image must be of type np.ndarray, got {type(image)}") rescaled_image = image.astype(np.float64) * scale # Numpy type promotion has changed, so always upcast first if data_format is not None: rescaled_image = to_channel_dimension_format(rescaled_image, data_format, input_data_format) rescaled_image = rescaled_image.astype(dtype) # Finally downcast to the desired dtype at the end return rescaled_image def _rescale_for_pil_conversion(image): """ Detects whether or not the image needs to be rescaled before being converted to a PIL image. The assumption is that if the image is of type `np.float` and all values are between 0 and 1, it needs to be rescaled. """ if image.dtype == np.uint8: do_rescale = False elif np.allclose(image, image.astype(int)): if np.all(0 <= image) and np.all(image <= 255): do_rescale = False else: raise ValueError( "The image to be converted to a PIL image contains values outside the range [0, 255], " f"got [{image.min()}, {image.max()}] which cannot be converted to uint8." ) elif np.all(0 <= image) and np.all(image <= 1): do_rescale = True else: raise ValueError( "The image to be converted to a PIL image contains values outside the range [0, 1], " f"got [{image.min()}, {image.max()}] which cannot be converted to uint8." ) return do_rescale def to_pil_image( image: Union[np.ndarray, "PIL.Image.Image", "torch.Tensor"], do_rescale: Optional[bool] = None, image_mode: Optional[str] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> "PIL.Image.Image": """ Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if needed. Args: image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`): The image to convert to the `PIL.Image` format. do_rescale (`bool`, *optional*): Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will default to `True` if the image type is a floating type and casting to `int` would result in a loss of precision, and `False` otherwise. image_mode (`str`, *optional*): The mode to use for the PIL image. If unset, will use the default mode for the input image type. input_data_format (`ChannelDimension`, *optional*): The channel dimension format of the input image. If unset, will use the inferred format from the input. Returns: `PIL.Image.Image`: The converted image. """ requires_backends(to_pil_image, ["vision"]) if isinstance(image, PIL.Image.Image): return image # Convert all tensors to numpy arrays before converting to PIL image if is_torch_tensor(image): image = image.numpy() elif not isinstance(image, np.ndarray): raise ValueError(f"Input image type not supported: {type(image)}") # If the channel has been moved to first dim, we put it back at the end. image = to_channel_dimension_format(image, ChannelDimension.LAST, input_data_format) # If there is a single channel, we squeeze it, as otherwise PIL can't handle it. image = np.squeeze(image, axis=-1) if image.shape[-1] == 1 else image # PIL.Image can only store uint8 values so we rescale the image to be between 0 and 255 if needed. do_rescale = _rescale_for_pil_conversion(image) if do_rescale is None else do_rescale if do_rescale: image = rescale(image, 255) image = image.astype(np.uint8) return PIL.Image.fromarray(image, mode=image_mode) def get_size_with_aspect_ratio(image_size, size, max_size=None) -> tuple[int, int]: """ Computes the output image size given the input image size and the desired output size. Args: image_size (`tuple[int, int]`): The input image size. size (`int`): The desired output size. max_size (`int`, *optional*): The maximum allowed output size. """ height, width = image_size raw_size = None if max_size is not None: min_original_size = float(min((height, width))) max_original_size = float(max((height, width))) if max_original_size / min_original_size * size > max_size: raw_size = max_size * min_original_size / max_original_size size = int(round(raw_size)) if (height <= width and height == size) or (width <= height and width == size): oh, ow = height, width elif width < height: ow = size if max_size is not None and raw_size is not None: oh = int(raw_size * height / width) else: oh = int(size * height / width) else: oh = size if max_size is not None and raw_size is not None: ow = int(raw_size * width / height) else: ow = int(size * width / height) return (oh, ow) # Logic adapted from torchvision resizing logic: https://github.com/pytorch/vision/blob/511924c1ced4ce0461197e5caa64ce5b9e558aab/torchvision/transforms/functional.py#L366 def get_resize_output_image_size( input_image: np.ndarray, size: Union[int, tuple[int, int], list[int], tuple[int, ...]], default_to_square: bool = True, max_size: Optional[int] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> tuple: """ Find the target (height, width) dimension of the output image after resizing given the input image and the desired size. Args: input_image (`np.ndarray`): The image to resize. size (`int` or `tuple[int, int]` or list[int] or `tuple[int]`): The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to this. If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this number. i.e, if height > width, then image will be rescaled to (size * height / width, size). default_to_square (`bool`, *optional*, defaults to `True`): How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square (`size`,`size`). If set to `False`, will replicate [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize) with support for resizing only the smallest edge and providing an optional `max_size`. max_size (`int`, *optional*): The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater than `max_size` after being resized according to `size`, then the image is resized again so that the longer edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter than `size`. Only used if `default_to_square` is `False`. input_data_format (`ChannelDimension`, *optional*): The channel dimension format of the input image. If unset, will use the inferred format from the input. Returns: `tuple`: The target (height, width) dimension of the output image after resizing. """ if isinstance(size, (tuple, list)): if len(size) == 2: return tuple(size) elif len(size) == 1: # Perform same logic as if size was an int size = size[0] else: raise ValueError("size must have 1 or 2 elements if it is a list or tuple") if default_to_square: return (size, size) height, width = get_image_size(input_image, input_data_format) short, long = (width, height) if width <= height else (height, width) requested_new_short = size new_short, new_long = requested_new_short, int(requested_new_short * long / short) if max_size is not None: if max_size <= requested_new_short: raise ValueError( f"max_size = {max_size} must be strictly greater than the requested " f"size for the smaller edge size = {size}" ) if new_long > max_size: new_short, new_long = int(max_size * new_short / new_long), max_size return (new_long, new_short) if width <= height else (new_short, new_long) def resize( image: np.ndarray, size: tuple[int, int], resample: Optional["PILImageResampling"] = None, reducing_gap: Optional[int] = None, data_format: Optional[ChannelDimension] = None, return_numpy: bool = True, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """ Resizes `image` to `(height, width)` specified by `size` using the PIL library. Args: image (`np.ndarray`): The image to resize. size (`tuple[int, int]`): The size to use for resizing the image. resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`): The filter to user for resampling. reducing_gap (`int`, *optional*): Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to the fair resampling. See corresponding Pillow documentation for more details. data_format (`ChannelDimension`, *optional*): The channel dimension format of the output image. If unset, will use the inferred format from the input. return_numpy (`bool`, *optional*, defaults to `True`): Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is returned. input_data_format (`ChannelDimension`, *optional*): The channel dimension format of the input image. If unset, will use the inferred format from the input. Returns: `np.ndarray`: The resized image. """ requires_backends(resize, ["vision"]) resample = resample if resample is not None else PILImageResampling.BILINEAR if not len(size) == 2: raise ValueError("size must have 2 elements") # For all transformations, we want to keep the same data format as the input image unless otherwise specified. # The resized image from PIL will always have channels last, so find the input format first. if input_data_format is None: input_data_format = infer_channel_dimension_format(image) data_format = input_data_format if data_format is None else data_format # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use # the pillow library to resize the image and then convert back to numpy do_rescale = False if not isinstance(image, PIL.Image.Image): do_rescale = _rescale_for_pil_conversion(image) image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format) height, width = size # PIL images are in the format (width, height) resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap) if return_numpy: resized_image = np.array(resized_image) # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image # so we need to add it back if necessary. resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image # The image is always in channels last format after converting from a PIL image resized_image = to_channel_dimension_format( resized_image, data_format, input_channel_dim=ChannelDimension.LAST ) # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to # rescale it back to the original range. resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image return resized_image def normalize( image: np.ndarray, mean: Union[float, Collection[float]], std: Union[float, Collection[float]], data_format: Optional[ChannelDimension] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """ Normalizes `image` using the mean and standard deviation specified by `mean` and `std`. image = (image - mean) / std Args: image (`np.ndarray`): The image to normalize. mean (`float` or `Collection[float]`): The mean to use for normalization. std (`float` or `Collection[float]`): The standard deviation to use for normalization. data_format (`ChannelDimension`, *optional*): The channel dimension format of the output image. If unset, will use the inferred format from the input. input_data_format (`ChannelDimension`, *optional*): The channel dimension format of the input image. If unset, will use the inferred format from the input. """ if not isinstance(image, np.ndarray): raise TypeError("image must be a numpy array") if input_data_format is None: input_data_format = infer_channel_dimension_format(image) channel_axis = get_channel_dimension_axis(image, input_data_format=input_data_format) num_channels = image.shape[channel_axis] # We cast to float32 to avoid errors that can occur when subtracting uint8 values. # We preserve the original dtype if it is a float type to prevent upcasting float16. if not np.issubdtype(image.dtype, np.floating): image = image.astype(np.float32) if isinstance(mean, Collection): if len(mean) != num_channels: raise ValueError(f"mean must have {num_channels} elements if it is an iterable, got {len(mean)}") else: mean = [mean] * num_channels mean = np.array(mean, dtype=image.dtype) if isinstance(std, Collection): if len(std) != num_channels: raise ValueError(f"std must have {num_channels} elements if it is an iterable, got {len(std)}") else: std = [std] * num_channels std = np.array(std, dtype=image.dtype) if input_data_format == ChannelDimension.LAST: image = (image - mean) / std else: image = ((image.T - mean) / std).T image = to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image return image def center_crop( image: np.ndarray, size: tuple[int, int], data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """ Crops the `image` to the specified `size` using a center crop. Note that if the image is too small to be cropped to the size given, it will be padded (so the returned result will always be of size `size`). Args: image (`np.ndarray`): The image to crop. size (`tuple[int, int]`): The target size for the cropped image. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the output image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use the inferred format of the input image. input_data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use the inferred format of the input image. Returns: `np.ndarray`: The cropped image. """ requires_backends(center_crop, ["vision"]) if not isinstance(image, np.ndarray): raise TypeError(f"Input image must be of type np.ndarray, got {type(image)}") if not isinstance(size, Iterable) or len(size) != 2: raise ValueError("size must have 2 elements representing the height and width of the output image") if input_data_format is None: input_data_format = infer_channel_dimension_format(image) output_data_format = data_format if data_format is not None else input_data_format # We perform the crop in (C, H, W) format and then convert to the output format image = to_channel_dimension_format(image, ChannelDimension.FIRST, input_data_format) orig_height, orig_width = get_image_size(image, ChannelDimension.FIRST) crop_height, crop_width = size crop_height, crop_width = int(crop_height), int(crop_width) # In case size is odd, (image_shape[0] + size[0]) // 2 won't give the proper result. top = (orig_height - crop_height) // 2 bottom = top + crop_height # In case size is odd, (image_shape[1] + size[1]) // 2 won't give the proper result. left = (orig_width - crop_width) // 2 right = left + crop_width # Check if cropped area is within image boundaries if top >= 0 and bottom <= orig_height and left >= 0 and right <= orig_width: image = image[..., top:bottom, left:right] image = to_channel_dimension_format(image, output_data_format, ChannelDimension.FIRST) return image # Otherwise, we may need to pad if the image is too small. Oh joy... new_height = max(crop_height, orig_height) new_width = max(crop_width, orig_width) new_shape = image.shape[:-2] + (new_height, new_width) new_image = np.zeros_like(image, shape=new_shape) # If the image is too small, pad it with zeros top_pad = ceil((new_height - orig_height) / 2) bottom_pad = top_pad + orig_height left_pad = ceil((new_width - orig_width) / 2) right_pad = left_pad + orig_width new_image[..., top_pad:bottom_pad, left_pad:right_pad] = image top += top_pad bottom += top_pad left += left_pad right += left_pad new_image = new_image[..., max(0, top) : min(new_height, bottom), max(0, left) : min(new_width, right)] new_image = to_channel_dimension_format(new_image, output_data_format, ChannelDimension.FIRST) return new_image def _center_to_corners_format_torch(bboxes_center: "torch.Tensor") -> "torch.Tensor": center_x, center_y, width, height = bboxes_center.unbind(-1) bbox_corners = torch.stack( # top left x, top left y, bottom right x, bottom right y [(center_x - 0.5 * width), (center_y - 0.5 * height), (center_x + 0.5 * width), (center_y + 0.5 * height)], dim=-1, ) return bbox_corners def _center_to_corners_format_numpy(bboxes_center: np.ndarray) -> np.ndarray: center_x, center_y, width, height = bboxes_center.T bboxes_corners = np.stack( # top left x, top left y, bottom right x, bottom right y [center_x - 0.5 * width, center_y - 0.5 * height, center_x + 0.5 * width, center_y + 0.5 * height], axis=-1, ) return bboxes_corners # 2 functions below inspired by https://github.com/facebookresearch/detr/blob/master/util/box_ops.py def center_to_corners_format(bboxes_center: TensorType) -> TensorType: """ Converts bounding boxes from center format to corners format. center format: contains the coordinate for the center of the box and its width, height dimensions (center_x, center_y, width, height) corners format: contains the coordinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y) """ # Function is used during model forward pass, so we use torch if relevant, without converting to numpy if is_torch_tensor(bboxes_center): return _center_to_corners_format_torch(bboxes_center) elif isinstance(bboxes_center, np.ndarray): return _center_to_corners_format_numpy(bboxes_center) raise ValueError(f"Unsupported input type {type(bboxes_center)}") def _corners_to_center_format_torch(bboxes_corners: "torch.Tensor") -> "torch.Tensor": top_left_x, top_left_y, bottom_right_x, bottom_right_y = bboxes_corners.unbind(-1) b = [ (top_left_x + bottom_right_x) / 2, # center x (top_left_y + bottom_right_y) / 2, # center y (bottom_right_x - top_left_x), # width (bottom_right_y - top_left_y), # height ] return torch.stack(b, dim=-1) def _corners_to_center_format_numpy(bboxes_corners: np.ndarray) -> np.ndarray: top_left_x, top_left_y, bottom_right_x, bottom_right_y = bboxes_corners.T bboxes_center = np.stack( [ (top_left_x + bottom_right_x) / 2, # center x (top_left_y + bottom_right_y) / 2, # center y (bottom_right_x - top_left_x), # width (bottom_right_y - top_left_y), # height ], axis=-1, ) return bboxes_center def corners_to_center_format(bboxes_corners: TensorType) -> TensorType: """ Converts bounding boxes from corners format to center format. corners format: contains the coordinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y) center format: contains the coordinate for the center of the box and its the width, height dimensions (center_x, center_y, width, height) """ # Inverse function accepts different input types so implemented here too if is_torch_tensor(bboxes_corners): return _corners_to_center_format_torch(bboxes_corners) elif isinstance(bboxes_corners, np.ndarray): return _corners_to_center_format_numpy(bboxes_corners) raise ValueError(f"Unsupported input type {type(bboxes_corners)}") # 2 functions below copied from https://github.com/cocodataset/panopticapi/blob/master/panopticapi/utils.py # Copyright (c) 2018, Alexander Kirillov # All rights reserved. def rgb_to_id(color): """ Converts RGB color to unique ID. """ if isinstance(color, np.ndarray) and len(color.shape) == 3: if color.dtype == np.uint8: color = color.astype(np.int32) return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2] return int(color[0] + 256 * color[1] + 256 * 256 * color[2]) def id_to_rgb(id_map): """ Converts unique ID to RGB color. """ if isinstance(id_map, np.ndarray): id_map_copy = id_map.copy() rgb_shape = tuple(list(id_map.shape) + [3]) rgb_map = np.zeros(rgb_shape, dtype=np.uint8) for i in range(3): rgb_map[..., i] = id_map_copy % 256 id_map_copy //= 256 return rgb_map color = [] for _ in range(3): color.append(id_map % 256) id_map //= 256 return color class PaddingMode(ExplicitEnum): """ Enum class for the different padding modes to use when padding images. """ CONSTANT = "constant" REFLECT = "reflect" REPLICATE = "replicate" SYMMETRIC = "symmetric" def pad( image: np.ndarray, padding: Union[int, tuple[int, int], Iterable[tuple[int, int]]], mode: PaddingMode = PaddingMode.CONSTANT, constant_values: Union[float, Iterable[float]] = 0.0, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """ Pads the `image` with the specified (height, width) `padding` and `mode`. Args: image (`np.ndarray`): The image to pad. padding (`int` or `tuple[int, int]` or `Iterable[tuple[int, int]]`): Padding to apply to the edges of the height, width axes. Can be one of three formats: - `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis. - `((before, after),)` yields same before and after pad for height and width. - `(pad,)` or int is a shortcut for before = after = pad width for all axes. mode (`PaddingMode`): The padding mode to use. Can be one of: - `"constant"`: pads with a constant value. - `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the vector along each axis. - `"replicate"`: pads with the replication of the last value on the edge of the array along each axis. - `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array. constant_values (`float` or `Iterable[float]`, *optional*): The value to use for the padding if `mode` is `"constant"`. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the output image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use same as the input image. input_data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use the inferred format of the input image. Returns: `np.ndarray`: The padded image. """ if input_data_format is None: input_data_format = infer_channel_dimension_format(image) def _expand_for_data_format(values): """ Convert values to be in the format expected by np.pad based on the data format. """ if isinstance(values, (int, float)): values = ((values, values), (values, values)) elif isinstance(values, tuple) and len(values) == 1: values = ((values[0], values[0]), (values[0], values[0])) elif isinstance(values, tuple) and len(values) == 2 and isinstance(values[0], int): values = (values, values) elif isinstance(values, tuple) and len(values) == 2 and isinstance(values[0], tuple): pass else: raise ValueError(f"Unsupported format: {values}") # add 0 for channel dimension values = ((0, 0), *values) if input_data_format == ChannelDimension.FIRST else (*values, (0, 0)) # Add additional padding if there's a batch dimension values = ((0, 0), *values) if image.ndim == 4 else values return values padding = _expand_for_data_format(padding) if mode == PaddingMode.CONSTANT: constant_values = _expand_for_data_format(constant_values) image = np.pad(image, padding, mode="constant", constant_values=constant_values) elif mode == PaddingMode.REFLECT: image = np.pad(image, padding, mode="reflect") elif mode == PaddingMode.REPLICATE: image = np.pad(image, padding, mode="edge") elif mode == PaddingMode.SYMMETRIC: image = np.pad(image, padding, mode="symmetric") else: raise ValueError(f"Invalid padding mode: {mode}") image = to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image return image # TODO (Amy): Accept 1/3/4 channel numpy array as input and return np.array as default def convert_to_rgb(image: ImageInput) -> ImageInput: """ Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image as is. Args: image (Image): The image to convert. """ requires_backends(convert_to_rgb, ["vision"]) if not isinstance(image, PIL.Image.Image): return image if image.mode == "RGB": return image image = image.convert("RGB") return image def flip_channel_order( image: np.ndarray, data_format: Optional[ChannelDimension] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """ Flips the channel order of the image. If the image is in RGB format, it will be converted to BGR and vice versa. Args:
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/activations.py
src/transformers/activations.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools import math from collections import OrderedDict import torch from torch import Tensor, nn from .integrations.hub_kernels import use_kernel_forward_from_hub from .utils import logging from .utils.import_utils import is_torchdynamo_compiling logger = logging.get_logger(__name__) @use_kernel_forward_from_hub("GeluTanh") class GELUTanh(nn.Module): """ A fast C implementation of the tanh approximation of the GeLU activation function. See https://huggingface.co/papers/1606.08415. This implementation is equivalent to NewGELU and FastGELU but much faster. However, it is not an exact numerical match due to rounding errors. """ def __init__(self, use_gelu_tanh_python: bool = False): super().__init__() if use_gelu_tanh_python: self.act = self._gelu_tanh_python else: self.act = functools.partial(nn.functional.gelu, approximate="tanh") def _gelu_tanh_python(self, input: Tensor) -> Tensor: return input * 0.5 * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(input, 3.0)))) def forward(self, input: Tensor) -> Tensor: return self.act(input) # Added for compatibility with autoawq which is archived now and imports PytorchGELUTanh from activations.py PytorchGELUTanh = GELUTanh @use_kernel_forward_from_hub("NewGELU") class NewGELUActivation(nn.Module): """ Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see the Gaussian Error Linear Units paper: https://huggingface.co/papers/1606.08415 """ def forward(self, input: Tensor) -> Tensor: return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(input, 3.0)))) @use_kernel_forward_from_hub("GeLU") class GELUActivation(nn.Module): """ Original Implementation of the GELU activation function in Google BERT repo when initially created. For information: OpenAI GPT's GELU is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) This is now written in C in nn.functional Also see the Gaussian Error Linear Units paper: https://huggingface.co/papers/1606.08415 """ def __init__(self, use_gelu_python: bool = False): super().__init__() if use_gelu_python: self.act = self._gelu_python else: self.act = nn.functional.gelu def _gelu_python(self, input: Tensor) -> Tensor: return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0))) def forward(self, input: Tensor) -> Tensor: return self.act(input) @use_kernel_forward_from_hub("SiLU") class SiLUActivation(nn.Module): """ See Gaussian Error Linear Units (Hendrycks et al., https://arxiv.org/abs/1606.08415) where the SiLU (Sigmoid Linear Unit) was originally introduced and coined, and see Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning (Elfwing et al., https://arxiv.org/abs/1702.03118) and Swish: a Self-Gated Activation Function (Ramachandran et al., https://arxiv.org/abs/1710.05941v1) where the SiLU was experimented with later. """ def forward(self, input: Tensor) -> Tensor: return nn.functional.silu(input) @use_kernel_forward_from_hub("FastGELU") class FastGELUActivation(nn.Module): """ Applies GELU approximation that is slower than QuickGELU but more accurate. See: https://github.com/hendrycks/GELUs """ def forward(self, input: Tensor) -> Tensor: return 0.5 * input * (1.0 + torch.tanh(input * 0.7978845608 * (1.0 + 0.044715 * input * input))) @use_kernel_forward_from_hub("QuickGELU") class QuickGELUActivation(nn.Module): """ Applies GELU approximation that is fast but somewhat inaccurate. See: https://github.com/hendrycks/GELUs """ def forward(self, input: Tensor) -> Tensor: return input * torch.sigmoid(1.702 * input) class ClippedGELUActivation(nn.Module): """ Clip the range of possible GeLU outputs between [min, max]. This is especially useful for quantization purpose, as it allows mapping negatives values in the GeLU spectrum. For more information on this trick, please refer to https://huggingface.co/papers/2004.09602. Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))). See https://huggingface.co/papers/1606.08415 """ def __init__(self, min: float, max: float): if min > max: raise ValueError(f"min should be < max (got min: {min}, max: {max})") super().__init__() self.min = min self.max = max def forward(self, x: Tensor) -> Tensor: return torch.clip(gelu(x), self.min, self.max) class AccurateGELUActivation(nn.Module): """ Applies GELU approximation that is faster than default and more accurate than QuickGELU. See: https://github.com/hendrycks/GELUs Implemented along with MEGA (Moving Average Equipped Gated Attention) """ def __init__(self): super().__init__() self.precomputed_constant = math.sqrt(2 / math.pi) def forward(self, input: Tensor) -> Tensor: return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.044715 * torch.pow(input, 3)))) class MishActivation(nn.Module): """ See Mish: A Self-Regularized Non-Monotonic Activation Function (Misra., https://huggingface.co/papers/1908.08681). Also visit the official repository for the paper: https://github.com/digantamisra98/Mish """ def __init__(self): super().__init__() self.act = nn.functional.mish def _mish_python(self, input: Tensor) -> Tensor: return input * torch.tanh(nn.functional.softplus(input)) def forward(self, input: Tensor) -> Tensor: return self.act(input) class LinearActivation(nn.Module): """ Applies the linear activation function, i.e. forwarding input directly to output. """ def forward(self, input: Tensor) -> Tensor: return input class LaplaceActivation(nn.Module): """ Applies elementwise activation based on Laplace function, introduced in MEGA as an attention activation. See https://huggingface.co/papers/2209.10655 Inspired by squared relu, but with bounded range and gradient for better stability """ def forward(self, input, mu=0.707107, sigma=0.282095): input = (input - mu).div(sigma * math.sqrt(2.0)) return 0.5 * (1.0 + torch.erf(input)) class ReLUSquaredActivation(nn.Module): """ Applies the relu^2 activation introduced in https://huggingface.co/papers/2109.08668 """ def forward(self, input): relu_applied = nn.functional.relu(input) squared = torch.square(relu_applied) return squared class ClassInstantier(OrderedDict): def __getitem__(self, key): content = super().__getitem__(key) cls, kwargs = content if isinstance(content, tuple) else (content, {}) return cls(**kwargs) class XIELUActivation(nn.Module): """ Applies the xIELU activation function introduced in https://arxiv.org/abs/2411.13010 If the user has installed the nickjbrowning/XIELU wheel, we import xIELU CUDA Otherwise, we emit a single warning and use xIELU Python """ def __init__( self, alpha_p_init=0.8, alpha_n_init=0.8, beta=0.5, eps=-1e-6, dtype=torch.bfloat16, with_vector_loads=False, ): super().__init__() self.alpha_p = nn.Parameter(torch.log(torch.expm1(torch.tensor(alpha_p_init, dtype=dtype))).unsqueeze(0)) self.alpha_n = nn.Parameter( torch.log(torch.expm1(torch.tensor(alpha_n_init - beta, dtype=dtype))).unsqueeze(0) ) self.register_buffer("beta", torch.tensor(beta, dtype=dtype)) self.register_buffer("eps", torch.tensor(eps, dtype=dtype)) self.with_vector_loads = with_vector_loads # Temporary until xIELU CUDA fully implemented self._beta_scalar = float(self.beta.detach().cpu().float().item()) self._eps_scalar = float(self.eps.detach().cpu().float().item()) self._xielu_cuda_obj = None try: import xielu.ops # noqa: F401 self._xielu_cuda_obj = torch.classes.xielu.XIELU() msg = "Using experimental xIELU CUDA." try: from torch._dynamo import allow_in_graph self._xielu_cuda_fn = allow_in_graph(self._xielu_cuda) msg += " Enabled torch._dynamo for xIELU CUDA." except Exception as err: msg += f" Could not enable torch._dynamo for xIELU ({err}) - this may result in slower performance." self._xielu_cuda_fn = self._xielu_cuda logger.warning_once(msg) except Exception as err: logger.warning_once( "CUDA-fused xIELU not available (%s) – falling back to a Python version.\n" "For CUDA xIELU (experimental), `pip install git+https://github.com/nickjbrowning/XIELU`", str(err), ) def _xielu_python(self, x: Tensor) -> Tensor: alpha_p = nn.functional.softplus(self.alpha_p) alpha_n = self.beta + nn.functional.softplus(self.alpha_n) return torch.where( x > 0, alpha_p * x * x + self.beta * x, (torch.expm1(torch.min(x, self.eps)) - x) * alpha_n + self.beta * x, ) def _xielu_cuda(self, x: Tensor) -> Tensor: """Firewall function to prevent torch.compile from seeing .item() calls""" original_shape = x.shape # CUDA kernel expects 3D tensors, reshape if needed while x.dim() < 3: x = x.unsqueeze(0) if x.dim() > 3: x = x.view(-1, 1, x.size(-1)) if original_shape != x.shape: logger.warning_once( "Warning: xIELU input tensor expects 3 dimensions but got (shape: %s). Reshaping to (shape: %s).", original_shape, x.shape, ) result = self._xielu_cuda_obj.forward( x, self.alpha_p.to(x.dtype), self.alpha_n.to(x.dtype), # Temporary until xIELU CUDA fully implemented -> self.{beta,eps}.item() self._beta_scalar, self._eps_scalar, self.with_vector_loads, ) return result.view(original_shape) def forward(self, input: Tensor) -> Tensor: if self._xielu_cuda_obj is not None and input.is_cuda: if not is_torchdynamo_compiling(): return self._xielu_cuda_fn(input) else: logger.warning_once("torch._dynamo is compiling, using Python version of xIELU.") return self._xielu_python(input) ACT2CLS = { "gelu": GELUActivation, "gelu_10": (ClippedGELUActivation, {"min": -10, "max": 10}), "gelu_fast": FastGELUActivation, "gelu_new": NewGELUActivation, "gelu_python": (GELUActivation, {"use_gelu_python": True}), "gelu_pytorch_tanh": GELUTanh, "gelu_python_tanh": (GELUTanh, {"use_gelu_tanh_python": True}), "gelu_accurate": AccurateGELUActivation, "laplace": LaplaceActivation, "leaky_relu": nn.LeakyReLU, "linear": LinearActivation, "mish": MishActivation, "quick_gelu": QuickGELUActivation, "relu": nn.ReLU, "relu2": ReLUSquaredActivation, "relu6": nn.ReLU6, "sigmoid": nn.Sigmoid, "silu": SiLUActivation, "swish": nn.SiLU, "tanh": nn.Tanh, "prelu": nn.PReLU, "xielu": XIELUActivation, } ACT2FN = ClassInstantier(ACT2CLS) def get_activation(activation_string): if activation_string in ACT2FN: return ACT2FN[activation_string] else: raise KeyError(f"function {activation_string} not found in ACT2FN mapping {list(ACT2FN.keys())}") # For backwards compatibility with: from activations import gelu_python gelu_python = get_activation("gelu_python") gelu_new = get_activation("gelu_new") gelu = get_activation("gelu") gelu_fast = get_activation("gelu_fast") quick_gelu = get_activation("quick_gelu") silu = get_activation("silu") mish = get_activation("mish") linear_act = get_activation("linear")
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/configuration_utils.py
src/transformers/configuration_utils.py
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Configuration base class and utilities.""" import copy import json import math import os import warnings from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union from huggingface_hub import create_repo from packaging import version from . import __version__ from .dynamic_module_utils import custom_object_save from .generation.configuration_utils import GenerationConfig from .modeling_gguf_pytorch_utils import load_gguf_checkpoint from .modeling_rope_utils import RotaryEmbeddingConfigMixin from .utils import ( CONFIG_NAME, PushToHubMixin, cached_file, copy_func, extract_commit_hash, is_torch_available, logging, ) from .utils.generic import is_timm_config_dict if TYPE_CHECKING: import torch logger = logging.get_logger(__name__) # type hinting: specifying the type of config class that inherits from PreTrainedConfig SpecificPreTrainedConfigType = TypeVar("SpecificPreTrainedConfigType", bound="PreTrainedConfig") _FLOAT_TAG_KEY = "__float__" _FLOAT_TAG_VALUES = {"Infinity": float("inf"), "-Infinity": float("-inf"), "NaN": float("nan")} class PreTrainedConfig(PushToHubMixin, RotaryEmbeddingConfigMixin): # no-format r""" Base class for all configuration classes. Handles a few parameters common to all models' configurations as well as methods for loading/downloading/saving configurations. <Tip> A configuration file can be loaded and saved to disk. Loading the configuration file and using this file to initialize a model does **not** load the model weights. It only affects the model's configuration. </Tip> Class attributes (overridden by derived classes): - **model_type** (`str`) -- An identifier for the model type, serialized into the JSON file, and used to recreate the correct object in [`~transformers.AutoConfig`]. - **has_no_defaults_at_init** (`bool`) -- Whether the config class can be initialized without providing input arguments. Some configurations requires inputs to be defined at init and have no default values, usually these are composite configs, (but not necessarily) such as [`~transformers.EncoderDecoderConfig`] or [`~RagConfig`]. They have to be initialized from two or more configs of type [`~transformers.PreTrainedConfig`]. - **keys_to_ignore_at_inference** (`list[str]`) -- A list of keys to ignore by default when looking at dictionary outputs of the model during inference. - **attribute_map** (`dict[str, str]`) -- A dict that maps model specific attribute names to the standardized naming of attributes. - **base_model_tp_plan** (`dict[str, Any]`) -- A dict that maps sub-modules FQNs of a base model to a tensor parallel plan applied to the sub-module when `model.tensor_parallel` is called. - **base_model_pp_plan** (`dict[str, tuple[list[str]]]`) -- A dict that maps child-modules of a base model to a pipeline parallel plan that enables users to place the child-module on the appropriate device. Common attributes (present in all subclasses): - **vocab_size** (`int`) -- The number of tokens in the vocabulary, which is also the first dimension of the embeddings matrix (this attribute may be missing for models that don't have a text modality like ViT). - **hidden_size** (`int`) -- The hidden size of the model. - **num_attention_heads** (`int`) -- The number of attention heads used in the multi-head attention layers of the model. - **num_hidden_layers** (`int`) -- The number of blocks in the model. <Tip warning={true}> Setting parameters for sequence generation in the model config is deprecated. For backward compatibility, loading some of them will still be possible, but attempting to overwrite them will throw an exception -- you should set them in a [~transformers.GenerationConfig]. Check the documentation of [~transformers.GenerationConfig] for more information about the individual parameters. </Tip> Arg: name_or_path (`str`, *optional*, defaults to `""`): Store the string that was passed to [`PreTrainedModel.from_pretrained`] as `pretrained_model_name_or_path` if the configuration was created with such a method. output_hidden_states (`bool`, *optional*, defaults to `False`): Whether or not the model should return all hidden-states. output_attentions (`bool`, *optional*, defaults to `False`): Whether or not the model should returns all attentions. return_dict (`bool`, *optional*, defaults to `True`): Whether or not the model should return a [`~transformers.utils.ModelOutput`] instead of a plain tuple. is_encoder_decoder (`bool`, *optional*, defaults to `False`): Whether the model is used as an encoder/decoder or not. is_decoder (`bool`, *optional*, defaults to `False`): Whether to only use the decoder in an encoder-decoder architecture, otherwise it has no effect on decoder-only or encoder-only architectures. cross_attention_hidden_size (`bool`, *optional*): The hidden size of the cross-attention layer in case the model is used as a decoder in an encoder-decoder setting and the cross-attention hidden dimension differs from `self.config.hidden_size`. add_cross_attention (`bool`, *optional*, defaults to `False`): Whether cross-attention layers should be added to the model. Note, this option is only relevant for models that can be used as decoder models within the [`EncoderDecoderModel`] class, which consists of all models in `AUTO_MODELS_FOR_CAUSAL_LM`. chunk_size_feed_forward (`int`, *optional*, defaults to `0`): The chunk size of all feed forward layers in the residual attention blocks. A chunk size of `0` means that the feed forward layer is not chunked. A chunk size of n means that the feed forward layer processes `n` < sequence_length embeddings at a time. For more information on feed forward chunking, see [How does Feed Forward Chunking work?](../glossary.html#feed-forward-chunking). > Parameters for fine-tuning tasks architectures (`list[str]`, *optional*): Model architectures that can be used with the model pretrained weights. finetuning_task (`str`, *optional*): Name of the task used to fine-tune the model. id2label (`dict[int, str]`, *optional*): A map from index (for instance prediction index, or target index) to label. label2id (`dict[str, int]`, *optional*): A map from label to index for the model. num_labels (`int`, *optional*): Number of labels to use in the last layer added to the model, typically for a classification task. task_specific_params (`dict[str, Any]`, *optional*): Additional keyword arguments to store for the current task. problem_type (`str`, *optional*): Problem type for `XxxForSequenceClassification` models. Can be one of `"regression"`, `"single_label_classification"` or `"multi_label_classification"`. > Parameters linked to the tokenizer tokenizer_class (`str`, *optional*): The name of the associated tokenizer class to use (if none is set, will use the tokenizer associated to the model by default). prefix (`str`, *optional*): A specific prompt that should be added at the beginning of each text before calling the model. bos_token_id (`int`, *optional*): The id of the _beginning-of-stream_ token. pad_token_id (`int`, *optional*): The id of the _padding_ token. eos_token_id (`int`, *optional*): The id of the _end-of-stream_ token. decoder_start_token_id (`int`, *optional*): If an encoder-decoder model starts decoding with a different token than _bos_, the id of that token. sep_token_id (`int`, *optional*): The id of the _separation_ token. > PyTorch specific parameters tie_word_embeddings (`bool`, *optional*, defaults to `True`): Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the model has a output word embedding layer. dtype (`str`, *optional*): The `dtype` of the weights. This attribute can be used to initialize the model to a non-default `dtype` (which is normally `float32`) and thus allow for optimal storage allocation. For example, if the saved model is `float16`, ideally we want to load it back using the minimal amount of memory needed to load `float16` weights. """ model_type: str = "" base_config_key: str = "" sub_configs: dict[str, type["PreTrainedConfig"]] = {} has_no_defaults_at_init: bool = False attribute_map: dict[str, str] = {} base_model_tp_plan: Optional[dict[str, Any]] = None base_model_pp_plan: Optional[dict[str, tuple[list[str]]]] = None base_model_ep_plan: Optional[dict[str, tuple[list[str]]]] = None _auto_class: Optional[str] = None def __setattr__(self, key, value): if key in super().__getattribute__("attribute_map"): key = super().__getattribute__("attribute_map")[key] super().__setattr__(key, value) def __getattribute__(self, key): if key != "attribute_map" and key in super().__getattribute__("attribute_map"): key = super().__getattribute__("attribute_map")[key] return super().__getattribute__(key) def __init__( self, *, # All models common arguments output_hidden_states: bool = False, output_attentions: bool = False, return_dict: bool = True, dtype: Optional[Union[str, "torch.dtype"]] = None, # Common arguments tie_word_embeddings: bool = True, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, is_decoder: bool = False, cross_attention_hidden_size: Optional[int] = None, add_cross_attention: bool = False, # Fine-tuning task arguments architectures: Optional[list[str]] = None, finetuning_task: Optional[str] = None, id2label: Optional[dict[int, str]] = None, label2id: Optional[dict[str, int]] = None, num_labels: Optional[int] = None, task_specific_params: Optional[dict[str, Any]] = None, problem_type: Optional[str] = None, # Tokenizer kwargs tokenizer_class: Optional[str] = None, prefix: Optional[str] = None, bos_token_id: Optional[int] = None, pad_token_id: Optional[int] = None, eos_token_id: Optional[int] = None, sep_token_id: Optional[int] = None, decoder_start_token_id: Optional[int] = None, **kwargs, ): # Validation for some arguments if label2id is not None and not isinstance(label2id, dict): raise ValueError("Argument label2id should be a dictionary.") if id2label is not None and not isinstance(id2label, dict): raise ValueError("Argument id2label should be a dictionary.") if num_labels is not None and id2label is not None and len(id2label) != num_labels: logger.warning( f"You passed `num_labels={num_labels}` which is incompatible to " f"the `id2label` map of length `{len(id2label)}`." ) if problem_type is not None and problem_type not in ( "regression", "single_label_classification", "multi_label_classification", ): raise ValueError( f"The config parameter `problem_type` was not understood: received {problem_type} " "but only 'regression', 'single_label_classification' and 'multi_label_classification' are valid." ) # BC for the `torch_dtype` argument instead of the simpler `dtype` # Do not warn, as it would otherwise always be triggered since most configs on the hub have `torch_dtype` if (torch_dtype := kwargs.pop("torch_dtype", None)) is not None: # If both are provided, keep `dtype` dtype = dtype if dtype is not None else torch_dtype if dtype is not None and isinstance(dtype, str) and is_torch_available(): # we will start using self.dtype in v5, but to be consistent with # from_pretrained's dtype arg convert it to an actual torch.dtype object import torch dtype = getattr(torch, dtype) # BC for rotary embeddings. We will pop out legacy keys from kwargs and rename to new format if hasattr(self, "rope_parameters"): ignore_keys_at_rope_validation = kwargs.pop("ignore_keys_at_rope_validation", None) kwargs = self.convert_rope_params_to_dict( ignore_keys_at_rope_validation=ignore_keys_at_rope_validation, **kwargs ) # Attributes common for all models self.return_dict = return_dict self.output_hidden_states = output_hidden_states self.dtype = dtype self._output_attentions = output_attentions # has public property # Less common kwargs, only used by some models if "tie_encoder_decoder" in kwargs: tie_encoder_decoder = kwargs.pop("tie_encoder_decoder") tie_word_embeddings = tie_encoder_decoder or tie_word_embeddings self.tie_word_embeddings = tie_word_embeddings self.chunk_size_feed_forward = chunk_size_feed_forward # Encoder-decoder models attributes self.is_encoder_decoder = is_encoder_decoder self.is_decoder = is_decoder # used in encoder-decoder models to differentiate encoder from decoder self.cross_attention_hidden_size = cross_attention_hidden_size self.add_cross_attention = add_cross_attention # Fine-tuning task attributes self.architectures = architectures self.finetuning_task = finetuning_task self.id2label = id2label self.label2id = label2id self.task_specific_params = task_specific_params self.problem_type = problem_type if self.id2label is None: self._create_id_label_maps(num_labels if num_labels is not None else 2) else: # Keys are always strings in JSON so convert ids to int here. self.id2label = {int(key): value for key, value in self.id2label.items()} # Tokenizer attributes self.tokenizer_class = tokenizer_class self.prefix = prefix self.bos_token_id = bos_token_id self.pad_token_id = pad_token_id self.eos_token_id = eos_token_id self.sep_token_id = sep_token_id self.decoder_start_token_id = decoder_start_token_id # Parameters for sequence generation saved in the config are popped instead of loading them. for parameter_name in GenerationConfig._get_default_generation_params().keys(): kwargs.pop(parameter_name, None) # Name or path to the pretrained checkpoint self._name_or_path = str(kwargs.pop("name_or_path", "")) self._commit_hash = kwargs.pop("_commit_hash", None) # Attention implementation to use, if relevant (it sets it recursively on sub-configs) self._attn_implementation = kwargs.pop("attn_implementation", None) # Drop the transformers version info self.transformers_version = kwargs.pop("transformers_version", None) # Deal with gradient checkpointing if kwargs.get("gradient_checkpointing", False): warnings.warn( "Passing `gradient_checkpointing` to a config initialization is deprecated and will be removed in v5 " "Transformers. Using `model.gradient_checkpointing_enable()` instead, or if you are using the " "`Trainer` API, pass `gradient_checkpointing=True` in your `TrainingArguments`." ) # Additional attributes without default values for key, value in kwargs.items(): try: setattr(self, key, value) except AttributeError as err: logger.error(f"Can't set {key} with value {value} for {self}") raise err def _create_id_label_maps(self, num_labels: int): self.id2label = {i: f"LABEL_{i}" for i in range(num_labels)} self.label2id = dict(zip(self.id2label.values(), self.id2label.keys())) @property def name_or_path(self) -> Optional[str]: return getattr(self, "_name_or_path", None) @name_or_path.setter def name_or_path(self, value): self._name_or_path = str(value) # Make sure that name_or_path is a string (for JSON encoding) @property def output_attentions(self): """ `bool`: Whether or not the model should returns all attentions. """ return self._output_attentions @output_attentions.setter def output_attentions(self, value: bool): # If we set `output_attentions` explicitly before the attn implementation, dispatch eager if value and self._attn_implementation is None: self._attn_implementation = "eager" if value and self._attn_implementation != "eager": raise ValueError( "The `output_attentions` attribute is not supported when using the `attn_implementation` set to " f"{self._attn_implementation}. Please set it to 'eager' instead." ) self._output_attentions = value @property def use_return_dict(self) -> bool: """ `bool`: Whether or not return [`~utils.ModelOutput`] instead of tuples. """ return self.return_dict @property def num_labels(self) -> int: """ `int`: The number of labels for classification models. """ return len(self.id2label) @num_labels.setter def num_labels(self, num_labels: int): # we do not store `num_labels` attribute in config, but instead # compute it based on the length of the `id2label` map if self.id2label is None or self.num_labels != num_labels: self._create_id_label_maps(num_labels) @property def _attn_implementation(self): return self._attn_implementation_internal @_attn_implementation.setter def _attn_implementation(self, value: str | dict | None): """We set it recursively on the sub-configs as well""" # Set if for current config current_attn = getattr(self, "_attn_implementation", None) attn_implementation = value if not isinstance(value, dict) else value.get("", current_attn) self._attn_implementation_internal = attn_implementation # Set it recursively on the subconfigs for subconfig_key in self.sub_configs: subconfig = getattr(self, subconfig_key, None) if subconfig is not None: current_subconfig_attn = getattr(subconfig, "_attn_implementation", None) sub_implementation = ( value if not isinstance(value, dict) else value.get(subconfig_key, current_subconfig_attn) ) subconfig._attn_implementation = sub_implementation @property def torch_dtype(self): logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!") return self.dtype @torch_dtype.setter def torch_dtype(self, value): logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!") self.dtype = value @property def rope_scaling(self): return self.rope_parameters @rope_scaling.setter def rope_scaling(self, value): self.rope_parameters = value def save_pretrained(self, save_directory: str | os.PathLike, push_to_hub: bool = False, **kwargs): """ Save a configuration object to the directory `save_directory`, so that it can be re-loaded using the [`~PreTrainedConfig.from_pretrained`] class method. Args: save_directory (`str` or `os.PathLike`): Directory where the configuration JSON file will be saved (will be created if it does not exist). push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace). kwargs (`dict[str, Any]`, *optional*): Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method. """ if os.path.isfile(save_directory): raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file") generation_parameters = self._get_generation_parameters() if len(generation_parameters) > 0: raise ValueError( "Some generation parameters are set in the model config. These should go into `model.generation_config`" f"as opposed to `model.config`. \nGeneration parameters found: {str(generation_parameters)}", ) os.makedirs(save_directory, exist_ok=True) if push_to_hub: commit_message = kwargs.pop("commit_message", None) repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1]) repo_id = create_repo(repo_id, exist_ok=True, **kwargs).repo_id files_timestamps = self._get_files_timestamps(save_directory) # This attribute is important to know on load, but should not be serialized on save. if "transformers_weights" in self: delattr(self, "transformers_weights") # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be # loaded from the Hub. if self._auto_class is not None: custom_object_save(self, save_directory, config=self) # If we save using the predefined names, we can load using `from_pretrained` output_config_file = os.path.join(save_directory, CONFIG_NAME) self.to_json_file(output_config_file, use_diff=True) logger.info(f"Configuration saved in {output_config_file}") if push_to_hub: self._upload_modified_files( save_directory, repo_id, files_timestamps, commit_message=commit_message, token=kwargs.get("token"), ) @classmethod def from_pretrained( cls: type[SpecificPreTrainedConfigType], pretrained_model_name_or_path: str | os.PathLike, cache_dir: str | os.PathLike | None = None, force_download: bool = False, local_files_only: bool = False, token: str | bool | None = None, revision: str = "main", **kwargs, ) -> SpecificPreTrainedConfigType: r""" Instantiate a [`PreTrainedConfig`] (or a derived class) from a pretrained model configuration. Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained model configuration hosted inside a model repo on huggingface.co. - a path to a *directory* containing a configuration file saved using the [`~PreTrainedConfig.save_pretrained`] method, e.g., `./my_model_directory/`. - a path or url to a saved configuration JSON *file*, e.g., `./my_model_directory/configuration.json`. cache_dir (`str` or `os.PathLike`, *optional*): Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force to (re-)download the configuration files and override the cached versions if they exist. proxies (`dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. token (`str` or `bool`, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use the token generated when running `hf auth login` (stored in `~/.huggingface`). revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. <Tip> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`. </Tip> return_unused_kwargs (`bool`, *optional*, defaults to `False`): If `False`, then this function returns just the final configuration object. If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the part of `kwargs` which has not been used to update `config` and is otherwise ignored. subfolder (`str`, *optional*, defaults to `""`): In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can specify the folder name here. kwargs (`dict[str, Any]`, *optional*): The values in kwargs of any keys which are configuration attributes will be used to override the loaded values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled by the `return_unused_kwargs` keyword parameter. Returns: [`PreTrainedConfig`]: The configuration object instantiated from this pretrained model. Examples: ```python # We can't instantiate directly the base class *PreTrainedConfig* so let's show the examples on a # derived class: BertConfig config = BertConfig.from_pretrained( "google-bert/bert-base-uncased" ) # Download configuration from huggingface.co and cache. config = BertConfig.from_pretrained( "./test/saved_model/" ) # E.g. config (or model) was saved using *save_pretrained('./test/saved_model/')* config = BertConfig.from_pretrained("./test/saved_model/my_configuration.json") config = BertConfig.from_pretrained("google-bert/bert-base-uncased", output_attentions=True, foo=False) assert config.output_attentions == True config, unused_kwargs = BertConfig.from_pretrained( "google-bert/bert-base-uncased", output_attentions=True, foo=False, return_unused_kwargs=True ) assert config.output_attentions == True assert unused_kwargs == {"foo": False} ```""" kwargs["cache_dir"] = cache_dir kwargs["force_download"] = force_download kwargs["local_files_only"] = local_files_only kwargs["revision"] = revision config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs) if cls.base_config_key and cls.base_config_key in config_dict: config_dict = config_dict[cls.base_config_key] if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type: # sometimes the config has no `base_config_key` if the config is used in several composite models # e.g. LlamaConfig. In that case we try to see if there is match in `model_type` before raising a warning for v in config_dict.values(): if isinstance(v, dict) and v.get("model_type") == cls.model_type: config_dict = v # raise warning only if we still can't see a match in `model_type` if config_dict["model_type"] != cls.model_type: logger.warning( f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(config_dict, **kwargs) @classmethod def get_config_dict( cls, pretrained_model_name_or_path: str | os.PathLike, **kwargs ) -> tuple[dict[str, Any], dict[str, Any]]: """ From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a [`PreTrainedConfig`] using `from_dict`. Parameters: pretrained_model_name_or_path (`str` or `os.PathLike`): The identifier of the pre-trained checkpoint from which we want the dictionary of parameters. Returns: `tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the configuration object. """ original_kwargs = copy.deepcopy(kwargs) # Get config dict associated with the base config file config_dict, kwargs = cls._get_config_dict(pretrained_model_name_or_path, **kwargs) if config_dict is None: return {}, kwargs if "_commit_hash" in config_dict: original_kwargs["_commit_hash"] = config_dict["_commit_hash"] # That config file may point us toward another config file to use. if "configuration_files" in config_dict: configuration_file = get_configuration_file(config_dict["configuration_files"]) config_dict, kwargs = cls._get_config_dict( pretrained_model_name_or_path, _configuration_file=configuration_file, **original_kwargs ) return config_dict, kwargs @classmethod def _get_config_dict( cls, pretrained_model_name_or_path: str | os.PathLike, **kwargs ) -> tuple[dict[str, Any], dict[str, Any]]: cache_dir = kwargs.pop("cache_dir", None) force_download = kwargs.pop("force_download", False) proxies = kwargs.pop("proxies", None) token = kwargs.pop("token", None) local_files_only = kwargs.pop("local_files_only", False) revision = kwargs.pop("revision", None) trust_remote_code = kwargs.pop("trust_remote_code", None) subfolder = kwargs.pop("subfolder", "") from_pipeline = kwargs.pop("_from_pipeline", None) from_auto_class = kwargs.pop("_from_auto", False) commit_hash = kwargs.pop("_commit_hash", None) gguf_file = kwargs.get("gguf_file") if trust_remote_code is True: logger.warning( "The argument `trust_remote_code` is to be used with Auto classes. It has no effect here and is" " ignored." ) user_agent = {"file_type": "config", "from_auto_class": from_auto_class} if from_pipeline is not None: user_agent["using_pipeline"] = from_pipeline pretrained_model_name_or_path = str(pretrained_model_name_or_path) is_local = os.path.isdir(pretrained_model_name_or_path) if os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)): # Special case when pretrained_model_name_or_path is a local file
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/tokenization_utils_tokenizers.py
src/transformers/tokenization_utils_tokenizers.py
# Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Tokenization classes for fast tokenizers (provided by HuggingFace's tokenizers library). For slow (python) tokenizers see tokenization_utils.py """ import copy import json import os from collections import defaultdict from collections.abc import Iterable from shutil import copyfile from typing import Any, Optional, Union import tokenizers.pre_tokenizers as pre_tokenizers_fast from huggingface_hub import is_offline_mode from tokenizers import AddedToken, processors from tokenizers import Encoding as EncodingFast from tokenizers import Tokenizer as TokenizerFast from tokenizers.decoders import Decoder as DecoderFast from tokenizers.trainers import BpeTrainer, UnigramTrainer, WordLevelTrainer, WordPieceTrainer from .integrations.ggml import convert_gguf_tokenizer from .modeling_gguf_pytorch_utils import load_gguf_checkpoint from .tokenization_utils_base import ( INIT_TOKENIZER_DOCSTRING, BatchEncoding, PreTokenizedInput, PreTrainedTokenizerBase, TextInput, TruncationStrategy, generate_merges, ) from .utils import PaddingStrategy, add_end_docstrings, logging logger = logging.get_logger(__name__) # Fast tokenizers (provided by HuggingFace tokenizer's library) can be saved in a single file TOKENIZER_FILE = "tokenizer.json" SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json" TOKENIZER_CONFIG_FILE = "tokenizer_config.json" TIKTOKEN_VOCAB_FILE = "tokenizer.model" # Slow tokenizers have an additional added tokens files ADDED_TOKENS_FILE = "added_tokens.json" INIT_TOKENIZER_DOCSTRING += """ tokenizer_object ([`tokenizers.Tokenizer`]): A [`tokenizers.Tokenizer`] object from 🤗 tokenizers to instantiate from. See [Using tokenizers from 🤗 tokenizers](../fast_tokenizers) for more information. tokenizer_file ([`str`]): A path to a local JSON file representing a previously serialized [`tokenizers.Tokenizer`] object from 🤗 tokenizers. """ MODEL_TO_TRAINER_MAPPING = { "BPE": BpeTrainer, "Unigram": UnigramTrainer, "WordLevel": WordLevelTrainer, "WordPiece": WordPieceTrainer, } VOCAB_FILES_NAMES = {"tokenizer_file": TOKENIZER_FILE, "vocab_file": TIKTOKEN_VOCAB_FILE} @add_end_docstrings(INIT_TOKENIZER_DOCSTRING) class TokenizersBackend(PreTrainedTokenizerBase): """ Base class for all fast tokenizers (wrapping HuggingFace tokenizers library). Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`]. Handles all the shared methods for tokenization and special tokens, as well as methods for downloading/caching/loading pretrained tokenizers, as well as adding tokens to the vocabulary. This class also contains the added tokens in a unified way on top of all tokenizers so we don't have to handle the specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...). """ vocab_files_names = VOCAB_FILES_NAMES model = None _tokenizer = None @classmethod def convert_to_native_format(cls, trust_remote_code=False, **kwargs): """s Build a `tokenizers.Tokenizer` backend from the available serialization files (tokenizer.json, sentencepiece models, tekken.json, vocab/merges). """ # Preserve kwargs for possible downstream use local_kwargs = dict(kwargs) fast_tokenizer_file = local_kwargs.pop("tokenizer_file", None) if ( fast_tokenizer_file is not None and os.path.isfile(fast_tokenizer_file) and (cls is TokenizersBackend or "__init__" not in cls.__dict__ or trust_remote_code) ): local_kwargs["tokenizer_object"] = TokenizerFast.from_file(fast_tokenizer_file) return local_kwargs elif fast_tokenizer_file is not None and os.path.isfile(fast_tokenizer_file): # we extract vocab / merges from the tokenizer file to pass them to __init__ processor = TokenizerFast.from_file(fast_tokenizer_file).post_processor with open(fast_tokenizer_file, encoding="utf-8") as tokenizer_handle: tokenizer_json = json.load(tokenizer_handle) vocab = tokenizer_json.get("model", {}).get("vocab", None) if cls.model is None: if isinstance(vocab, list): vocab = list(map(tuple, vocab)) # TODO just for now elif cls.model.__name__ == "Unigram": vocab = list(map(tuple, vocab)) elif cls.model.__name__ == "WordLevel": vocab = {token: i for i, token in enumerate(vocab)} elif cls.model.__name__ == "BPE" or cls.model.__name__ == "WordPiece": if isinstance(vocab, list): vocab = {token[0] if isinstance(token, list) else token: i for i, token in enumerate(vocab)} local_kwargs["vocab"] = vocab model_type = getattr(cls, "model", None) if "merges" in tokenizer_json.get("model", {}) and (model_type and model_type.__name__ == "BPE"): merges = tokenizer_json["model"]["merges"] merges = [tuple(merge.split(" ")) if isinstance(merge, str) else tuple(merge) for merge in merges] local_kwargs["merges"] = merges if processor is not None: local_kwargs["post_processor"] = processor return local_kwargs vocab_file = local_kwargs.get("vocab_file") merges_file = local_kwargs.get("merges_file") vocab = local_kwargs.get("vocab") merges = local_kwargs.get("merges") # Tekken converter (Mistral) if isinstance(vocab_file, str) and vocab_file.endswith("tekken.json") and os.path.isfile(vocab_file): from .convert_slow_tokenizer import MistralConverter local_kwargs["vocab"], local_kwargs["merges"] = MistralConverter( vocab_file=vocab_file ).extract_vocab_merges_from_model(vocab_file) return local_kwargs # SentencePiece model (with TikToken fallback) if isinstance(vocab_file, str) and os.path.isfile(vocab_file) and vocab_file.endswith(".model"): try: from .convert_slow_tokenizer import SentencePieceExtractor local_kwargs = SentencePieceExtractor(vocab_file).extract(cls.model, **local_kwargs) try: from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS converter_class = SLOW_TO_FAST_CONVERTERS.get(cls.__name__) if converter_class is not None and hasattr(converter_class, "convert_from_spm"): local_kwargs = converter_class.convert_from_spm(**local_kwargs) except Exception as e: logger.warning( f"Could not reorder vocab using converter for {cls.__name__} due to {e}. Falling back to raw SentencePiece extraction." ) # what used to be in `convert_slow` if hasattr(cls, "convert_from_spm_model"): local_kwargs = cls.convert_from_spm_model(**local_kwargs) except Exception as e: # TODO only catch deserialization error here! logger.warning( f"Could not extract SentencePiece model from {vocab_file} using sentencepiece library due to {e}. " "Falling back to TikToken extractor." ) from .convert_slow_tokenizer import TikTokenConverter local_kwargs["vocab"], local_kwargs["merges"] = TikTokenConverter( vocab_file=vocab_file, extra_special_tokens=local_kwargs.get("extra_special_tokens") ).extract_vocab_merges_from_model(vocab_file) return local_kwargs # Fallback to standard vocab/merges files if they existed! if vocab is None and isinstance(vocab_file, str) and os.path.isfile(vocab_file): local_kwargs["vocab"] = vocab_file vocab = local_kwargs["vocab"] if merges is None and isinstance(merges_file, str) and os.path.isfile(merges_file): local_kwargs["merges"] = merges_file merges = local_kwargs["merges"] # Generate merges automatically when not provided for BPE tokenizers if merges is None and cls.model is not None and cls.model.__name__ == "BPE" and isinstance(vocab, dict): # Gather special tokens from kwargs to skip in merge generation def _iter_special_tokens(values: Iterable[Any]) -> list[str]: collected: list[str] = [] for val in values: if val is None: continue if isinstance(val, (list, tuple)): collected.extend(_iter_special_tokens(val)) else: collected.append(str(val)) return collected special_tokens_keys = [ "pad_token", "unk_token", "bos_token", "eos_token", "sep_token", "cls_token", "mask_token", "additional_special_tokens", "extra_special_tokens", ] skip_tokens: set[str] = set() for key in special_tokens_keys: if key in local_kwargs: skip_tokens.update(_iter_special_tokens([local_kwargs[key]])) merges = generate_merges(vocab, skip_tokens=skip_tokens) local_kwargs["merges"] = merges return local_kwargs def __init__(self, *args, **kwargs): tokenizer_object = kwargs.pop("tokenizer_object", None) gguf_file = kwargs.pop("gguf_file", None) fast_tokenizer_file = kwargs.pop("tokenizer_file", None) # Note: added_tokens_decoder is NOT popped - it's passed to super().__init__() for processing added_tokens_decoder = kwargs.get("added_tokens_decoder", {}) # Store add_prefix_space before super().__init__() to ensure it's not overridden add_prefix_space = kwargs.get("add_prefix_space", False) vocab_file = kwargs.get("vocab_file") fast_tokenizer = None if tokenizer_object is not None: fast_tokenizer = copy.deepcopy(tokenizer_object) elif fast_tokenizer_file is not None and os.path.isfile(fast_tokenizer_file): # We have a serialization from tokenizers which let us directly build the backend fast_tokenizer = TokenizerFast.from_file(fast_tokenizer_file) elif gguf_file is not None: # We need to convert a slow tokenizer to build the backend gguf_param = load_gguf_checkpoint(kwargs.get("vocab_file")) architecture = gguf_param["config"]["model_type"] tokenizer_dict = gguf_param["tokenizer"] tokenizer_config = gguf_param["tokenizer_config"] fast_tokenizer, additional_kwargs = convert_gguf_tokenizer(architecture, tokenizer_dict) kwargs.update(tokenizer_config) if len(additional_kwargs) > 0: kwargs.update(additional_kwargs) elif self._tokenizer is None: raise ValueError( "Couldn't instantiate the backend tokenizer from one of: \n" "(1) a `tokenizers` library serialization file, \n" "(2) a slow tokenizer instance to convert or \n" "(3) an equivalent slow tokenizer class to instantiate and convert. \n" "You need to have sentencepiece or tiktoken installed to convert a slow tokenizer to a fast one." ) if fast_tokenizer is not None: self._tokenizer = fast_tokenizer if self._tokenizer is None: raise ValueError("The backend tokenizer is not correctly initialized.") _truncation = self._tokenizer.truncation if _truncation is not None: self._tokenizer.enable_truncation(**_truncation) kwargs.setdefault("max_length", _truncation["max_length"]) kwargs.setdefault("truncation_side", _truncation["direction"]) kwargs.setdefault("stride", _truncation["stride"]) kwargs.setdefault("truncation_strategy", _truncation["strategy"]) else: self._tokenizer.no_truncation() _padding = self._tokenizer.padding if _padding is not None: self._tokenizer.enable_padding(**_padding) kwargs.setdefault("pad_token", _padding["pad_token"]) kwargs.setdefault("pad_token_type_id", _padding["pad_type_id"]) kwargs.setdefault("padding_side", _padding["direction"]) kwargs.setdefault("max_length", _padding["length"]) kwargs.setdefault("pad_to_multiple_of", _padding["pad_to_multiple_of"]) # Set backend to "tokenizers" if not already set if "backend" not in kwargs: kwargs["backend"] = "tokenizers" explicit_bos_eos_in_kwargs = "add_bos_token" in kwargs or "add_eos_token" in kwargs self._add_bos_token = kwargs.get("add_bos_token", False) self._add_eos_token = kwargs.get("add_eos_token", False) if post_processor := kwargs.pop("post_processor", None): # most reliable way to get the post-processor self._tokenizer.post_processor = post_processor self._should_update_post_processor = explicit_bos_eos_in_kwargs or self._tokenizer.post_processor is None # We call this after having initialized the backend tokenizer because we update it. super().__init__(**kwargs) if vocab_file is not None: self.vocab_file = vocab_file # Ensure add_prefix_space is set correctly after parent init self.add_prefix_space = add_prefix_space self._tokenizer.encode_special_tokens = self.split_special_tokens added_tokens_decoder_hash = {hash(repr(token)) for token in self.added_tokens_decoder} tokens_to_add = [ token for index, token in sorted(added_tokens_decoder.items(), key=lambda x: x[0]) if hash(repr(token)) not in added_tokens_decoder_hash ] encoder = list(self.added_tokens_encoder.keys()) + [str(token) for token in tokens_to_add] # if some of the special tokens are not already in the tokenizer, add them # V5: Check both named special tokens and extra special tokens # Iterate over _special_tokens_map to preserve AddedToken properties (lstrip, rstrip, etc.) for special_token_value in self._special_tokens_map.values(): if special_token_value is None: continue if str(special_token_value) not in encoder and special_token_value not in tokens_to_add: tokens_to_add.append(special_token_value) # Also check extra special tokens for token in self._extra_special_tokens: if str(token) not in encoder and token not in tokens_to_add: tokens_to_add.append(token) if len(tokens_to_add) > 0: tokens = [] all_named_tokens = [str(t) for t in self._special_tokens_map.values() if t] for token in tokens_to_add: if isinstance(token, str): # Convert string to AddedToken, assuming it's special token = AddedToken(token, special=True) elif isinstance(token, AddedToken): # Ensure the special flag is set correctly for special tokens if not token.special and str(token) in all_named_tokens: token.special = True tokens.append(token) if tokens: # These tokens are from the special tokens map self.add_tokens(tokens) try: vocab_size = self._tokenizer.get_vocab_size() except NotImplementedError: vocab_size = 0 # Optionally patches mistral tokenizers with wrong regex if vocab_size > 100000 and getattr(self._tokenizer, "pre_tokenizer", None) is not None: kwargs.pop("tokenizer", None) self._tokenizer = self._patch_mistral_regex( self._tokenizer, self.init_kwargs.get("name_or_path", None), init_kwargs=self.init_kwargs, fix_mistral_regex=kwargs.get("fix_mistral_regex"), **kwargs, ) self._should_update_post_processor = ( self._should_update_post_processor or self._tokenizer.post_processor is None ) if self._should_update_post_processor: self.update_post_processor() @property def is_fast(self) -> bool: return True @property def can_save_slow_tokenizer(self) -> bool: """ `bool`: Whether or not the slow tokenizer can be saved. For a sentencepiece based slow tokenizer, this can only be `True` if the original `"sentencepiece.model"` was not deleted. """ if "vocab_file" in self.vocab_files_names and self.vocab_files_names["vocab_file"].endswith(".model"): if hasattr(self, "vocab_file") and self.vocab_file: # If the vocab file is a sentencepiece model, we can save it return os.path.isfile(self.vocab_file) return False else: return True def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]: if not os.path.isdir(save_directory): logger.error(f"Vocabulary path ({save_directory}) should be a directory") return out_vocab_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): copyfile(self.vocab_file, out_vocab_file) return (out_vocab_file,) def update_post_processor(self): """ Updates the underlying post processor with the current `bos_token` and `eos_token`. """ bos = self.bos_token bos_token_id = self.bos_token_id if bos is None and self.add_bos_token: raise ValueError("add_bos_token = True but bos_token = None") eos = self.eos_token eos_token_id = self.eos_token_id # If eos_token is None and add_eos_token is True, silently disable add_eos_token # This allows tokenizers to set add_eos_token even if eos_token is not configured if eos is None and self.add_eos_token: self.add_eos_token = False return single = f"{(bos + ':0 ') if self.add_bos_token else ''}$A:0{(' ' + eos + ':0') if self.add_eos_token else ''}" pair = f"{single}{(' ' + bos + ':1') if self.add_bos_token else ''} $B:1{(' ' + eos + ':1') if self.add_eos_token else ''}" special_tokens = [] if self.add_bos_token: special_tokens.append((bos, bos_token_id)) if self.add_eos_token: special_tokens.append((eos, eos_token_id)) self._tokenizer.post_processor = processors.TemplateProcessing( single=single, pair=pair, special_tokens=special_tokens ) @property def add_eos_token(self): return getattr(self, "_add_eos_token", False) @property def add_bos_token(self): return getattr(self, "_add_bos_token", False) @add_eos_token.setter def add_eos_token(self, value): object.__setattr__(self, "_add_eos_token", value) self.update_post_processor() @add_bos_token.setter def add_bos_token(self, value): object.__setattr__(self, "_add_bos_token", value) self.update_post_processor() def _post_init(self): """ Post-initialization hook that runs after the tokenizer is fully set up. This is called by from_pretrained() after loading the tokenizer, which allows us to add any special tokens that may have been passed as AddedToken objects. Child classes should call super()._post_init() if they override this method. """ tokens_to_add = [] # V5: Check named special tokens for token_value in self._special_tokens_map.values(): if token_value is None: continue if isinstance(token_value, AddedToken): tokens_to_add.append(token_value) elif isinstance(token_value, str): tokens_to_add.append(AddedToken(token_value, special=True, normalized=False)) # V5: Check extra special tokens for token in self._extra_special_tokens: if isinstance(token, AddedToken): tokens_to_add.append(token) elif isinstance(token, str): tokens_to_add.append(AddedToken(token, special=True, normalized=False)) if tokens_to_add: # Ensure special tokens are added as such to the backend self.add_tokens(tokens_to_add, special_tokens=True) if getattr(self, "_should_update_post_processor", True) or self._tokenizer.post_processor is None: self.update_post_processor() @property def vocab_size(self) -> int: """ `int`: Size of the base vocabulary (without the added tokens). """ return self._tokenizer.get_vocab_size(with_added_tokens=False) def get_vocab(self) -> dict[str, int]: return self._tokenizer.get_vocab(with_added_tokens=True) @property def vocab(self) -> dict[str, int]: return self.get_vocab() @property def added_tokens_encoder(self) -> dict[str, int]: """ Returns the sorted mapping from string to index. The added tokens encoder is cached for performance optimisation in `self._added_tokens_encoder` for the slow tokenizers. """ return {k.content: v for v, k in sorted(self.added_tokens_decoder.items(), key=lambda item: item[0])} @property def added_tokens_decoder(self) -> dict[int, AddedToken]: """ Returns the added tokens in the vocabulary as a dictionary of index to AddedToken. Returns: `dict[str, int]`: The added tokens. """ return self._tokenizer.get_added_tokens_decoder() def get_added_vocab(self) -> dict[str, int]: """ Returns the added tokens in the vocabulary as a dictionary of token to index. Returns: `dict[str, int]`: The added tokens. """ return {k.content: v for v, k in sorted(self.added_tokens_decoder.items(), key=lambda item: item[0])} def __bool__(self) -> bool: """ Returns True, to avoid expensive `assert tokenizer` gotchas. """ return True def __len__(self) -> int: """ Size of the full vocabulary with the added tokens. """ return self._tokenizer.get_vocab_size(with_added_tokens=True) @property def backend_tokenizer(self) -> TokenizerFast: """ `tokenizers.implementations.BaseTokenizer`: The Rust tokenizer used as a backend. """ return self._tokenizer @property def decoder(self) -> DecoderFast: """ `tokenizers.decoders.Decoder`: The Rust decoder for this tokenizer. """ return self._tokenizer.decoder def _convert_encoding( self, encoding: EncodingFast, return_token_type_ids: bool | None = None, return_attention_mask: bool | None = None, return_overflowing_tokens: bool = False, return_special_tokens_mask: bool = False, return_offsets_mapping: bool = False, return_length: bool = False, verbose: bool = True, ) -> tuple[dict[str, Any], list[EncodingFast]]: """ Convert the encoding representation (from low-level HuggingFace tokenizer output) to a python Dict and a list of encodings, take care of building a batch from overflowing tokens. Overflowing tokens are converted to additional examples (like batches) so the output values of the dict are lists (overflows) of lists (tokens). Output shape: (overflows, sequence length) """ if return_token_type_ids is None: return_token_type_ids = "token_type_ids" in self.model_input_names if return_attention_mask is None: return_attention_mask = "attention_mask" in self.model_input_names if return_overflowing_tokens and encoding.overflowing is not None: encodings = [encoding] + encoding.overflowing else: encodings = [encoding] encoding_dict = defaultdict(list) for e in encodings: encoding_dict["input_ids"].append(e.ids) if return_token_type_ids: encoding_dict["token_type_ids"].append(e.type_ids) if return_attention_mask: encoding_dict["attention_mask"].append(e.attention_mask) if return_special_tokens_mask: encoding_dict["special_tokens_mask"].append(e.special_tokens_mask) if return_offsets_mapping: encoding_dict["offset_mapping"].append(e.offsets) if return_length: encoding_dict["length"].append(len(e.ids)) return encoding_dict, encodings def _convert_token_to_id_with_added_voc(self, token: str) -> int: index = self._tokenizer.token_to_id(token) if index is None: return self.unk_token_id return index def _convert_id_to_token(self, index: int) -> str | None: return self._tokenizer.id_to_token(int(index)) def _add_tokens(self, new_tokens: list[str | AddedToken], special_tokens=False) -> int: if special_tokens: return self._tokenizer.add_special_tokens(new_tokens) return self._tokenizer.add_tokens(new_tokens) def num_special_tokens_to_add(self, pair: bool = False) -> int: """ Returns the number of added tokens when encoding a sequence with special tokens. <Tip> This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put this inside your training loop. </Tip> Args: pair (`bool`, *optional*, defaults to `False`): Whether the number of added tokens should be computed in the case of a sequence pair or a single sequence. Returns: `int`: Number of special tokens added to sequences. """ return self._tokenizer.num_special_tokens_to_add(pair) def convert_ids_to_tokens(self, ids: int | list[int], skip_special_tokens: bool = False) -> str | list[str]: """ Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and added tokens. Args: ids (`int` or `list[int]`): The token id (or token ids) to convert to tokens. skip_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not to remove special tokens in the decoding. Returns: `str` or `list[str]`: The decoded token(s). """ if isinstance(ids, int): return self._tokenizer.id_to_token(ids) tokens = [] # self.all_special_ids is an @property which may be slow, so only compute it once before the loop ids_to_skip = set(self.all_special_ids) if skip_special_tokens else set() for index in ids: index = int(index) if index in ids_to_skip: continue tokens.append(self._tokenizer.id_to_token(index)) return tokens def tokenize(self, text: str, pair: str | None = None, add_special_tokens: bool = False, **kwargs) -> list[str]: return self._encode_plus(text=text, text_pair=pair, add_special_tokens=add_special_tokens, **kwargs).tokens() def set_truncation_and_padding( self, padding_strategy: PaddingStrategy, truncation_strategy: TruncationStrategy, max_length: int, stride: int, pad_to_multiple_of: int | None, padding_side: str | None, ): """ Define the truncation and the padding strategies for fast tokenizers (provided by HuggingFace tokenizers library) and restore the tokenizer settings afterwards. The provided tokenizer has no padding / truncation strategy before the managed section. If your tokenizer set a padding / truncation strategy before, then it will be reset to no padding / truncation when exiting the managed section. Args: padding_strategy ([`~utils.PaddingStrategy`]): The kind of padding that will be applied to the input truncation_strategy ([`~tokenization_utils_base.TruncationStrategy`]): The kind of truncation that will be applied to the input max_length (`int`): The maximum size of a sequence. stride (`int`): The stride to use when handling overflow. pad_to_multiple_of (`int`, *optional*): If set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta). padding_side (`str`, *optional*): The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name. """ _truncation = self._tokenizer.truncation _padding = self._tokenizer.padding # Set truncation and padding on the backend tokenizer if truncation_strategy == TruncationStrategy.DO_NOT_TRUNCATE: if _truncation is not None: self._tokenizer.no_truncation() else: target = { "max_length": max_length, "stride": stride, "strategy": truncation_strategy.value, "direction": self.truncation_side, } # _truncation might contain more keys that the target `transformers` # supports. Use only the target keys to trigger `enable_truncation`. # This should enable this code to works on various `tokenizers` # targets. if _truncation is None: current = None else: current = {k: _truncation.get(k, None) for k in target} if current != target: self._tokenizer.enable_truncation(**target) if padding_strategy == PaddingStrategy.DO_NOT_PAD: if _padding is not None: self._tokenizer.no_padding() else: length = max_length if padding_strategy == PaddingStrategy.MAX_LENGTH else None target = { "length": length, "direction": padding_side if padding_side is not None else self.padding_side, "pad_id": self.pad_token_id, "pad_token": self.pad_token, "pad_type_id": self.pad_token_type_id, "pad_to_multiple_of": pad_to_multiple_of, } if _padding != target: self._tokenizer.enable_padding(**target) def _encode_plus( self, text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]], text_pair: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] = None, add_special_tokens: bool = True, padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE, max_length: int | None = None,
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
true
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/loss/loss_utils.py
src/transformers/loss/loss_utils.py
# Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch import torch.nn as nn from torch.nn import BCEWithLogitsLoss, MSELoss from .loss_d_fine import DFineForObjectDetectionLoss from .loss_deformable_detr import DeformableDetrForObjectDetectionLoss, DeformableDetrForSegmentationLoss from .loss_for_object_detection import ForObjectDetectionLoss, ForSegmentationLoss from .loss_grounding_dino import GroundingDinoForObjectDetectionLoss from .loss_rt_detr import RTDetrForObjectDetectionLoss def fixed_cross_entropy( source: torch.Tensor, target: torch.Tensor, num_items_in_batch: torch.Tensor | None = None, ignore_index: int = -100, **kwargs, ) -> torch.Tensor: reduction = "sum" if num_items_in_batch is not None else "mean" loss = nn.functional.cross_entropy(source, target, ignore_index=ignore_index, reduction=reduction) if reduction == "sum": # just in case users pass an int for num_items_in_batch, which could be the case for custom trainer if torch.is_tensor(num_items_in_batch): num_items_in_batch = num_items_in_batch.to(loss.device) loss = loss / num_items_in_batch return loss def ForCausalLMLoss( logits, labels, vocab_size: int, num_items_in_batch: torch.Tensor | None = None, ignore_index: int = -100, shift_labels: torch.Tensor | None = None, **kwargs, ) -> torch.Tensor: # Upcast to float if we need to compute the loss to avoid potential precision issues logits = logits.float() if shift_labels is None: # Shift so that tokens < n predict n labels = nn.functional.pad(labels, (0, 1), value=ignore_index) shift_labels = labels[..., 1:].contiguous() # Flatten the tokens logits = logits.view(-1, vocab_size) shift_labels = shift_labels.view(-1) shift_labels = shift_labels.to(logits.device) loss = fixed_cross_entropy(logits, shift_labels, num_items_in_batch, ignore_index, **kwargs) return loss def ForMaskedLMLoss( logits: torch.Tensor, labels: torch.Tensor, vocab_size: int, num_items_in_batch: torch.Tensor | None = None, ignore_index: int = -100, **kwargs, ): # Upcast to float if we need to compute the loss to avoid potential precision issues logits = logits.float() # Flatten the tokens logits = logits.view(-1, vocab_size) labels = labels.view(-1) labels = labels.to(logits.device) loss = fixed_cross_entropy(logits, labels, num_items_in_batch, ignore_index, **kwargs) return loss def ForSequenceClassificationLoss(labels: torch.Tensor, pooled_logits: torch.Tensor, config, **kwargs) -> torch.Tensor: num_labels = config.num_labels if config.problem_type is None: if num_labels == 1: config.problem_type = "regression" elif num_labels > 1 and (labels.dtype in (torch.long, torch.int)): config.problem_type = "single_label_classification" else: config.problem_type = "multi_label_classification" labels = labels.to(pooled_logits.device) if config.problem_type == "regression": loss_fct = MSELoss() if num_labels == 1: return loss_fct(pooled_logits.squeeze(), labels.squeeze()) else: return loss_fct(pooled_logits, labels) if config.problem_type == "single_label_classification": return fixed_cross_entropy(pooled_logits.view(-1, num_labels), labels.view(-1), **kwargs) if config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() return loss_fct(pooled_logits, labels) raise RuntimeError(f"Invalid problem type: {config.problem_type}") def ForQuestionAnsweringLoss(start_logits, end_logits, start_positions, end_positions, **kwargs): total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1).to(start_logits.device) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1).to(end_logits.device) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions = start_positions.clamp(0, ignored_index) end_positions = end_positions.clamp(0, ignored_index) start_loss = fixed_cross_entropy(start_logits, start_positions, ignore_index=ignored_index, **kwargs) end_loss = fixed_cross_entropy(end_logits, end_positions, ignore_index=ignored_index, **kwargs) total_loss = (start_loss + end_loss) / 2 return total_loss def ForTokenClassification(logits: torch.Tensor, labels, config, **kwargs): # Upcast to float if we need to compute the loss to avoid potential precision issues logits = logits.view(-1, config.num_labels) labels = labels.view(-1).to(logits.device) logits = logits.float() # Flatten the tokens return fixed_cross_entropy(logits, labels, **kwargs) LOSS_MAPPING = { "ForCausalLM": ForCausalLMLoss, "ForMaskedLM": ForMaskedLMLoss, "ForQuestionAnswering": ForQuestionAnsweringLoss, "ForSequenceClassification": ForSequenceClassificationLoss, "ForImageClassification": ForSequenceClassificationLoss, "ForVideoClassification": ForSequenceClassificationLoss, "ForAudioClassification": ForSequenceClassificationLoss, "ForTokenClassification": ForTokenClassification, "ForSegmentation": ForSegmentationLoss, "ForObjectDetection": ForObjectDetectionLoss, "ForConditionalGeneration": ForCausalLMLoss, "DeformableDetrForObjectDetection": DeformableDetrForObjectDetectionLoss, "ConditionalDetrForObjectDetection": DeformableDetrForObjectDetectionLoss, "DabDetrForObjectDetection": DeformableDetrForObjectDetectionLoss, "GroundingDinoForObjectDetection": GroundingDinoForObjectDetectionLoss, "MMGroundingDinoForObjectDetection": GroundingDinoForObjectDetectionLoss, "ConditionalDetrForSegmentation": DeformableDetrForSegmentationLoss, "RTDetrForObjectDetection": RTDetrForObjectDetectionLoss, "RTDetrV2ForObjectDetection": RTDetrForObjectDetectionLoss, "DFineForObjectDetection": DFineForObjectDetectionLoss, "CsmForConditionalGeneration": ForCausalLMLoss, }
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/loss/loss_grounding_dino.py
src/transformers/loss/loss_grounding_dino.py
# Copyright 2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch import torch.nn as nn from ..image_transforms import center_to_corners_format from ..utils import is_scipy_available from .loss_for_object_detection import HungarianMatcher, ImageLoss, _set_aux_loss, generalized_box_iou if is_scipy_available(): from scipy.optimize import linear_sum_assignment # Similar to the one used in `DeformableDetr` but we reduce with sum and normalize by num_boxes # instead of mean. def sigmoid_focal_loss( inputs: torch.Tensor, targets: torch.Tensor, num_boxes: int, alpha: float = 0.25, gamma: float = 2, ): """ Loss used in RetinaNet for dense detection: https://huggingface.co/papers/1708.02002. Args: inputs (`torch.FloatTensor` of arbitrary shape): The predictions for each example. targets (`torch.FloatTensor` with the same shape as `inputs`) A tensor storing the binary classification label for each element in the `inputs` (0 for the negative class and 1 for the positive class). num_boxes (`int`): The total number of boxes in the batch. alpha (`float`, *optional*, defaults to 0.25): Optional weighting factor in the range (0,1) to balance positive vs. negative examples. gamma (`int`, *optional*, defaults to 2): Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples. Returns: Loss tensor """ prob = inputs.sigmoid() ce_loss = nn.functional.binary_cross_entropy_with_logits(inputs, targets, reduction="none") # add modulating factor p_t = prob * targets + (1 - prob) * (1 - targets) loss = ce_loss * ((1 - p_t) ** gamma) if alpha >= 0: alpha_t = alpha * targets + (1 - alpha) * (1 - targets) loss = alpha_t * loss return loss.sum() / num_boxes class GroundingDinoHungarianMatcher(HungarianMatcher): @torch.no_grad() def forward(self, outputs, targets): """ Args: outputs (`dict`): A dictionary that contains at least these entries: * "logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits * "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates. * "label_maps": Tuple of tensors of dim [num_classes, hidden_dim]. targets (`list[dict]`): A list of targets (len(targets) = batch_size), where each target is a dict containing: * "class_labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth objects in the target) containing the class labels * "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates. Returns: `list[Tuple]`: A list of size `batch_size`, containing tuples of (index_i, index_j) where: - index_i is the indices of the selected predictions (in order) - index_j is the indices of the corresponding selected targets (in order) For each batch element, it holds: len(index_i) = len(index_j) = min(num_queries, num_target_boxes) """ batch_size, num_queries = outputs["logits"].shape[:2] # We flatten to compute the cost matrices in a batch out_prob = outputs["logits"].flatten(0, 1).sigmoid() # [batch_size * num_queries, hidden_dim] out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4] label_maps = outputs["label_maps"] # First take the label map for each class in each batch and then concatenate them label_maps = torch.cat([label_map[target["class_labels"]] for label_map, target in zip(label_maps, targets)]) # Normalize label maps based on number of tokens per class label_maps = label_maps / label_maps.sum(dim=-1, keepdim=True) # Also concat the target labels and boxes target_bbox = torch.cat([v["boxes"] for v in targets]) # Compute the classification cost. alpha = 0.25 gamma = 2.0 neg_cost_class = (1 - alpha) * (out_prob**gamma) * (-(1 - out_prob + 1e-8).log()) pos_cost_class = alpha * ((1 - out_prob) ** gamma) * (-(out_prob + 1e-8).log()) # Compute the classification cost by taking pos and neg cost in the appropriate index class_cost = (pos_cost_class - neg_cost_class) @ label_maps.t() # Compute the L1 cost between boxes bbox_cost = torch.cdist(out_bbox, target_bbox, p=1) # Compute the giou cost between boxes giou_cost = -generalized_box_iou(center_to_corners_format(out_bbox), center_to_corners_format(target_bbox)) # Final cost matrix cost_matrix = self.bbox_cost * bbox_cost + self.class_cost * class_cost + self.giou_cost * giou_cost cost_matrix = cost_matrix.view(batch_size, num_queries, -1).cpu() sizes = [len(v["boxes"]) for v in targets] indices = [linear_sum_assignment(c[i]) for i, c in enumerate(cost_matrix.split(sizes, -1))] return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices] class GroundingDinoImageLoss(ImageLoss): """ This class computes the losses for `GroundingDinoForObjectDetection`. The process happens in two steps: 1) we compute hungarian assignment between ground truth boxes and the outputs of the model 2) we supervise each pair of matched ground-truth / prediction (supervise class and box). Args: matcher (`GroundingDinoHungarianMatcher`): Module able to compute a matching between targets and proposals. focal_alpha (`float`): Alpha parameter in focal loss. losses (`list[str]`): List of all the losses to be applied. See `get_loss` for a list of all available losses. """ def __init__(self, matcher, focal_alpha, losses): nn.Module.__init__(self) self.matcher = matcher self.focal_alpha = focal_alpha self.losses = losses def _get_target_classes_one_hot(self, outputs, targets, indices): """ Create one_hot based on the matching indices """ logits = outputs["logits"] # Add offsets to class_labels to select the correct label map class_labels = torch.cat( [ target["class_labels"][J] + len(outputs["label_maps"][i]) if i > 0 else target["class_labels"][J] for i, (target, (_, J)) in enumerate(zip(targets, indices)) ] ) label_maps = torch.cat(outputs["label_maps"], dim=0) idx = self._get_source_permutation_idx(indices) target_classes_onehot = torch.zeros_like(logits, device=logits.device, dtype=torch.long) target_classes_onehot[idx] = label_maps[class_labels].to(torch.long) return target_classes_onehot def loss_labels(self, outputs, targets, indices, num_boxes): """ Classification loss (Binary focal loss) targets dicts must contain the key "class_labels" containing a tensor of dim [nb_target_boxes] """ if "logits" not in outputs: raise KeyError("No logits were found in the outputs") if "text_mask" not in outputs: raise KeyError("No text_mask were found in the outputs") target_classes_onehot = self._get_target_classes_one_hot(outputs, targets, indices) source_logits = outputs["logits"] text_mask = outputs["text_mask"] # Select only valid logits source_logits = torch.masked_select(source_logits, text_mask) target_classes_onehot = torch.masked_select(target_classes_onehot, text_mask) target_classes_onehot = target_classes_onehot.float() loss_ce = sigmoid_focal_loss( inputs=source_logits, targets=target_classes_onehot, num_boxes=num_boxes, alpha=self.focal_alpha, gamma=2, ) losses = {"loss_ce": loss_ce} return losses def GroundingDinoForObjectDetectionLoss( logits, labels, device, pred_boxes, config, label_maps, text_mask, outputs_class=None, outputs_coord=None, encoder_logits=None, encoder_pred_boxes=None, ): # First: create the matcher matcher = GroundingDinoHungarianMatcher( class_cost=config.class_cost, bbox_cost=config.bbox_cost, giou_cost=config.giou_cost ) # Second: create the criterion losses = ["labels", "boxes", "cardinality"] criterion = GroundingDinoImageLoss( matcher=matcher, focal_alpha=config.focal_alpha, losses=losses, ) criterion.to(device) # Third: compute the losses, based on outputs and labels outputs_loss = {} outputs_loss["logits"] = logits outputs_loss["pred_boxes"] = pred_boxes outputs_loss["label_maps"] = label_maps outputs_loss["text_mask"] = text_mask auxiliary_outputs = None if config.auxiliary_loss: auxiliary_outputs = _set_aux_loss(outputs_class, outputs_coord) for aux_output in auxiliary_outputs: aux_output["label_maps"] = label_maps aux_output["text_mask"] = text_mask outputs_loss["auxiliary_outputs"] = auxiliary_outputs loss_dict = criterion(outputs_loss, labels) if config.two_stage: encoder_outputs_loss = { "logits": encoder_logits, "pred_boxes": encoder_pred_boxes, "label_maps": label_maps, "text_mask": text_mask, } encoder_loss_dict = criterion(encoder_outputs_loss, labels) encoder_loss_dict = {k + "_enc": v for k, v in encoder_loss_dict.items()} loss_dict.update(encoder_loss_dict) # Fourth: compute total loss, as a weighted sum of the various losses weight_dict = { "loss_ce": 2.0, "loss_bbox": config.bbox_loss_coefficient, "loss_giou": config.giou_loss_coefficient, } if config.two_stage: enc_weight_dict = {k + "_enc": v for k, v in weight_dict.items()} weight_dict.update(enc_weight_dict) if config.auxiliary_loss: aux_weight_dict = {} for i in range(config.decoder_layers - 1): aux_weight_dict.update({k + f"_{i}": v for k, v in weight_dict.items()}) weight_dict.update(aux_weight_dict) loss = sum(loss_dict[k] * weight_dict[k] for k in loss_dict if k in weight_dict) return loss, loss_dict, auxiliary_outputs
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false
huggingface/transformers
https://github.com/huggingface/transformers/blob/a7f29523361b2cc12e51c1f5133d95f122f6f45c/src/transformers/loss/loss_rt_detr.py
src/transformers/loss/loss_rt_detr.py
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch import torch.nn as nn import torch.nn.functional as F from ..utils import is_scipy_available, is_vision_available, requires_backends from .loss_for_object_detection import ( box_iou, dice_loss, generalized_box_iou, nested_tensor_from_tensor_list, sigmoid_focal_loss, ) if is_scipy_available(): from scipy.optimize import linear_sum_assignment if is_vision_available(): from transformers.image_transforms import center_to_corners_format # different for RT-DETR: not slicing the last element like in DETR one def _set_aux_loss(outputs_class, outputs_coord): return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class, outputs_coord)] class RTDetrHungarianMatcher(nn.Module): """This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are un-matched (and thus treated as non-objects). Args: config: RTDetrConfig """ def __init__(self, config): super().__init__() requires_backends(self, ["scipy"]) self.class_cost = config.matcher_class_cost self.bbox_cost = config.matcher_bbox_cost self.giou_cost = config.matcher_giou_cost self.use_focal_loss = config.use_focal_loss self.alpha = config.matcher_alpha self.gamma = config.matcher_gamma if self.class_cost == self.bbox_cost == self.giou_cost == 0: raise ValueError("All costs of the Matcher can't be 0") @torch.no_grad() def forward(self, outputs, targets): """Performs the matching Params: outputs: This is a dict that contains at least these entries: "logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing: "class_labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth objects in the target) containing the class labels "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates Returns: A list of size batch_size, containing tuples of (index_i, index_j) where: - index_i is the indices of the selected predictions (in order) - index_j is the indices of the corresponding selected targets (in order) For each batch element, it holds: len(index_i) = len(index_j) = min(num_queries, num_target_boxes) """ batch_size, num_queries = outputs["logits"].shape[:2] # We flatten to compute the cost matrices in a batch out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4] # Also concat the target labels and boxes target_ids = torch.cat([v["class_labels"] for v in targets]) target_bbox = torch.cat([v["boxes"] for v in targets]) # Compute the classification cost. Contrary to the loss, we don't use the NLL, # but approximate it in 1 - proba[target class]. # The 1 is a constant that doesn't change the matching, it can be omitted. if self.use_focal_loss: out_prob = F.sigmoid(outputs["logits"].flatten(0, 1)) out_prob = out_prob[:, target_ids] neg_cost_class = (1 - self.alpha) * (out_prob**self.gamma) * (-(1 - out_prob + 1e-8).log()) pos_cost_class = self.alpha * ((1 - out_prob) ** self.gamma) * (-(out_prob + 1e-8).log()) class_cost = pos_cost_class - neg_cost_class else: out_prob = outputs["logits"].flatten(0, 1).softmax(-1) # [batch_size * num_queries, num_classes] class_cost = -out_prob[:, target_ids] # Compute the L1 cost between boxes bbox_cost = torch.cdist(out_bbox, target_bbox, p=1) # Compute the giou cost between boxes giou_cost = -generalized_box_iou(center_to_corners_format(out_bbox), center_to_corners_format(target_bbox)) # Compute the final cost matrix cost_matrix = self.bbox_cost * bbox_cost + self.class_cost * class_cost + self.giou_cost * giou_cost cost_matrix = cost_matrix.view(batch_size, num_queries, -1).cpu() sizes = [len(v["boxes"]) for v in targets] indices = [linear_sum_assignment(c[i]) for i, c in enumerate(cost_matrix.split(sizes, -1))] return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices] class RTDetrLoss(nn.Module): """ This class computes the losses for RTDetr. The process happens in two steps: 1) we compute hungarian assignment between ground truth boxes and the outputs of the model 2) we supervise each pair of matched ground-truth / prediction (supervise class and box). Args: matcher (`DetrHungarianMatcher`): Module able to compute a matching between targets and proposals. weight_dict (`Dict`): Dictionary relating each loss with its weights. These losses are configured in RTDetrConf as `weight_loss_vfl`, `weight_loss_bbox`, `weight_loss_giou` losses (`list[str]`): List of all the losses to be applied. See `get_loss` for a list of all available losses. alpha (`float`): Parameter alpha used to compute the focal loss. gamma (`float`): Parameter gamma used to compute the focal loss. eos_coef (`float`): Relative classification weight applied to the no-object category. num_classes (`int`): Number of object categories, omitting the special no-object category. """ def __init__(self, config): super().__init__() self.matcher = RTDetrHungarianMatcher(config) self.num_classes = config.num_labels self.weight_dict = { "loss_vfl": config.weight_loss_vfl, "loss_bbox": config.weight_loss_bbox, "loss_giou": config.weight_loss_giou, } self.losses = ["vfl", "boxes"] self.eos_coef = config.eos_coefficient empty_weight = torch.ones(config.num_labels + 1) empty_weight[-1] = self.eos_coef self.register_buffer("empty_weight", empty_weight) self.alpha = config.focal_loss_alpha self.gamma = config.focal_loss_gamma def loss_labels_vfl(self, outputs, targets, indices, num_boxes, log=True): if "pred_boxes" not in outputs: raise KeyError("No predicted boxes found in outputs") if "logits" not in outputs: raise KeyError("No predicted logits found in outputs") idx = self._get_source_permutation_idx(indices) src_boxes = outputs["pred_boxes"][idx] target_boxes = torch.cat([_target["boxes"][i] for _target, (_, i) in zip(targets, indices)], dim=0) ious, _ = box_iou(center_to_corners_format(src_boxes.detach()), center_to_corners_format(target_boxes)) ious = torch.diag(ious) src_logits = outputs["logits"] target_classes_original = torch.cat([_target["class_labels"][i] for _target, (_, i) in zip(targets, indices)]) target_classes = torch.full( src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device ) target_classes[idx] = target_classes_original target = F.one_hot(target_classes, num_classes=self.num_classes + 1)[..., :-1] target_score_original = torch.zeros_like(target_classes, dtype=src_logits.dtype) target_score_original[idx] = ious.to(target_score_original.dtype) target_score = target_score_original.unsqueeze(-1) * target pred_score = F.sigmoid(src_logits.detach()) weight = self.alpha * pred_score.pow(self.gamma) * (1 - target) + target_score loss = F.binary_cross_entropy_with_logits(src_logits, target_score, weight=weight, reduction="none") loss = loss.mean(1).sum() * src_logits.shape[1] / num_boxes return {"loss_vfl": loss} def loss_labels(self, outputs, targets, indices, num_boxes, log=True): """Classification loss (NLL) targets dicts must contain the key "class_labels" containing a tensor of dim [nb_target_boxes] """ if "logits" not in outputs: raise KeyError("No logits were found in the outputs") src_logits = outputs["logits"] idx = self._get_source_permutation_idx(indices) target_classes_original = torch.cat([_target["class_labels"][i] for _target, (_, i) in zip(targets, indices)]) target_classes = torch.full( src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device ) target_classes[idx] = target_classes_original loss_ce = F.cross_entropy(src_logits.transpose(1, 2), target_classes, self.class_weight) losses = {"loss_ce": loss_ce} return losses @torch.no_grad() def loss_cardinality(self, outputs, targets, indices, num_boxes): """ Compute the cardinality error, i.e. the absolute error in the number of predicted non-empty boxes. This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients. """ logits = outputs["logits"] device = logits.device target_lengths = torch.as_tensor([len(v["class_labels"]) for v in targets], device=device) # Count the number of predictions that are NOT "no-object" (which is the last class) card_pred = (logits.argmax(-1) != logits.shape[-1] - 1).sum(1) card_err = nn.functional.l1_loss(card_pred.float(), target_lengths.float()) losses = {"cardinality_error": card_err} return losses def loss_boxes(self, outputs, targets, indices, num_boxes): """ Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss. Targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]. The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size. """ if "pred_boxes" not in outputs: raise KeyError("No predicted boxes found in outputs") idx = self._get_source_permutation_idx(indices) src_boxes = outputs["pred_boxes"][idx] target_boxes = torch.cat([t["boxes"][i] for t, (_, i) in zip(targets, indices)], dim=0) losses = {} loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction="none") losses["loss_bbox"] = loss_bbox.sum() / num_boxes loss_giou = 1 - torch.diag( generalized_box_iou(center_to_corners_format(src_boxes), center_to_corners_format(target_boxes)) ) losses["loss_giou"] = loss_giou.sum() / num_boxes return losses def loss_masks(self, outputs, targets, indices, num_boxes): """ Compute the losses related to the masks: the focal loss and the dice loss. Targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]. """ if "pred_masks" not in outputs: raise KeyError("No predicted masks found in outputs") source_idx = self._get_source_permutation_idx(indices) target_idx = self._get_target_permutation_idx(indices) source_masks = outputs["pred_masks"] source_masks = source_masks[source_idx] masks = [t["masks"] for t in targets] target_masks, valid = nested_tensor_from_tensor_list(masks).decompose() target_masks = target_masks.to(source_masks) target_masks = target_masks[target_idx] # upsample predictions to the target size source_masks = nn.functional.interpolate( source_masks[:, None], size=target_masks.shape[-2:], mode="bilinear", align_corners=False ) source_masks = source_masks[:, 0].flatten(1) target_masks = target_masks.flatten(1) target_masks = target_masks.view(source_masks.shape) losses = { "loss_mask": sigmoid_focal_loss(source_masks, target_masks, num_boxes), "loss_dice": dice_loss(source_masks, target_masks, num_boxes), } return losses def loss_labels_bce(self, outputs, targets, indices, num_boxes, log=True): src_logits = outputs["logits"] idx = self._get_source_permutation_idx(indices) target_classes_original = torch.cat([_target["class_labels"][i] for _target, (_, i) in zip(targets, indices)]) target_classes = torch.full( src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device ) target_classes[idx] = target_classes_original target = F.one_hot(target_classes, num_classes=self.num_classes + 1)[..., :-1] loss = F.binary_cross_entropy_with_logits(src_logits, target * 1.0, reduction="none") loss = loss.mean(1).sum() * src_logits.shape[1] / num_boxes return {"loss_bce": loss} def _get_source_permutation_idx(self, indices): # permute predictions following indices batch_idx = torch.cat([torch.full_like(source, i) for i, (source, _) in enumerate(indices)]) source_idx = torch.cat([source for (source, _) in indices]) return batch_idx, source_idx def _get_target_permutation_idx(self, indices): # permute targets following indices batch_idx = torch.cat([torch.full_like(target, i) for i, (_, target) in enumerate(indices)]) target_idx = torch.cat([target for (_, target) in indices]) return batch_idx, target_idx def loss_labels_focal(self, outputs, targets, indices, num_boxes, log=True): if "logits" not in outputs: raise KeyError("No logits found in outputs") src_logits = outputs["logits"] idx = self._get_source_permutation_idx(indices) target_classes_original = torch.cat([_target["class_labels"][i] for _target, (_, i) in zip(targets, indices)]) target_classes = torch.full( src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device ) target_classes[idx] = target_classes_original target = F.one_hot(target_classes, num_classes=self.num_classes + 1)[..., :-1] loss = sigmoid_focal_loss(src_logits, target, self.alpha, self.gamma) loss = loss.mean(1).sum() * src_logits.shape[1] / num_boxes return {"loss_focal": loss} def get_loss(self, loss, outputs, targets, indices, num_boxes): loss_map = { "labels": self.loss_labels, "cardinality": self.loss_cardinality, "boxes": self.loss_boxes, "masks": self.loss_masks, "bce": self.loss_labels_bce, "focal": self.loss_labels_focal, "vfl": self.loss_labels_vfl, } if loss not in loss_map: raise ValueError(f"Loss {loss} not supported") return loss_map[loss](outputs, targets, indices, num_boxes) @staticmethod def get_cdn_matched_indices(dn_meta, targets): dn_positive_idx, dn_num_group = dn_meta["dn_positive_idx"], dn_meta["dn_num_group"] num_gts = [len(t["class_labels"]) for t in targets] device = targets[0]["class_labels"].device dn_match_indices = [] for i, num_gt in enumerate(num_gts): if num_gt > 0: gt_idx = torch.arange(num_gt, dtype=torch.int64, device=device) gt_idx = gt_idx.tile(dn_num_group) assert len(dn_positive_idx[i]) == len(gt_idx) dn_match_indices.append((dn_positive_idx[i], gt_idx)) else: dn_match_indices.append( ( torch.zeros(0, dtype=torch.int64, device=device), torch.zeros(0, dtype=torch.int64, device=device), ) ) return dn_match_indices def forward(self, outputs, targets): """ This performs the loss computation. Args: outputs (`dict`, *optional*): Dictionary of tensors, see the output specification of the model for the format. targets (`list[dict]`, *optional*): List of dicts, such that `len(targets) == batch_size`. The expected keys in each dict depends on the losses applied, see each loss' doc. """ outputs_without_aux = {k: v for k, v in outputs.items() if "auxiliary_outputs" not in k} # Retrieve the matching between the outputs of the last layer and the targets indices = self.matcher(outputs_without_aux, targets) # Compute the average number of target boxes across all nodes, for normalization purposes num_boxes = sum(len(t["class_labels"]) for t in targets) num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device) num_boxes = torch.clamp(num_boxes, min=1).item() # Compute all the requested losses losses = {} for loss in self.losses: l_dict = self.get_loss(loss, outputs, targets, indices, num_boxes) l_dict = {k: l_dict[k] * self.weight_dict[k] for k in l_dict if k in self.weight_dict} losses.update(l_dict) # In case of auxiliary losses, we repeat this process with the output of each intermediate layer. if "auxiliary_outputs" in outputs: for i, auxiliary_outputs in enumerate(outputs["auxiliary_outputs"]): indices = self.matcher(auxiliary_outputs, targets) for loss in self.losses: if loss == "masks": # Intermediate masks losses are too costly to compute, we ignore them. continue l_dict = self.get_loss(loss, auxiliary_outputs, targets, indices, num_boxes) l_dict = {k: l_dict[k] * self.weight_dict[k] for k in l_dict if k in self.weight_dict} l_dict = {k + f"_aux_{i}": v for k, v in l_dict.items()} losses.update(l_dict) # In case of cdn auxiliary losses. For rtdetr if "dn_auxiliary_outputs" in outputs: if "denoising_meta_values" not in outputs: raise ValueError( "The output must have the 'denoising_meta_values` key. Please, ensure that 'outputs' includes a 'denoising_meta_values' entry." ) indices = self.get_cdn_matched_indices(outputs["denoising_meta_values"], targets) num_boxes = num_boxes * outputs["denoising_meta_values"]["dn_num_group"] for i, auxiliary_outputs in enumerate(outputs["dn_auxiliary_outputs"]): # indices = self.matcher(auxiliary_outputs, targets) for loss in self.losses: if loss == "masks": # Intermediate masks losses are too costly to compute, we ignore them. continue kwargs = {} l_dict = self.get_loss(loss, auxiliary_outputs, targets, indices, num_boxes, **kwargs) l_dict = {k: l_dict[k] * self.weight_dict[k] for k in l_dict if k in self.weight_dict} l_dict = {k + f"_dn_{i}": v for k, v in l_dict.items()} losses.update(l_dict) return losses def RTDetrForObjectDetectionLoss( logits, labels, device, pred_boxes, config, outputs_class=None, outputs_coord=None, enc_topk_logits=None, enc_topk_bboxes=None, denoising_meta_values=None, **kwargs, ): criterion = RTDetrLoss(config) criterion.to(device) # Second: compute the losses, based on outputs and labels outputs_loss = {} outputs_loss["logits"] = logits outputs_loss["pred_boxes"] = pred_boxes auxiliary_outputs = None if config.auxiliary_loss: if denoising_meta_values is not None: dn_out_coord, outputs_coord = torch.split(outputs_coord, denoising_meta_values["dn_num_split"], dim=2) dn_out_class, outputs_class = torch.split(outputs_class, denoising_meta_values["dn_num_split"], dim=2) auxiliary_outputs = _set_aux_loss(outputs_class[:, :-1].transpose(0, 1), outputs_coord[:, :-1].transpose(0, 1)) outputs_loss["auxiliary_outputs"] = auxiliary_outputs outputs_loss["auxiliary_outputs"].extend(_set_aux_loss([enc_topk_logits], [enc_topk_bboxes])) if denoising_meta_values is not None: outputs_loss["dn_auxiliary_outputs"] = _set_aux_loss( dn_out_class.transpose(0, 1), dn_out_coord.transpose(0, 1) ) outputs_loss["denoising_meta_values"] = denoising_meta_values loss_dict = criterion(outputs_loss, labels) loss = sum(loss_dict.values()) return loss, loss_dict, auxiliary_outputs
python
Apache-2.0
a7f29523361b2cc12e51c1f5133d95f122f6f45c
2026-01-04T14:38:15.407064Z
false