huggingface/transformers · #50586
Add native loss support for JEV decision models
docs/source/en/model_doc/jev.md31 + / 0 −
@@ -81,6 +81,37 @@ and [d3](https://huggingface.co/vllm-sr/d3), whose Qwen3.5 backbone attends to t pipeline("decision", model="vllm-sr/d3")(request) # or perplexity-ai/pplx-decider-v1.1-27b ``` +## Training++[JEV](https://huggingface.co/autotrust/JEV-9B#training-details) uses KL divergence over the active options and adds+half the ranked probability score for ordered Score questions.+Using the model and request above, train on the first option of each question:++```python+from transformers.decision import Question++model.train()+inputs, questions = config.prepare_inputs(request, tokenizer)[0]+counts = torch.tensor([[len(q.options) for q in questions]])+types = torch.tensor([[Question.questions_types.index(q.type) for q in questions]])++inputs.update(+ marks=inputs["marks"][None],+ num_options=counts,+ question_type_ids=types,+ labels=torch.zeros_like(counts),+)+outputs = model(**{name: tensor.to(model.device) for name, tensor in inputs.items()})+outputs.loss.backward()+```++Pass `loss_weights` with shape `(1, num_questions)` to weight individual questions. The loss is divided by the number+of valid questions. If your `Trainer` dataset includes a `loss_weights` column, set `remove_unused_columns=False`+to pass it through to the model.++In a custom accumulation loop, pass the total valid-question count as `num_items_in_batch` to weight prompts with+different numbers of questions correctly. The standard `Trainer` averages the microbatch losses.+ ## JevConfig [[autodoc]] JevConfigsrc/transformers/decision/modeling_utils.py3 + / 1 −
@@ -111,6 +111,8 @@ def decide( `Question.answer` turns into answers. """ decision_config = decision_config or self.decision_config+ # Override any caller preference because we read `.logits` below.+ kwargs["return_dict"] = True inputs = {"input_ids": input_ids, **kwargs} num_options = torch.tensor([[len(question.options) for question in decision_questions]]) question_types = [Question.questions_types.index(question.type) for question in decision_questions]@@ -119,7 +121,7 @@ def decide( num_options=num_options.to(self.device), question_type_ids=torch.tensor([question_types], device=self.device), **{key: value.to(self.device) if hasattr(value, "to") else value for key, value in inputs.items()},- )+ ).logits return process_scores( decision_config, inputs["input_ids"], marks, decision_questions, scores.split(num_options[0].tolist()) )src/transformers/loss/loss_jev.pyadded86 + / 0 −
@@ -0,0 +1,86 @@+# Copyright 2026 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+from torch.nn import functional as F+++def masked_log_softmax(scores: torch.Tensor, option_mask: torch.Tensor) -> torch.Tensor:+ """Compute stable log probabilities over the active options of each question."""+ scores = scores.float().masked_fill(~option_mask, -torch.inf)+ # Exclude the maximum before log1p to retain tiny losses and target gradients at confident predictions.+ maximum = scores.argmax(-1, keepdim=True)+ is_maximum = torch.arange(scores.shape[-1], device=scores.device) == maximum+ shifted = torch.where(is_maximum, 0.0, scores - scores.gather(-1, maximum))+ others = shifted.exp().masked_fill(is_maximum, 0.0).sum(-1, keepdim=True)+ return (shifted - torch.log1p(others)).masked_fill(~option_mask, 0.0)+++def ranked_probability_score(+ probabilities: torch.Tensor, targets: torch.Tensor, num_options: torch.Tensor+) -> torch.Tensor:+ """Average the squared CDF error over the gaps between adjacent ranks."""+ difference = probabilities.cumsum(-1) - targets.cumsum(-1)+ gaps = torch.arange(probabilities.shape[-1], device=probabilities.device) < (num_options - 1)[:, None]+ return (difference.square() * gaps).sum(-1) / (num_options - 1).clamp_min(1)+++def JevForDecisionLoss(+ logits: torch.Tensor,+ labels: torch.Tensor,+ num_options: torch.Tensor,+ is_score: torch.Tensor,+ loss_weights: torch.Tensor | None = None,+ num_items_in_batch: torch.Tensor | int | None = None,+ ignore_index: int = -100,+ **kwargs,+) -> torch.Tensor:+ """AutoTrust JEV's documented KL(target || model) + ordinal RPS objective over each question's active slots.++ Source: https://huggingface.co/autotrust/JEV-9B/blob/7ac669b8fb476ba926491e3d1c39f9330d68dbed/README.md#training-details+ """+ labels = labels.to(logits.device).reshape(-1)+ num_options = num_options.to(logits.device).reshape(-1)+ soft_labels = labels.is_floating_point()+ expected_size = logits.numel() if soft_labels else num_options.numel()+ if labels.numel() != expected_size:+ raise ValueError("Expected one soft label per active option or one integer label per question.")++ valid = torch.ones_like(num_options, dtype=torch.bool) if soft_labels else labels != ignore_index+ if not soft_labels and torch.any(valid & ((labels < 0) | (labels >= num_options))):+ raise ValueError("Each integer label must select an active option of its question.")++ positions = torch.arange(num_options.max(), device=logits.device)+ option_mask = positions < num_options[:, None]+ starts = num_options.cumsum(0) - num_options+ indices = (starts[:, None] + positions).clamp_max(logits.numel() - 1)+ log_probabilities = masked_log_softmax(logits[indices], option_mask)++ if soft_labels:+ targets = labels[indices].float().clamp_min(0).masked_fill(~option_mask, 0.0)+ else:+ targets = F.one_hot(labels.masked_fill(~valid, 0).long(), num_classes=positions.numel()).float()+ targets = targets * valid[:, None]++ # Keep target entropy: soft-target CE has the same gradients, but a different loss value.+ losses = F.kl_div(log_probabilities, targets, reduction="none").sum(-1)+ rps = ranked_probability_score(log_probabilities.exp() * option_mask, targets, num_options)+ losses = losses + 0.5 * rps * is_score.to(logits.device).reshape(-1)++ if loss_weights is not None:+ losses = losses * loss_weights.to(logits.device).reshape(-1)++ # Normalize over valid questions, including when question weights are supplied.+ normalizer = valid.sum().clamp_min(1) if num_items_in_batch is None else num_items_in_batch+ normalizer = torch.as_tensor(normalizer, device=logits.device)+ return (losses * valid).sum() / normalizersrc/transformers/loss/loss_utils.py2 + / 0 −
@@ -23,6 +23,7 @@ from .loss_deimv2 import Deimv2ForObjectDetectionLoss from .loss_for_object_detection import ForObjectDetectionLoss, ForSegmentationLoss from .loss_grounding_dino import GroundingDinoForObjectDetectionLoss+from .loss_jev import JevForDecisionLoss from .loss_lsd import PocketTTSForConditionalGenerationLoss from .loss_lw_detr import LwDetrForObjectDetectionLoss from .loss_rf_detr import RfDetrForSegmentationLoss@@ -172,6 +173,7 @@ def ForSemanticSegmentationLoss( LOSS_MAPPING = {+ "JevForDecision": JevForDecisionLoss, "ForSemanticSegmentation": ForSemanticSegmentationLoss, "ForCausalLM": ForCausalLMLoss, "ForMaskedLM": ForMaskedLMLoss,src/transformers/models/jev/modeling_jev.py40 + / 3 −
@@ -11,13 +11,15 @@ # 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 dataclasses import dataclass+ import torch from torch import nn from ...decision import Question from ...decision.modeling_utils import DecisionMixin from ...modeling_utils import PreTrainedModel-from ...utils import auto_docstring+from ...utils import ModelOutput, auto_docstring, can_return_tuple from ..auto import AutoModel from .configuration_jev import JevConfig @@ -29,28 +31,53 @@ class JevPreTrainedModel(PreTrainedModel): _supports_sdpa = _supports_flash_attn = _supports_flex_attn = True +@auto_docstring+@dataclass+class JevDecisionOutput(ModelOutput):+ r"""+ loss (`torch.FloatTensor` of shape `()`, *optional*):+ Mean KL loss plus half the ranked probability score on `score` questions, when labels are supplied.+ logits (`torch.FloatTensor` of shape `(total_num_options,)`):+ Uncalibrated active-option scores concatenated in question order.+ """++ loss: torch.Tensor | None = None+ logits: torch.Tensor | None = None++ @auto_docstring( custom_intro=""" JEV (autotrust/JEV-9B): the model of its repo and a decision head, linear scores of single-token labels at the token before the `<|mark|>` of each question, soft-capped like the logits of a language model head. """ ) class JevForDecision(DecisionMixin, JevPreTrainedModel):+ # Trainer averages microbatch losses. Its automatic item count would count options for soft labels.+ accepts_loss_kwargs = False+ def __init__(self, config: JevConfig): super().__init__(config) self.model = AutoModel.from_config(config.text_config) self.proj = nn.Linear(config.hidden_size, config.num_verbalizers) self.post_init() + @can_return_tuple @auto_docstring def forward( self, input_ids: torch.LongTensor, marks: torch.LongTensor, num_options: torch.LongTensor, question_type_ids: torch.LongTensor,+ labels: torch.Tensor | None = None, **kwargs,- ) -> torch.Tensor:+ ) -> JevDecisionOutput:+ r"""+ labels (`torch.Tensor`, *optional*):+ Integer option indices of shape `(1, num_questions)`, with `-100` for ignored questions, or floating-point+ target distributions of shape `(1, total_num_options)`, concatenated in question order. Each distribution+ must sum to one over that question's active options.+ """ # A batch of one prompt marks, num_options, question_type_ids = marks[0], num_options[0], question_type_ids[0] hidden_states = self.model(input_ids=input_ids, use_cache=False, **kwargs).last_hidden_state[0]@@ -61,7 +88,17 @@ def forward( offsets = [self.config.offsets[question_type] for question_type in Question.questions_types] starts = torch.tensor(offsets, device=logits.device)[question_type_ids] rows = torch.arange(logits.shape[-1], device=logits.device)- return logits[(rows >= starts[:, None]) & (rows < (starts + num_options)[:, None])]+ scores = logits[(rows >= starts[:, None]) & (rows < (starts + num_options)[:, None])]+ loss = None+ if labels is not None:+ loss = self.loss_function(+ logits=scores,+ labels=labels,+ num_options=num_options,+ is_score=question_type_ids == Question.questions_types.index("score"),+ **kwargs,+ )+ return JevDecisionOutput(loss=loss, logits=scores) __all__ = ["JevForDecision", "JevPreTrainedModel"]tests/models/jev/test_modeling_jev.py55 + / 2 −
@@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import copy import json import tempfile import unittest@@ -21,10 +22,14 @@ from safetensors.torch import save_file from transformers import AutoProcessor, is_torch_available, pipeline-from transformers.decision import DecisionConfig+from transformers.decision import DecisionConfig, Question from transformers.testing_utils import require_torch, require_torch_accelerator, require_vision, slow -from ...test_decision_head_common import DecisionHeadTesterMixin, check_decision, render+from ...test_decision_head_common import (+ DecisionHeadTesterMixin,+ check_decision,+ render,+) if is_torch_available():@@ -33,12 +38,60 @@ from transformers import JevForDecision +class JevModelTester:+ def __init__(self, config, prompt):+ self.config = config+ self.prompt = prompt++ def prepare_config_and_inputs_for_training(self):+ prompt = self.prompt+ counts = torch.tensor([[len(q.options) for q in prompt.questions]])+ types = torch.tensor([[Question.questions_types.index(q.type) for q in prompt.questions]])+ generator = torch.Generator().manual_seed(0)+ labels = (torch.rand(counts.shape, generator=generator) * counts).long()+ inputs = {+ **prompt.inputs,+ "marks": prompt.inputs["marks"][None],+ "num_options": counts,+ "question_type_ids": types,+ "labels": labels,+ "loss_weights": torch.full_like(counts, 0.5, dtype=torch.float32),+ }+ return copy.deepcopy(self.config), inputs++ @require_torch class JevForDecisionTest(DecisionHeadTesterMixin, unittest.TestCase): all_model_classes = (JevForDecision,) if is_torch_available() else ()+ is_training = True decision_repo = "hf-internal-testing/decision-gev" tiny_sizes = {"hidden_size": 16} + def setUp(self):+ self.model_tester = JevModelTester(self.config, self.prompts[0])++ def test_training_loss_on_packed_questions(self):+ model = JevForDecision(copy.deepcopy(self.config)).train()+ choice_target = torch.tensor([1.0, 0.0])+ score_target = torch.tensor([0.25, 0.75, 0.0])+ outputs = model(+ input_ids=torch.tensor([[1, 2, 3, 4, 5, 6]]),+ marks=torch.tensor([[3, 6]]),+ num_options=torch.tensor([[2, 3]]),+ question_type_ids=torch.tensor([[Question.questions_types.index(kind) for kind in ("choice", "score")]]),+ labels=torch.cat((choice_target, score_target))[None],+ loss_weights=torch.tensor([[0.5, 2.0]]),+ num_items_in_batch=3,+ )++ choice_logits, score_logits = outputs.logits.detach().split((2, 3))+ choice_kl = torch.nn.functional.cross_entropy(choice_logits, choice_target)+ score_log_probs = score_logits.log_softmax(-1)+ score_kl = torch.nn.functional.kl_div(score_log_probs, score_target, reduction="sum")+ score_rps = (score_log_probs.exp().cumsum(0)[:-1] - score_target.cumsum(0)[:-1]).square().mean()+ expected_loss = (0.5 * choice_kl + 2 * (score_kl + 0.5 * score_rps)) / 3+ torch.testing.assert_close(outputs.loss, expected_loss)+ @require_vision def test_chat_template_reproduces_the_model_code(self): super().test_chat_template_reproduces_the_model_code()tests/test_decision_head_common.py21 + / 0 −
@@ -63,6 +63,8 @@ class DecisionHeadTesterMixin: `backbone_class` model. """ + is_training = False+ model_tester = None backbone_class = Qwen2ForCausalLM if is_torch_available() else None @classmethod@@ -109,6 +111,25 @@ def test_scores_and_save_load(self): torch.testing.assert_close(loaded_scores, scores) self.assertEqual([len(s) for s in scores], [len(question.options) for question in prompt.questions]) + def test_training(self):+ if not self.is_training:+ self.skipTest("Decision head is not configured to run training tests.")++ for model_class in self.all_model_classes:+ with self.subTest(model=model_class.__name__):+ config, inputs = self.model_tester.prepare_config_and_inputs_for_training()+ model = model_class(config).to(torch_device).train()+ inputs = {name: tensor.to(torch_device) for name, tensor in inputs.items()}++ loss = model(**inputs).loss+ self.assertEqual(loss.ndim, 0)+ self.assertTrue(torch.isfinite(loss))+ loss.backward()++ gradients = [parameter.grad for parameter in model.parameters() if parameter.grad is not None]+ self.assertTrue(all(torch.isfinite(grad).all() for grad in gradients))+ self.assertTrue(any(torch.count_nonzero(grad) for grad in gradients))+ def check_decision( test_case, model: str | None, decision_repo: str, expected: dict, atol: float = 1e-3, **pipeline_kwargs