#customtrainer
Super proud of Mike, Eric, and Jeremiah's work redesigning and creating 3 different trainers & consumables needed for BCH Neuro Bootcamp. Their hard work and dedication to our patients is evident. #IDSSim #customtrainer #awesometeam #healthcaresimulation #immersivedesignsystems #engineering
January 23, 2025 at 4:47 PM
Log losses/metrics with CustomTrainer(Trainer) class in the same frequency as Trainer, with wandb
Thanks @John6666 ! The training loop is working but then, I’ve issues in : `metrics = trainer.evaluate()`: IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed In the logs, I can see : [forward] total_loss : 1.5778188705444336 [forward] mlm_loss : 0.49145200848579407 [forward] clf_loss : 1.086366891860962 {'loss': 1.5778188705444336, 'mlm_loss': 0.49145200848579407, 'clf_loss': 1.086366891860962, 'perplexity': 1.634688138961792, 'epoch': 33.04} {'train_runtime': 1.5641, 'train_samples_per_second': 2045.918, 'train_steps_per_second': 63.935, 'train_loss': 0.021779886566766417, 'epoch': 33.64} 101it [00:01, 64.76it/s] ***** train metrics ***** epoch = 33.64 train_loss = 0.0218 train_runtime = 0:00:01.56 train_samples = 99 train_samples_per_second = 2045.918 train_steps_per_second = 63.935 [forward] total_loss : 1.7311770915985107 [forward] mlm_loss : 0.76634281873703 [forward] clf_loss : 0.9648342728614807 The `train_loss = 0.0218` and it different from `total_loss = 1.5778188705444336` for example for each step. My training arguments are : --per_device_train_batch_size 4 \ --per_device_eval_batch_size 4 \ --gradient_accumulation_steps 8 \ --eval_accumulation_steps 8 \ --do_train \ --do_eval \ --evaluation_strategy steps \ --max_steps 100 \ --save_steps 10 \ --learning_rate 0.00001 \ --logging_steps 2 \ --eval_steps 4 \
discuss.huggingface.co
August 6, 2025 at 1:20 PM
Log losses/metrics with CustomTrainer(Trainer) class in the same frequency as Trainer, with wandb
Thanks a lot for taking time to answer ! I’ve read the different interesting ressources, thanks a lot ! I’m sorry, I’m a newbie using Trainer class Why adding callback would be the cleanest method ? Would this log the `mlm_loss` and `clf_loss` at the same frequency as the train loss in Trainer ? In the Trainer class, I’ve understood that: * tr_loss : tracks the cumulative training loss at each training step. It is initialized as following: tr_loss = torch.tensor(0.0, device=args.device) * _total_loss_scalar : aims to log average training loss across `global_steps` . `self._total_loss_scalar = 0.0` * tr_loss_step : computes the loss at one training step `tr_loss_step = self.training_step(model, inputs, num_items_in_batch)` * if tr_loss_step is not a NaN value: `tr_loss = tr_loss + tr_loss_step` * else: `# if loss is nan or inf simply add the average of previous logged losses tr_loss = tr_loss + tr_loss / (1 + self.state.global_step - self._globalstep_last_logged) ` * At the end of a step, self._maybe_log_save_evaluate() is called to log `tr_loss` self._maybe_log_save_evaluate( tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval, start_time, learning_rate=learning_rate, ) In the definition of _maybe_log_save_evaluate() method : def _maybe_log_save_evaluate( self, tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval, start_time, learning_rate=None ): if self.control.should_log and self.state.global_step > self._globalstep_last_logged: if is_torch_xla_available(): xm.mark_step() logs: dict[str, float] = {} # all_gather + mean() to get average loss over all processes tr_loss_scalar = self._nested_gather(tr_loss).mean().item() # reset tr_loss to zero tr_loss -= tr_loss logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4) if grad_norm is not None: logs["grad_norm"] = grad_norm.item() if isinstance(grad_norm, torch.Tensor) else grad_norm if learning_rate is not None: logs["learning_rate"] = learning_rate else: logs["learning_rate"] = self._get_learning_rate() self._total_loss_scalar += tr_loss_scalar self._globalstep_last_logged = self.state.global_step self.store_flos() self.log(logs, start_time) metrics = None if self.control.should_evaluate: metrics = self._evaluate(trial, ignore_keys_for_eval) is_new_best_metric = self._determine_best_metric(metrics=metrics, trial=trial) if self.args.save_strategy == SaveStrategy.BEST: self.control.should_save = is_new_best_metric if self.control.should_save: self._save_checkpoint(model, trial) self.control = self.callback_handler.on_save(self.args, self.state, self.control) We can see that the logged loss is the average loss over the steps since the last logged global step: `logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)` * At the end of the training loop, train_loss : it is an average value across the global steps: > self._total_loss_scalar += tr_loss.item() > effective_global_step = max(self.state.global_step, 0.001) # Avoid ZeroDivisionError > train_loss = self._total_loss_scalar / effective_global_step Is it correct ? Should I write a training_step method inside my `CustomTrainer(Trainer)` class ?
discuss.huggingface.co
August 4, 2025 at 3:00 PM
Log losses/metrics with CustomTrainer(Trainer) class in the same frequency as Trainer, with wandb
Adding callbacks are probably the cleanest method. Implementing it in other ways may cause problems if the library version is updated and the behavior changes. from transformers import TrainerCallback class MyLogger(TrainerCallback): def __init__(self): ... def on_log(self, args, state, control, logs=None, **kwargs): ... trainer = CustomTrainer( ..., callbacks=[MyLogger()], ) Trainer log my custom metrics at training step Beginners > If you don’t use gradient accumulation, then I usually just hack by overwriting Trainer.compute_loss and tucking in one line of self.log(compute_my_metric(output) If you use gradient accumulation, one alternative is to trigger a CustomCallback per Metrics for Training Set in Trainer - #7 by Kaveri. For example, you can do one forward pass on the entire train set on_epoch_end or on_evaluate. It will be repeated work, slow and coarse. And let me know if you figured out an easy way to log custom … github.com/huggingface/transformers #### MlFlow log artefacts opened 08:33AM - 24 Mar 21 UTC closed 03:02PM - 01 May 21 UTC dmilcevski ## Environment info - `transformers` version: 4.4.2 - Platform: Darwin-20.…3.0-x86_64-i386-64bit - Python version: 3.7.4 - PyTorch version (GPU?): 1.3.1 (False) - Tensorflow version (GPU?): not installed (NA) - Using GPU in script?: No - Using distributed or parallel set-up in script?: No ### Who can help @sgugger ## Information Model I am using (Bert, XLNet ...): Bert The problem arises when using: * [x] the official example scripts: (give details below) * [ ] my own modified scripts: (give details below) The tasks I am working on is: * [x] an official GLUE/SQUaD task: NER * [ ] my own task or dataset: (give details below) ## To reproduce The bug is for the PR #8016. Steps to reproduce the behavior: 1. MlFlow installed and the following env variables exported ``` export HF_MLFLOW_LOG_ARTIFACTS=TRUE export MLFLOW_S3_ENDPOINT_URL=<custom endpont> export MLFLOW_TRACKING_URI=<custom uri> export MLFLOW_TRACKING_TOKEN=<custom token> ``` 2. Run the token classification example with the following command ``` python run_ner.py \ --model_name_or_path bert-base-uncased \ --dataset_name conll2003 \ --output_dir /tmp/test-ner \ --do_train \ --do_eval ``` ## Expected behavior When the training finishes, before the evaluation is performed, the `integrations.MLflowCallback` executes the method `on_train_end`, where if the env variable `HF_MLFLOW_LOG_ARTIFACTS` is set to `TRUE`, it logs the model artifacts to mlflow. The problem is, however, when the method `on_train_end` is called and the following line is executed: `self._ml_flow.log_artifacts(args.output_dir)`, the model is not stored on the `args.output_dir`. The model artefacts are stored once the `trainer.save_model()` is called, which is after the training ending. There is no callback in the `trainer.save_model()` that can be called from a `TrainerCallback` to save the model. There is a method `TrainierCallback.on_save()` method, that is called `trainer._maybe_log_save_evaluate()`, but even then the model is not available on the `output_dir`. Possible solutions would be to extend the `TrainierCallback` with `on_model_save()` callback method, insert the callback in the `trainer.save_model()`. Or, a workaround I have now is to change `on_train_end ` with `on_evaluate` in `integrations.MLflowCallback`, that is called after the model is saved in the example script. However, this is not the right solution since it depends on having set the `do_eval` parameter, and it is not semantically correct. stackoverflow.com #### Validation and Training Loss when using HuggingFace **nlp, huggingface-transformers, huggingface, huggingface-trainer** asked by tt40kiwi on 01:36PM - 16 Aug 23 UTC
discuss.huggingface.co
August 1, 2025 at 8:27 PM
Log losses/metrics with CustomTrainer(Trainer) class in the same frequency as Trainer, with wandb
Adding callbacks are probably the cleanest method. Implementing it in other ways may cause problems if the library version is updated and the behavior changes. from transformers import TrainerCallback class MyLogger(TrainerCallback): def __init__(self): ... def on_log(self, args, state, control, logs=None, **kwargs): ... trainer = CustomTrainer( ..., callbacks=[MyLogger()], ) Trainer log my custom metrics at training step Beginners > If you don’t use gradient accumulation, then I usually just hack by overwriting Trainer.compute_loss and tucking in one line of self.log(compute_my_metric(output) If you use gradient accumulation, one alternative is to trigger a CustomCallback per Metrics for Training Set in Trainer - #7 by Kaveri. For example, you can do one forward pass on the entire train set on_epoch_end or on_evaluate. It will be repeated work, slow and coarse. And let me know if you figured out an easy way to log custom … github.com/huggingface/transformers #### MlFlow log artefacts opened 08:33AM - 24 Mar 21 UTC closed 03:02PM - 01 May 21 UTC dmilcevski ## Environment info - `transformers` version: 4.4.2 - Platform: Darwin-20.…3.0-x86_64-i386-64bit - Python version: 3.7.4 - PyTorch version (GPU?): 1.3.1 (False) - Tensorflow version (GPU?): not installed (NA) - Using GPU in script?: No - Using distributed or parallel set-up in script?: No ### Who can help @sgugger ## Information Model I am using (Bert, XLNet ...): Bert The problem arises when using: * [x] the official example scripts: (give details below) * [ ] my own modified scripts: (give details below) The tasks I am working on is: * [x] an official GLUE/SQUaD task: NER * [ ] my own task or dataset: (give details below) ## To reproduce The bug is for the PR #8016. Steps to reproduce the behavior: 1. MlFlow installed and the following env variables exported ``` export HF_MLFLOW_LOG_ARTIFACTS=TRUE export MLFLOW_S3_ENDPOINT_URL=<custom endpont> export MLFLOW_TRACKING_URI=<custom uri> export MLFLOW_TRACKING_TOKEN=<custom token> ``` 2. Run the token classification example with the following command ``` python run_ner.py \ --model_name_or_path bert-base-uncased \ --dataset_name conll2003 \ --output_dir /tmp/test-ner \ --do_train \ --do_eval ``` ## Expected behavior When the training finishes, before the evaluation is performed, the `integrations.MLflowCallback` executes the method `on_train_end`, where if the env variable `HF_MLFLOW_LOG_ARTIFACTS` is set to `TRUE`, it logs the model artifacts to mlflow. The problem is, however, when the method `on_train_end` is called and the following line is executed: `self._ml_flow.log_artifacts(args.output_dir)`, the model is not stored on the `args.output_dir`. The model artefacts are stored once the `trainer.save_model()` is called, which is after the training ending. There is no callback in the `trainer.save_model()` that can be called from a `TrainerCallback` to save the model. There is a method `TrainierCallback.on_save()` method, that is called `trainer._maybe_log_save_evaluate()`, but even then the model is not available on the `output_dir`. Possible solutions would be to extend the `TrainierCallback` with `on_model_save()` callback method, insert the callback in the `trainer.save_model()`. Or, a workaround I have now is to change `on_train_end ` with `on_evaluate` in `integrations.MLflowCallback`, that is called after the model is saved in the example script. However, this is not the right solution since it depends on having set the `do_eval` parameter, and it is not semantically correct. stackoverflow.com #### Validation and Training Loss when using HuggingFace **nlp, huggingface-transformers, huggingface, huggingface-trainer** asked by tt40kiwi on 01:36PM - 16 Aug 23 UTC
discuss.huggingface.co
August 1, 2025 at 6:29 PM
Log losses/metrics with CustomTrainer(Trainer) class in the same frequency as Trainer, with wandb
Adding callbacks are probably the cleanest method. Implementing it in other ways may cause problems if the library version is updated and the behavior changes. from transformers import TrainerCallback class MyLogger(TrainerCallback): def __init__(self): ... def on_log(self, args, state, control, logs=None, **kwargs): ... trainer = CustomTrainer( ..., callbacks=[MyLogger()], ) Trainer log my custom metrics at training step Beginners > If you don’t use gradient accumulation, then I usually just hack by overwriting Trainer.compute_loss and tucking in one line of self.log(compute_my_metric(output) If you use gradient accumulation, one alternative is to trigger a CustomCallback per Metrics for Training Set in Trainer - #7 by Kaveri. For example, you can do one forward pass on the entire train set on_epoch_end or on_evaluate. It will be repeated work, slow and coarse. And let me know if you figured out an easy way to log custom … github.com/huggingface/transformers #### MlFlow log artefacts opened 08:33AM - 24 Mar 21 UTC closed 03:02PM - 01 May 21 UTC dmilcevski ## Environment info - `transformers` version: 4.4.2 - Platform: Darwin-20.…3.0-x86_64-i386-64bit - Python version: 3.7.4 - PyTorch version (GPU?): 1.3.1 (False) - Tensorflow version (GPU?): not installed (NA) - Using GPU in script?: No - Using distributed or parallel set-up in script?: No ### Who can help @sgugger ## Information Model I am using (Bert, XLNet ...): Bert The problem arises when using: * [x] the official example scripts: (give details below) * [ ] my own modified scripts: (give details below) The tasks I am working on is: * [x] an official GLUE/SQUaD task: NER * [ ] my own task or dataset: (give details below) ## To reproduce The bug is for the PR #8016. Steps to reproduce the behavior: 1. MlFlow installed and the following env variables exported ``` export HF_MLFLOW_LOG_ARTIFACTS=TRUE export MLFLOW_S3_ENDPOINT_URL=<custom endpont> export MLFLOW_TRACKING_URI=<custom uri> export MLFLOW_TRACKING_TOKEN=<custom token> ``` 2. Run the token classification example with the following command ``` python run_ner.py \ --model_name_or_path bert-base-uncased \ --dataset_name conll2003 \ --output_dir /tmp/test-ner \ --do_train \ --do_eval ``` ## Expected behavior When the training finishes, before the evaluation is performed, the `integrations.MLflowCallback` executes the method `on_train_end`, where if the env variable `HF_MLFLOW_LOG_ARTIFACTS` is set to `TRUE`, it logs the model artifacts to mlflow. The problem is, however, when the method `on_train_end` is called and the following line is executed: `self._ml_flow.log_artifacts(args.output_dir)`, the model is not stored on the `args.output_dir`. The model artefacts are stored once the `trainer.save_model()` is called, which is after the training ending. There is no callback in the `trainer.save_model()` that can be called from a `TrainerCallback` to save the model. There is a method `TrainierCallback.on_save()` method, that is called `trainer._maybe_log_save_evaluate()`, but even then the model is not available on the `output_dir`. Possible solutions would be to extend the `TrainierCallback` with `on_model_save()` callback method, insert the callback in the `trainer.save_model()`. Or, a workaround I have now is to change `on_train_end ` with `on_evaluate` in `integrations.MLflowCallback`, that is called after the model is saved in the example script. However, this is not the right solution since it depends on having set the `do_eval` parameter, and it is not semantically correct. stackoverflow.com #### Validation and Training Loss when using HuggingFace **nlp, huggingface-transformers, huggingface, huggingface-trainer** asked by tt40kiwi on 01:36PM - 16 Aug 23 UTC
discuss.huggingface.co
August 1, 2025 at 4:26 PM
Log losses/metrics with CustomTrainer(Trainer) class in the same frequency as Trainer, with wandb
Hello ! How could I log losses and metrics with a CustomTrainer(Trainer) class, with the same frequency as the Trainer class ? The code I’m fine-tuning is logging a total loss with the Trainer class : `total_loss = mlm_loss + clf_loss` In the Trainer class, the train loss seems to be computed as following : transformers/src/transformers/trainer.py at a5923d4de7df2fbd1f373dfcfe983216b79b6937 · huggingface/transformers · GitHub And i need to log the `mlm_loss`, the `perplexity`, and the `clf_loss` during training and evaluation at the same frequency as in the **Trainer** class. I’m using Weights and Biases for logging. How could I implement that ? Could you explain the logic of the steps/global_step/accumulation_gradient_step ? I’ve understood that: * a **training step** represents 1 forward pass + compute the loss (and sometimes the backward pass), and is called once per batch. * a **gradient accumulation step** aims to simulate a larger effective batch size. It can run x training steps to accumulate gradients + do one optimizer update. * a **logging step** : controls the frequency of logging (loss + metrics). * a **global step** is the total number of training step over all the N epochs. Are these definition correct ? Should I also use some callbacks from transformers/src/transformers/trainer_callback.py at v4.53.3 · huggingface/transformers · GitHub ? I’m getting stuck in the implementation because I haven’t understood the logic. In my code, I’ve defined class CustomPreTrainingOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None mlm_loss: Optional[torch.FloatTensor] = None clf_loss: Optional[torch.FloatTensor] = None logits: Optional[torch.FloatTensor] = None # mlm_logits: Optional[torch.FloatTensor] = None clf_logits: Optional[torch.FloatTensor] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None So that the forward method returns this CustomPreTrainingOutput. In the CustomTrainer(Trainer), I have a `compute_loss` method : class CustomTrainer(Trainer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Initialize accumulators self._stored_mlm_loss = [] self._stored_clf_loss = [] self._stored_perplexity = [] def compute_loss(self, model, inputs, return_outputs=False): outputs = model(**inputs) loss = outputs.loss mlm_loss = getattr(outputs, 'mlm_loss', torch.tensor(0.0, device=loss.device)) clf_loss = getattr(outputs, 'clf_loss', torch.tensor(0.0, device=loss.device)) try: perplexity = torch.exp(mlm_loss) if mlm_loss is not None else torch.tensor(0.0, device=loss.device) except Exception: perplexity = torch.tensor(0.0, device=loss.device) # Safe float conversions for logging loss_value = loss.item() mlm_loss_value = mlm_loss.detach().cpu().item() clf_loss_value = clf_loss.detach().cpu().item() perplexity_value = perplexity.detach().cpu().item() # Log to console (optional) logger.info(f"class CustomTrainer(Trainer) [compute_loss] loss: {loss_value:.4f}") logger.info(f"class CustomTrainer(Trainer) [compute_loss] mlm_loss: {mlm_loss:.4f}") logger.info(f"class CustomTrainer(Trainer) [compute_loss] clf_loss: {clf_loss:.4f}") logger.info(f"class CustomTrainer(Trainer) [compute_loss] perplexity: {perplexity_value:.4f}") # Log to W&B and Trainer metrics self.log({ "loss": loss_value, "mlm_loss": mlm_loss_value, "clf_loss": clf_loss_value, "perplexity": perplexity_value, }) # wandb.log( # {"loss": loss_value, # "mlm_loss": mlm_loss_value, # "clf_loss": clf_loss_value, # "perplexity": perplexity_value # }) return (loss, outputs) if return_outputs else loss def evaluate(self, eval_dataset=None, **kwargs) -> Dict[str, float]: # Reset accumulators before evaluation self._stored_mlm_loss.clear() self._stored_clf_loss.clear() self._stored_perplexity.clear() eval_output = super().evaluate(eval_dataset=eval_dataset, **kwargs) if self.state.is_world_process_zero: self.log({ "eval_mlm_loss": eval_output["eval_mlm_loss"], "eval_clf_loss": eval_output["eval_clf_loss"], "eval_perplexity": eval_output["eval_perplexity"], }) wandb.log({f"eval/{k}": v for k, v in eval_output.items()}) return eval_output # return super().evaluate(eval_dataset=eval_dataset, **kwargs) def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None): # Ensure inputs are on the same device as model device = model.device if hasattr(model, 'device') else next(model.parameters()).device inputs = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()} # Standard eval step, get full output with torch.no_grad(): outputs = model(**inputs) loss = outputs.loss # Defensive: handle possible missing attributes mlm_loss = getattr(outputs, 'mlm_loss', torch.tensor(0.0, device=loss.device)) clf_loss = getattr(outputs, 'clf_loss', torch.tensor(0.0, device=loss.device)) perplexity = getattr(outputs, 'perplexity', torch.exp(loss_mlm)) # Save extra losses for logging (will be averaged later in `compute_metrics`) self._stored_mlm_loss.append(mlm_loss.detach().cpu().item()) self._stored_clf_loss.append(clf_loss.detach().cpu().item()) self._stored_perplexity.append(perplexity.detach().cpu().item()) return (loss, None, None) I don’t know how to get the same logging frequency than in the Trainer. I’ve tried to add callbacks with: class LossSplitLoggerCallback(TrainerCallback): def on_log(self, args, state, control, logs=None, **kwargs): trainer = kwargs["trainer"] if hasattr(trainer, "_last_mlm_loss"): logs["mlm_loss"] = trainer._last_lm_loss if hasattr(trainer, "_last_clf_loss"): logs["clf_loss"] = trainer._last_clf_loss And in my main function: trainer = CustomTrainer( model=model, args=training_args, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, tokenizer=tokenizer, data_collator=data_collator, compute_metrics=compute_metrics if training_args.do_eval and not is_torch_tpu_available() else None, preprocess_logits_for_metrics=preprocess_logits_for_metrics if training_args.do_eval and not is_torch_tpu_available() else None, callbacks=[LossSplitLoggerCallback()], ) What is the purpose of _maybe_log_save_evaluate() method ? Could you give me some guidance, please ? Thank in advance,
discuss.huggingface.co
August 1, 2025 at 12:26 PM
How do I backpropagate specific output tokens using Trainer?
I have a binary mask that masks the training loss for tokens that I don’t want to be updated in backpropagation. Until now I only set the loss of the tokens I didn’t want to train to zero. But now, **I want to completely remove backpropagation for these tokens, to gain speed in training**. Does anyone have any idea how to make this modification when I’m using this CustomTrainer? class CustomTrainer(transformers.Trainer): def compute_loss(self, model, inputs, return_outputs=False): labels = inputs.pop('labels') loss_mask = inputs.pop('loss_mask') # forward outputs = model(**inputs) logits = outputs.logits if torch.isnan(logits).any(): print('NaN detected in logits') print(logits) probs = nn.functional.softmax(logits, dim=-1) predicted_token_ids = torch.argmax(probs, dim=-1) loss_fct = nn.CrossEntropyLoss(reduction='none') losses = loss_fct(logits.view(-1, self.model.config.vocab_size), labels.view(-1)) losses = losses.view(-1, inputs['input_ids'].size(1)) masked_loss = losses * loss_mask loss = masked_loss.sum() / (loss_mask.sum() + 1e-9) batch_size, seq_length = inputs['input_ids'].size() return (loss, outputs) if return_outputs else loss def get_train_dataloader(self): train_dataset = self.train_dataset data_collator = self.data_collator dataloader_params = { 'batch_size': self.args.train_batch_size, 'collate_fn': data_collator, 'num_workers': self.args.dataloader_num_workers, 'pin_memory': self.args.dataloader_pin_memory } if not isinstance(train_dataset, torch.utils.data.IterableDataset): dataloader_params['shuffle'] = True dataloader_params['drop_last'] = self.args.dataloader_drop_last return DataLoader(train_dataset, **dataloader_params) def get_eval_dataloader(self, eval_dataset=None): if eval_dataset is None: eval_dataset = self.eval_dataset data_collator = self.data_collator dataloader_params = { 'batch_size': self.args.eval_batch_size, 'collate_fn': data_collator, 'num_workers': self.args.dataloader_num_workers, 'pin_memory': self.args.dataloader_pin_memory, 'shuffle': False, 'drop_last': self.args.dataloader_drop_last, } if isinstance(eval_dataset, torch.utils.data.IterableDataset): dataloader_params.pop('shuffle', None) dataloader_params.pop('drop_last', None) return DataLoader(eval_dataset, **dataloader_params) I’ve already tried some modifications, such as detaching the logits in the logits tensor lines that I don’t want backpropagation to go through, but I don’t know if this is the right way. I need a backpropagation like this, where only the first token and the first EOS are updated in the training (**Ignore the active SOS in the output part in the first image**):
discuss.huggingface.co
December 26, 2024 at 12:02 AM