diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index 7e33e3323ef5..2bcf4f03a8d1 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -727,6 +727,8 @@ title: GraniteMoeSWA - local: model_doc/granite_swa title: GraniteSWA + - local: model_doc/gs1 + title: GS1 - local: model_doc/gte title: GTE - local: model_doc/helium diff --git a/docs/source/en/model_doc/gs1.md b/docs/source/en/model_doc/gs1.md new file mode 100644 index 000000000000..3c54f159c564 --- /dev/null +++ b/docs/source/en/model_doc/gs1.md @@ -0,0 +1,70 @@ + +*This model was contributed to Hugging Face Transformers on 2026-11-24.* + +# GS1 + +GS1 is a family of pretrained models from [BIGAI](https://gs1.mybigai.ac.cn) for structured decision tasks. Given a state +and a question, GS1 scores each candidate answer. It supports `choice`, `score`, and `noul` (yes/no) questions. + +GS1 uses a Qwen3.5 text model and a Qwen3.5 vision encoder as its backbone. It includes GS1-specific bidirectional +decision-context processing, attention-residual routing, and a cross-attention decision head. The head reads the +question and option spans from the rendered prompt and returns one logit per option. + +| Model | Checkpoint | +|---|---| +| GS1-0.8B | [bigai/GS1-0.8B](https://huggingface.co/bigai/GS1-0.8B) | +| GS1-2B | [bigai/GS1-2B](https://huggingface.co/bigai/GS1-2B) | +| GS1-4B | [bigai/GS1-4B](https://huggingface.co/bigai/GS1-4B) | +| GS1-9B | [bigai/GS1-9B](https://huggingface.co/bigai/GS1-9B) | + +See the [open-source implementation](https://github.com/bigai-nlco/GS1) +for the model and inference reference. + +## Usage + +Use the [decision pipeline](../main_classes/pipelines#transformers.DecisionPipeline) to score options for a request. + +```python +from transformers import pipeline + +decide = pipeline("decision", model="bigai/GS1-0.8B") +answers = decide( + { + "state": "My package arrived damaged. Please send a replacement.", + "questions": { + "resolution": { + "type": "choice", + "instructions": "What does the customer want?", + "criteria": {"refund": "A refund", "replacement": "A replacement"}, + }, + }, + } +) +print(answers["resolution"]["choice"]) +``` + +## GS1Config + +[[autodoc]] GS1Config + +## GS1ForDecision + +[[autodoc]] GS1ForDecision + - forward diff --git a/src/transformers/conversion_mapping.py b/src/transformers/conversion_mapping.py index 8cd56149f42f..bc64b30c6bcb 100755 --- a/src/transformers/conversion_mapping.py +++ b/src/transformers/conversion_mapping.py @@ -162,6 +162,13 @@ def _build_checkpoint_conversion_mapping(): mapping = { + "gs1": [ + WeightRenaming(r"^decision_head\.routing_ffn\.(\d+)\.0\.", r"decision_head.routing_ffn_in.\1."), + WeightRenaming(r"^decision_head\.routing_ffn\.(\d+)\.2\.", r"decision_head.routing_ffn_out.\1."), + WeightRenaming(r"^decision_head\.(query|key)_mlp\.0\.", r"decision_head.\1_mlp_in."), + WeightRenaming(r"^decision_head\.(query|key)_mlp\.2\.", r"decision_head.\1_mlp_out."), + WeightRenaming(r"^calibrator\.beta", "calibration_beta"), + ], # Dory checkpoints store each decoder layer as an attention block followed by an mlp block "dory": [ LayerPairCollapse(), diff --git a/src/transformers/decision/modeling_utils.py b/src/transformers/decision/modeling_utils.py index eaa313d530a2..00a46a4d2ba3 100644 --- a/src/transformers/decision/modeling_utils.py +++ b/src/transformers/decision/modeling_utils.py @@ -54,11 +54,12 @@ def from_pretrained(cls, pretrained_model_name_or_path, *args, config=None, deci if head_config is None and config is not None: raise ValueError(f"{pretrained_model_name_or_path} has no {cls.__name__} head next to its weights.") config = head_config or config - model = super().from_pretrained(pretrained_model_name_or_path, *args, config=config, **kwargs) + result = super().from_pretrained(pretrained_model_name_or_path, *args, config=config, **kwargs) + model = result[0] if isinstance(result, tuple) else result if decision_config is None: # the decision config of the repo, read now like `generation_config` decision_config = DecisionConfig.from_pretrained(pretrained_model_name_or_path, **_hub_kwargs(kwargs)) model.decision_config = decision_config - return model + return result @classmethod def checkpoint_config( @@ -120,6 +121,8 @@ def decide( 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()}, ) + if not isinstance(scores, torch.Tensor): + scores = scores.logits return process_scores( decision_config, inputs["input_ids"], marks, decision_questions, scores.split(num_options[0].tolist()) ) diff --git a/src/transformers/loss/loss_gs1.py b/src/transformers/loss/loss_gs1.py new file mode 100644 index 000000000000..9bfb0a3d5d46 --- /dev/null +++ b/src/transformers/loss/loss_gs1.py @@ -0,0 +1,54 @@ +# 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 + +import torch + + +def GS1ForDecisionLoss( + logits: torch.Tensor, + labels: torch.Tensor, + num_options: torch.Tensor, + loss_weights: torch.Tensor | None = None, + brier_weight: float = 1.0, + num_items_in_batch: torch.Tensor | int | None = None, + **kwargs, +) -> torch.Tensor: + """Mean distribution NLL plus expected multiclass Brier, one unit per question.""" + logits = logits.float() + labels = labels.to(device=logits.device).reshape(-1) + num_options = num_options.to(device=logits.device, dtype=torch.long).reshape(-1) + if num_options.numel() == 0 or (num_options < 1).any() or num_options.sum() != logits.numel(): + raise ValueError("num_options must partition the flat candidate logits") + if not labels.is_floating_point() or labels.numel() != logits.numel(): + raise ValueError("GS1 targets must provide a floating-point distribution per active candidate") + labels = labels.float() + if not torch.isfinite(labels).all() or (labels < 0).any(): + raise ValueError("Decision targets must be finite and nonnegative") + + losses, offset = [], 0 + for index, count in enumerate(num_options.tolist()): + scores = logits[offset : offset + count] + target = labels[offset : offset + count] + if not torch.isclose(target.sum(), target.new_tensor(1.0), atol=1e-6, rtol=0): + raise ValueError("Each target distribution must sum to one") + log_probability = scores.log_softmax(-1) + probability = log_probability.exp() + nll = -(target * log_probability).sum() + brier = (probability - target).square().sum() + 1 - target.square().sum() + weight = 1.0 if loss_weights is None else loss_weights.reshape(-1)[index].to(logits.device) + losses.append((nll + brier_weight * brier) * weight) + offset += count + + loss = torch.stack(losses).sum() + if num_items_in_batch is not None: + denominator = torch.as_tensor(num_items_in_batch, device=logits.device).clamp_min(1) + return loss / denominator + return loss / len(losses) + + +__all__ = ["GS1ForDecisionLoss"] diff --git a/src/transformers/loss/loss_utils.py b/src/transformers/loss/loss_utils.py index 023f2dd8b285..fb25d378e3a5 100644 --- a/src/transformers/loss/loss_utils.py +++ b/src/transformers/loss/loss_utils.py @@ -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_gs1 import GS1ForDecisionLoss from .loss_lsd import PocketTTSForConditionalGenerationLoss from .loss_lw_detr import LwDetrForObjectDetectionLoss from .loss_rf_detr import RfDetrForSegmentationLoss @@ -185,6 +186,7 @@ def ForSemanticSegmentationLoss( "ForObjectDetection": ForObjectDetectionLoss, "ForCTC": ForCTCLoss, "ForConditionalGeneration": ForCausalLMLoss, + "ForDecision": GS1ForDecisionLoss, "DeformableDetrForObjectDetection": DeformableDetrForObjectDetectionLoss, "ConditionalDetrForObjectDetection": DeformableDetrForObjectDetectionLoss, "DabDetrForObjectDetection": DeformableDetrForObjectDetectionLoss, diff --git a/src/transformers/models/__init__.py b/src/transformers/models/__init__.py index ab0345512ed0..b4e17aa7b04e 100644 --- a/src/transformers/models/__init__.py +++ b/src/transformers/models/__init__.py @@ -222,6 +222,7 @@ from .granitemoeshared import * from .grounding_dino import * from .groupvit import * + from .gs1 import * from .gte import * from .helium import * from .herbert import * diff --git a/src/transformers/models/auto/auto_mappings.py b/src/transformers/models/auto/auto_mappings.py index b1729e21aa08..04059e8ab809 100644 --- a/src/transformers/models/auto/auto_mappings.py +++ b/src/transformers/models/auto/auto_mappings.py @@ -312,6 +312,7 @@ ("groupvit", "GroupViTConfig"), ("groupvit_text_model", "GroupViTTextConfig"), ("groupvit_vision_model", "GroupViTVisionConfig"), + ("gs1", "GS1Config"), ("gte", "GteConfig"), ("helium", "HeliumConfig"), ("hgnet_v2", "HGNetV2Config"), diff --git a/src/transformers/models/auto/modeling_auto.py b/src/transformers/models/auto/modeling_auto.py index a39e5484b698..4fc58c9e399b 100644 --- a/src/transformers/models/auto/modeling_auto.py +++ b/src/transformers/models/auto/modeling_auto.py @@ -2191,6 +2191,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): MODEL_FOR_DECISION_MAPPING_NAMES = OrderedDict( [ ("gemma4", "JevForDecision"), + ("gs1", "GS1ForDecision"), ("jev", "JevForDecision"), ("qwen2", "JevForDecision"), ("qwen3_5", "JevForDecision"), diff --git a/src/transformers/models/gs1/__init__.py b/src/transformers/models/gs1/__init__.py new file mode 100644 index 000000000000..5faf6b893718 --- /dev/null +++ b/src/transformers/models/gs1/__init__.py @@ -0,0 +1,27 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from the modules in `src/transformers/models/gs1`. +# Do NOT edit this file manually as any edits will be overwritten by auto-generation of the file. +# A module is picked up once it exports a name through `__all__`. +# Regenerate the file with: `python utils/check_inits.py --fix_and_overwrite` +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# 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 +from typing import TYPE_CHECKING + +from ...utils import _LazyModule +from ...utils.import_utils import define_import_structure + + +if TYPE_CHECKING: + from .configuration_gs1 import * + from .modeling_gs1 import * +else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) diff --git a/src/transformers/models/gs1/configuration_gs1.py b/src/transformers/models/gs1/configuration_gs1.py new file mode 100644 index 000000000000..bb83ee674e0e --- /dev/null +++ b/src/transformers/models/gs1/configuration_gs1.py @@ -0,0 +1,96 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/gs1/modular_gs1.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_gs1.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# 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 math +from dataclasses import field + +from huggingface_hub.dataclasses import strict + +from ...configuration_utils import PreTrainedConfig, SubConfigSpec +from ...utils import auto_docstring +from ..auto import AutoConfig + + +GS1_DEFAULTS = { + "attnres": True, + "attnres_layers": None, + "attnres_eps": 1e-6, + "bidirectional": True, + "bidirectional_layers": None, + "cross_attention_heads": 8, + "cross_attention_layers": 2, + "projection_size": 256, + "norm_eps": 1e-5, +} + + +@auto_docstring(checkpoint="bigai/GS1-9B") +@strict +class GS1Config(PreTrainedConfig): + r"""Configuration for the GS1 structured decision model. + + Args: + decision (`dict`, *optional*): GS1 routing and decision-head dimensions. + calibration (`dict`, *optional*): Calibration mode used by GS1 inference. + initialization_seed (`int`, *optional*, defaults to 12): Initialization seed stored with the checkpoint. + head_compute_dtype (`str`, *optional*, defaults to `"float32"`): Decision-head compute dtype. + structural_token_ids (`dict`, *optional*): IDs of the seven GS1 structural tokens. + inference_limits (`dict`, *optional*): Maximum context, request, question, and branch sizes. + decision_brier_weight (`float`, *optional*, defaults to 1.0): Expected multiclass Brier coefficient. + """ + + model_type = "gs1" + sub_configs_defaults = { + "text_config": SubConfigSpec(config_class=AutoConfig, model_type="qwen3_5_text"), + "vision_config": SubConfigSpec(config_class=AutoConfig, model_type="qwen3_5_vision"), + } + + text_config: dict | PreTrainedConfig | None = None + vision_config: dict | PreTrainedConfig | None = None + image_token_id: int = 248056 + video_token_id: int = 248057 + vision_start_token_id: int = 248053 + vision_end_token_id: int = 248054 + tie_word_embeddings: bool = False + decision: dict = field(default_factory=dict) + calibration: dict = field(default_factory=dict) + initialization_seed: int = 12 + head_compute_dtype: str = "float32" + structural_token_ids: dict | None = None + inference_limits: dict = field(default_factory=dict) + decision_brier_weight: float = 1.0 + + def __post_init__(self, **kwargs): + if isinstance(self.vision_config, dict) and self.vision_config.get("model_type") == "qwen3_5": + self.vision_config = {**self.vision_config, "model_type": "qwen3_5_vision"} + super().__post_init__(**kwargs) + self.decision = {**GS1_DEFAULTS, **(self.decision or {})} + self.calibration = {"mode": "identity", "log_temperature_bound": math.log(20), **self.calibration} + if self.head_compute_dtype not in {"float32", "bfloat16"}: + raise ValueError("head_compute_dtype must be float32 or bfloat16") + if self.text_config.hidden_size % self.decision["cross_attention_heads"]: + raise ValueError("cross_attention_heads must divide the text hidden size") + self.tie_word_embeddings = False + self.text_config.use_cache = False + self.text_config._attn_implementation = "sdpa" + self.vision_config._attn_implementation = "sdpa" + + +__all__ = ["GS1Config"] diff --git a/src/transformers/models/gs1/modeling_gs1.py b/src/transformers/models/gs1/modeling_gs1.py new file mode 100644 index 000000000000..88ac2b18a3bd --- /dev/null +++ b/src/transformers/models/gs1/modeling_gs1.py @@ -0,0 +1,494 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/gs1/modular_gs1.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_gs1.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# 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 math +from dataclasses import dataclass +from itertools import groupby + +import torch +from torch import nn +from torch.nn import functional as F +from torch.nn.attention import SDPBackend, sdpa_kernel +from torch.utils.checkpoint import checkpoint + +from ... import decision +from ... import initialization as init +from ...modeling_utils import PreTrainedModel +from ...utils import ModelOutput, auto_docstring, can_return_tuple +from ..auto import AutoModel +from .configuration_gs1 import GS1Config + + +@auto_docstring +@dataclass +class GS1DecisionOutput(ModelOutput): + r"""Output of GS1 structured candidate scoring. + + Args: + loss (`torch.FloatTensor` of shape `()`, *optional*): Mean GS1 decision training loss. + logits (`torch.FloatTensor` of shape `(total_options,)`): Candidate logits concatenated by question. + """ + + loss: torch.Tensor | None = None + logits: torch.Tensor | None = None + + +class GS1DecisionHead(nn.Module): + def __init__(self, config): + super().__init__() + decision = config.decision + hidden_size = config.text_config.hidden_size + width = decision["projection_size"] + heads = decision["cross_attention_heads"] + eps = decision["norm_eps"] + self.memory_norm = nn.LayerNorm(hidden_size, eps=eps) + self.memory_projection = nn.Linear(hidden_size, hidden_size, bias=False) + self.question_seed = nn.Linear(hidden_size, hidden_size, bias=False) + self.question_attention = nn.MultiheadAttention(hidden_size, heads, batch_first=True) + self.decision_projection = nn.Linear(hidden_size, hidden_size, bias=False) + self.question_projection = nn.Linear(hidden_size, hidden_size, bias=False) + self.question_evidence_projection = nn.Linear(hidden_size, hidden_size, bias=False) + self.context_norm = nn.LayerNorm(hidden_size, eps=eps) + self.option_projection = nn.Linear(hidden_size, hidden_size, bias=False) + self.condition_projection = nn.Linear(hidden_size, hidden_size, bias=False) + self.option_norm = nn.LayerNorm(hidden_size, eps=eps) + self.routing_attention = nn.ModuleList( + nn.MultiheadAttention(hidden_size, heads, batch_first=True) + for _ in range(decision["cross_attention_layers"]) + ) + self.routing_attention_norm = nn.ModuleList( + nn.LayerNorm(hidden_size, eps=eps) for _ in range(decision["cross_attention_layers"]) + ) + self.routing_ffn_in = nn.ModuleList( + nn.Linear(hidden_size, hidden_size) for _ in range(decision["cross_attention_layers"]) + ) + self.routing_ffn_out = nn.ModuleList( + nn.Linear(hidden_size, hidden_size) for _ in range(decision["cross_attention_layers"]) + ) + self.routing_output_norm = nn.ModuleList( + nn.LayerNorm(hidden_size, eps=eps) for _ in range(decision["cross_attention_layers"]) + ) + self.query_mlp_in = nn.Linear(hidden_size, hidden_size) + self.query_mlp_out = nn.Linear(hidden_size, width) + self.key_mlp_in = nn.Linear(hidden_size, hidden_size) + self.key_mlp_out = nn.Linear(hidden_size, width) + self.query_norm = nn.LayerNorm(width, eps=eps) + self.key_norm = nn.LayerNorm(width, eps=eps) + self.projection_size = width + self.bf16_compute = config.head_compute_dtype == "bfloat16" + + def forward(self, state, question, decision, options): + dtype = torch.bfloat16 if self.bf16_compute else self.memory_projection.weight.dtype + with torch.autocast(device_type=state.device.type, dtype=torch.bfloat16, enabled=self.bf16_compute): + state, question, decision, options = (value.to(dtype) for value in (state, question, decision, options)) + memory = self.memory_projection(self.memory_norm(state)).unsqueeze(0) + query = self.question_seed(question)[None, None] + with sdpa_kernel([SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION]): + evidence = self.question_attention(query, memory, memory, need_weights=False)[0][0, 0] + context = self.context_norm( + self.decision_projection(decision) + + self.question_projection(question) + + self.question_evidence_projection(evidence) + ) + routed = self.option_norm(self.option_projection(options) + self.condition_projection(context)) + for attention, attention_norm, ffn_in, ffn_out, output_norm in zip( + self.routing_attention, + self.routing_attention_norm, + self.routing_ffn_in, + self.routing_ffn_out, + self.routing_output_norm, + strict=True, + ): + with sdpa_kernel([SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION]): + evidence = attention(routed[None], memory, memory, need_weights=False)[0][0] + updated = attention_norm(routed + evidence) + routed = output_norm(updated + ffn_out(F.gelu(ffn_in(updated)))) + query = self.query_norm(self.query_mlp_out(F.gelu(self.query_mlp_in(context)))) + keys = self.key_norm(self.key_mlp_out(F.gelu(self.key_mlp_in(routed)))) + with torch.autocast(device_type=state.device.type, enabled=False): + return (keys.float() @ query.float()) / math.sqrt(self.projection_size) + + +class FADepthRouter(nn.Module): + def __init__(self, hidden_size, eps): + super().__init__() + self.query = nn.Parameter(torch.zeros(hidden_size)) + self.eps = eps + + def forward(self, carry, sources): + values = torch.stack(sources).float() + keys = values * torch.rsqrt(values.square().mean(-1, keepdim=True) + self.eps) + alpha = torch.einsum("d,nbtd->nbt", self.query.float(), keys).softmax(dim=0) + correction = torch.einsum("nbt,nbtd->btd", (alpha - 1 / len(sources)) * len(sources), values) + return (carry.float() + correction).to(carry.dtype) + + +class GS1DecoderLayer(nn.Module): + """Reuse Qwen3.5 projections and kernels with GS1's residual topology.""" + + def __init__(self, source): + super().__init__() + self.block_type = source.block_type + self.input_layernorm = source.input_layernorm + self.post_attention_layernorm = source.post_attention_layernorm + self.mlp = source.mlp + if self.block_type == "full_attention": + self.self_attn = source.self_attn + else: + self.linear_attn = source.linear_attn + + +class GS1TextModel(nn.Module): + def __init__(self, config): + super().__init__() + text, decision = config.text_config, config.decision + self.config = config + self.full_layers = tuple(i for i, kind in enumerate(text.layer_types) if kind == "full_attention") + backbone = AutoModel.from_config(text) + self.layers = nn.ModuleList(GS1DecoderLayer(layer) for layer in backbone.layers) + self.embed_tokens = backbone.embed_tokens + self.norm = backbone.norm + self.rotary_emb = backbone.rotary_emb + self.gradient_checkpointing = False + self._gradient_checkpointing_func = checkpoint + receivers = decision["attnres_layers"] or self.full_layers + self.attnres_routers = nn.ModuleDict( + { + str(i): FADepthRouter(text.hidden_size, decision["attnres_eps"]) + for i in receivers + if decision["attnres"] + } + ) + + @staticmethod + def _run_layer(layer, carry, positional, mask, read, valid): + if layer.block_type == "full_attention": + mixed = layer.self_attn(layer.input_layernorm(read), position_embeddings=positional, attention_mask=mask)[ + 0 + ] + else: + mixed = layer.linear_attn(hidden_states=layer.input_layernorm(carry), attention_mask=valid) + hidden = carry + mixed + ffn = layer.mlp(layer.post_attention_layernorm(hidden)) + return hidden + ffn, mixed, ffn + + def forward(self, inputs_embeds, position_ids, roles, attention_mask): + batch, length = inputs_embeds.shape[:2] + valid = attention_mask.bool() + if not valid[:, -1].all() or (valid[:, :-1] & ~valid[:, 1:]).any(): + raise ValueError("GS1 requires left-padded nonempty sequences") + keep = valid.unsqueeze(-1) + hidden = inputs_embeds * keep + eye = torch.eye(length, dtype=torch.bool, device=hidden.device)[None] + selected = self.config.decision["bidirectional_layers"] or self.full_layers + bidirectional = self.config.decision["bidirectional"] + masks = {} + for value in {bidirectional and i in selected for i in self.full_layers}: + if value: + allowed = (roles[:, :, None] >= roles[:, None, :]) & (roles[:, None, :] != 3) + allowed |= eye + else: + allowed = torch.ones((batch, length, length), dtype=torch.bool, device=hidden.device).tril_() + allowed &= valid[:, None, :] + allowed |= ~valid[:, :, None] & eye + masks[value] = hidden.new_zeros((batch, 1, length, length)).masked_fill( + ~allowed[:, None], torch.finfo(hidden.dtype).min + ) + positional = self.rotary_emb(hidden, position_ids) + bank, partial = (hidden,), None + for index, layer in enumerate(self.layers): + read = ( + hidden + if str(index) not in self.attnres_routers + else self.attnres_routers[str(index)](hidden, bank if partial is None else (*bank, partial)) + ) + mask = masks.get(bidirectional and index in selected) + if self.training and self.gradient_checkpointing: + hidden, mixed, ffn = self._gradient_checkpointing_func( + self._run_layer, layer, hidden, positional, mask, read, valid + ) + else: + hidden, mixed, ffn = self._run_layer(layer, hidden, positional, mask, read, valid) + hidden, mixed, ffn = hidden * keep, mixed * keep, ffn * keep + if self.attnres_routers: + partial = mixed + ffn if partial is None else partial + mixed + ffn + if layer.block_type == "full_attention": + bank, partial = (*bank, partial), None + return self.norm(hidden) * keep + + +@auto_docstring +class GS1PreTrainedModel(PreTrainedModel): + config: GS1Config + base_model_prefix = "language_model" + supports_gradient_checkpointing = True + _no_split_modules = ["GS1DecoderLayer"] + _supports_flash_attn = True + _supports_sdpa = True + _keys_to_ignore_on_load_unexpected = [r"^mtp.*"] + _can_record_outputs = {"hidden_states": GS1DecoderLayer, "attentions": "self_attn"} + _is_stateful = True + + def _init_weights(self, module): + super()._init_weights(module) + if isinstance(module, nn.LayerNorm): + init.ones_(module.weight) + if module.bias is not None: + init.zeros_(module.bias) + elif isinstance(module, FADepthRouter): + init.zeros_(module.query) + + +GS1_TEMPLATE = r"""{%- macro text(x) -%} +{%- set value = x if x is string else x | tojson(ensure_ascii=false, separators=(',', ':'), sort_keys=true) -%} +{{- value | replace('&', '&') | replace('<', '<') | replace('>', '>') -}} +{%- endmacro -%} +{{- '<|im_start|>user\n\n' -}} +{%- set has_images = state is sequence and state is not string and state is not mapping + and state | selectattr('type', 'defined') | selectattr('type', 'equalto', 'image') | list -%} +{%- if has_images -%} + {%- for part in state -%} + {%- if part.type == 'text' -%}{{- text(part.text) -}} + {%- elif part.type == 'image' -%}{{- '<|vision_start|><|image_pad|><|vision_end|>' -}} + {%- else -%}{{- raise_exception('Unsupported GS1 state item') -}}{%- endif -%} + {%- endfor -%} +{%- else -%}{{- text(state) -}}{%- endif -%} +{{- '\n\n\n' ~ text(question.instructions if question.instructions is not none else '') ~ '\n' -}} +{%- for option in question.options -%} + {{- '\n' -}} +{%- endfor -%} +{{- '<|im_end|>\n<|im_start|>assistant\n\n\n\n\n<|decide|><|mark|>' -}} +""" + + +@auto_docstring(checkpoint="bigai/GS1-9B") +class GS1ForDecision(decision.DecisionMixin, GS1PreTrainedModel): + accepts_loss_kwargs = False + + def __init__(self, config: GS1Config): + super().__init__(config) + self._newline_token_ids = () + self.language_model = GS1TextModel(config) + self.visual = AutoModel.from_config(config.vision_config) + self.decision_head = GS1DecisionHead(config) + if config.calibration["mode"] == "scalar_temperature": + self.calibration_beta = nn.Parameter(torch.zeros(())) + self.post_init() + + def get_input_embeddings(self): + return self.language_model.embed_tokens + + def set_input_embeddings(self, value): + self.language_model.embed_tokens = value + + def _decision_rows(self, input_ids, attention_mask): + names = ("", "", "", "", "", "<|decide|>") + try: + marker_ids = [self.config.structural_token_ids[name] for name in names] + except (TypeError, KeyError) as error: + raise ValueError("GS1 config must define all seven structural token IDs") from error + metadata, role_rows = [], [] + newline = self._newline_token_ids + for row, ids in enumerate(input_ids): + begin = int((~attention_mask[row].bool()).sum()) + values = ids[begin:] + + def find(token): + return torch.where(values == token)[0].tolist() + + state_starts, state_ends = find(marker_ids[0]), find(marker_ids[1]) + question_starts, question_ends = find(marker_ids[2]), find(marker_ids[3]) + option_starts, option_ends = find(marker_ids[4]), find(marker_ids[5]) + decisions = find(marker_ids[6]) + if not ( + len(state_starts) + == len(state_ends) + == len(question_starts) + == len(question_ends) + == len(decisions) + == 1 + ): + raise ValueError("A GS1 prompt needs one state, question, and decision marker") + if not option_starts or len(option_starts) != len(option_ends): + raise ValueError("GS1 prompt candidate markers are incomplete") + q0, q1, decision = question_starts[0], question_ends[0], decisions[0] + markers = [state_starts[0], state_ends[0], q0, q1] + markers.extend(pos for pair in zip(option_starts, option_ends, strict=True) for pos in pair) + markers.append(decision) + if any(left >= right for left, right in zip(markers, markers[1:])): + raise ValueError("GS1 prompt markers are out of order") + roles = torch.full_like(values, -1) + roles[:q0], roles[q0 : option_starts[0]], roles[option_starts[0] : decision], roles[decision] = 0, 1, 2, 3 + + def span(start, end): + start += 1 + if newline and tuple(values[start : start + len(newline)].tolist()) == newline: + start += len(newline) + if newline and tuple(values[end - len(newline) : end].tolist()) == newline: + end -= len(newline) + return (end, end + 1) if start >= end else (start, end) + + metadata.append( + ( + begin, + state_starts[0], + q0, + q1, + decision, + span(q0, q1), + option_starts, + option_ends, + [span(a, b) for a, b in zip(option_starts, option_ends, strict=True)], + ) + ) + role_rows.append(F.pad(roles, (begin, 0), value=-1)) + return metadata, torch.stack(role_rows) + + @staticmethod + def _pool_span(sequence, start, end, span): + return torch.stack((sequence[start], sequence[span[0] : span[1]].mean(0), sequence[end])).mean(0) + + def _vision_positions(self, input_ids, token_types, image_grid_thw): + positions = torch.zeros(3, *input_ids.shape, device=input_ids.device, dtype=torch.long) + grids = iter(image_grid_thw) + merge = self.config.vision_config.spatial_merge_size + for row in range(input_ids.shape[0]): + begin = offset = 0 + for kind, group in groupby(token_types[row].tolist()): + end = begin + sum(1 for _ in group) + if kind == 0: + part = torch.arange(end - begin, device=input_ids.device)[None].expand(3, -1) + offset + offset += end - begin + else: + t, h, w = map(int, next(grids)) + h, w = h // merge, w // merge + part = torch.stack( + ( + torch.full((t * h * w,), offset, device=input_ids.device), + torch.arange(offset, offset + h, device=input_ids.device).repeat_interleave(w * t), + torch.arange(offset, offset + w, device=input_ids.device).repeat(h * t), + ) + ) + offset += max(h, w) + positions[:, row, begin:end] = part + begin = end + return positions + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor, + attention_mask: torch.Tensor | None = None, + marks: torch.LongTensor | None = None, + num_options: torch.LongTensor | None = None, + question_type_ids: torch.LongTensor | None = None, + labels: torch.Tensor | None = None, + loss_weights: torch.Tensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_thw: torch.LongTensor | None = None, + mm_token_type_ids: torch.LongTensor | None = None, + **kwargs, + ) -> GS1DecisionOutput: + r""" + Args: + marks (`torch.LongTensor`, *optional*): Decision-marker positions produced by the decision input formatter. + num_options (`torch.LongTensor`, *optional*): Candidate count for each logical question. + question_type_ids (`torch.LongTensor`, *optional*): Encoded decision question types. + labels (`torch.FloatTensor`, *optional*): Flat concatenation of soft target distributions. + loss_weights (`torch.FloatTensor`, *optional*): Per-question objective weights. + pixel_values (`torch.FloatTensor`, *optional*): Processed image patches for visual states. + image_grid_thw (`torch.LongTensor`, *optional*): Temporal and spatial image grid sizes. + mm_token_type_ids (`torch.LongTensor`, *optional*): Text/image token type IDs. + """ + if attention_mask is None: + attention_mask = torch.ones_like(input_ids) + metadata, roles = self._decision_rows(input_ids, attention_mask) + hidden = self.get_input_embeddings()(input_ids) + position_ids = (attention_mask.long().cumsum(-1) - 1).clamp_min(0) + if pixel_values is not None: + features = self.visual( + pixel_values.to(self.visual.dtype), grid_thw=image_grid_thw, return_dict=True + ).pooler_output.to(hidden.device, hidden.dtype) + image_mask = (input_ids == self.config.image_token_id).unsqueeze(-1).expand_as(hidden) + if hidden[image_mask].numel() != features.numel(): + raise ValueError("Image feature count differs from GS1 image markers") + hidden = hidden.masked_scatter(image_mask, features) + if mm_token_type_ids is None: + raise ValueError("GS1 vision inputs require mm_token_type_ids") + position_ids = self._vision_positions(input_ids, mm_token_type_ids, image_grid_thw) + hidden = self.language_model(hidden, position_ids, roles, attention_mask) + logits = [] + for row, (begin, state_start, q0, q1, decision_position, qspan, starts, ends, spans) in enumerate(metadata): + sequence = hidden[row, begin:] + question = self._pool_span(sequence, q0, q1, qspan) + options = torch.stack( + [ + self._pool_span(sequence, start, end, span) + for start, end, span in zip(starts, ends, spans, strict=True) + ] + ) + logits.append(self.decision_head(sequence[state_start:q0], question, sequence[decision_position], options)) + logits = torch.cat(logits) + loss = None + if labels is not None: + option_counts = torch.tensor([len(row[-1]) for row in metadata], device=logits.device) + loss = self.loss_function( + logits=logits, + labels=labels, + num_options=option_counts, + loss_weights=loss_weights, + brier_weight=self.config.decision_brier_weight, + **kwargs, + ) + return GS1DecisionOutput(loss=loss, logits=logits) + + def post_init(self): + super().post_init() + self.decision_config = decision.configuration_utils.DecisionConfig( + chat_template=GS1_TEMPLATE, sanitize_control_tokens=True, noul_options=["false", "true"] + ) + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs): + result = super().from_pretrained(pretrained_model_name_or_path, *args, **kwargs) + model = result[0] if isinstance(result, tuple) else result + from ... import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained( + pretrained_model_name_or_path, **decision.modeling_utils._hub_kwargs(kwargs) + ) + model._newline_token_ids = tuple(tokenizer.encode("\n", add_special_tokens=False)) + if model.decision_config.chat_template is None: + model.decision_config.chat_template = GS1_TEMPLATE + model.decision_config.noul_options = ["false", "true"] + return result + + +__all__ = ["GS1PreTrainedModel", "GS1ForDecision"] diff --git a/src/transformers/models/gs1/modular_gs1.py b/src/transformers/models/gs1/modular_gs1.py new file mode 100644 index 000000000000..48c594e9e522 --- /dev/null +++ b/src/transformers/models/gs1/modular_gs1.py @@ -0,0 +1,553 @@ +# 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 math +from dataclasses import dataclass, field +from itertools import groupby + +import torch +from huggingface_hub.dataclasses import strict +from torch import nn +from torch.nn import functional as F +from torch.nn.attention import SDPBackend, sdpa_kernel +from torch.utils.checkpoint import checkpoint + +from ... import decision +from ... import initialization as init +from ...configuration_utils import PreTrainedConfig, SubConfigSpec +from ...modeling_utils import PreTrainedModel +from ...utils import ModelOutput, auto_docstring, can_return_tuple +from ..auto import AutoConfig, AutoModel + + +GS1_DEFAULTS = { + "attnres": True, + "attnres_layers": None, + "attnres_eps": 1e-6, + "bidirectional": True, + "bidirectional_layers": None, + "cross_attention_heads": 8, + "cross_attention_layers": 2, + "projection_size": 256, + "norm_eps": 1e-5, +} + +GS1_TEMPLATE = r"""{%- macro text(x) -%} +{%- set value = x if x is string else x | tojson(ensure_ascii=false, separators=(',', ':'), sort_keys=true) -%} +{{- value | replace('&', '&') | replace('<', '<') | replace('>', '>') -}} +{%- endmacro -%} +{{- '<|im_start|>user\n\n' -}} +{%- set has_images = state is sequence and state is not string and state is not mapping + and state | selectattr('type', 'defined') | selectattr('type', 'equalto', 'image') | list -%} +{%- if has_images -%} + {%- for part in state -%} + {%- if part.type == 'text' -%}{{- text(part.text) -}} + {%- elif part.type == 'image' -%}{{- '<|vision_start|><|image_pad|><|vision_end|>' -}} + {%- else -%}{{- raise_exception('Unsupported GS1 state item') -}}{%- endif -%} + {%- endfor -%} +{%- else -%}{{- text(state) -}}{%- endif -%} +{{- '\n\n\n' ~ text(question.instructions if question.instructions is not none else '') ~ '\n' -}} +{%- for option in question.options -%} + {{- '\n' -}} +{%- endfor -%} +{{- '<|im_end|>\n<|im_start|>assistant\n\n\n\n\n<|decide|><|mark|>' -}} +""" + + +@auto_docstring(checkpoint="bigai/GS1-9B") +@strict +class GS1Config(PreTrainedConfig): + r"""Configuration for the GS1 structured decision model. + + Args: + decision (`dict`, *optional*): GS1 routing and decision-head dimensions. + calibration (`dict`, *optional*): Calibration mode used by GS1 inference. + initialization_seed (`int`, *optional*, defaults to 12): Initialization seed stored with the checkpoint. + head_compute_dtype (`str`, *optional*, defaults to `"float32"`): Decision-head compute dtype. + structural_token_ids (`dict`, *optional*): IDs of the seven GS1 structural tokens. + inference_limits (`dict`, *optional*): Maximum context, request, question, and branch sizes. + decision_brier_weight (`float`, *optional*, defaults to 1.0): Expected multiclass Brier coefficient. + """ + + model_type = "gs1" + sub_configs_defaults = { + "text_config": SubConfigSpec(config_class=AutoConfig, model_type="qwen3_5_text"), + "vision_config": SubConfigSpec(config_class=AutoConfig, model_type="qwen3_5_vision"), + } + + text_config: dict | PreTrainedConfig | None = None + vision_config: dict | PreTrainedConfig | None = None + image_token_id: int = 248056 + video_token_id: int = 248057 + vision_start_token_id: int = 248053 + vision_end_token_id: int = 248054 + tie_word_embeddings: bool = False + decision: dict = field(default_factory=dict) + calibration: dict = field(default_factory=dict) + initialization_seed: int = 12 + head_compute_dtype: str = "float32" + structural_token_ids: dict | None = None + inference_limits: dict = field(default_factory=dict) + decision_brier_weight: float = 1.0 + + def __post_init__(self, **kwargs): + if isinstance(self.vision_config, dict) and self.vision_config.get("model_type") == "qwen3_5": + self.vision_config = {**self.vision_config, "model_type": "qwen3_5_vision"} + super().__post_init__(**kwargs) + self.decision = {**GS1_DEFAULTS, **(self.decision or {})} + self.calibration = {"mode": "identity", "log_temperature_bound": math.log(20), **self.calibration} + if self.head_compute_dtype not in {"float32", "bfloat16"}: + raise ValueError("head_compute_dtype must be float32 or bfloat16") + if self.text_config.hidden_size % self.decision["cross_attention_heads"]: + raise ValueError("cross_attention_heads must divide the text hidden size") + self.tie_word_embeddings = False + self.text_config.use_cache = False + self.text_config._attn_implementation = "sdpa" + self.vision_config._attn_implementation = "sdpa" + + +@auto_docstring +@dataclass +class GS1DecisionOutput(ModelOutput): + r"""Output of GS1 structured candidate scoring. + + Args: + loss (`torch.FloatTensor` of shape `()`, *optional*): Mean GS1 decision training loss. + logits (`torch.FloatTensor` of shape `(total_options,)`): Candidate logits concatenated by question. + """ + + loss: torch.Tensor | None = None + logits: torch.Tensor | None = None + + +class GS1DecisionHead(nn.Module): + def __init__(self, config): + super().__init__() + decision = config.decision + hidden_size = config.text_config.hidden_size + width = decision["projection_size"] + heads = decision["cross_attention_heads"] + eps = decision["norm_eps"] + self.memory_norm = nn.LayerNorm(hidden_size, eps=eps) + self.memory_projection = nn.Linear(hidden_size, hidden_size, bias=False) + self.question_seed = nn.Linear(hidden_size, hidden_size, bias=False) + self.question_attention = nn.MultiheadAttention(hidden_size, heads, batch_first=True) + self.decision_projection = nn.Linear(hidden_size, hidden_size, bias=False) + self.question_projection = nn.Linear(hidden_size, hidden_size, bias=False) + self.question_evidence_projection = nn.Linear(hidden_size, hidden_size, bias=False) + self.context_norm = nn.LayerNorm(hidden_size, eps=eps) + self.option_projection = nn.Linear(hidden_size, hidden_size, bias=False) + self.condition_projection = nn.Linear(hidden_size, hidden_size, bias=False) + self.option_norm = nn.LayerNorm(hidden_size, eps=eps) + self.routing_attention = nn.ModuleList( + nn.MultiheadAttention(hidden_size, heads, batch_first=True) + for _ in range(decision["cross_attention_layers"]) + ) + self.routing_attention_norm = nn.ModuleList( + nn.LayerNorm(hidden_size, eps=eps) for _ in range(decision["cross_attention_layers"]) + ) + self.routing_ffn_in = nn.ModuleList( + nn.Linear(hidden_size, hidden_size) for _ in range(decision["cross_attention_layers"]) + ) + self.routing_ffn_out = nn.ModuleList( + nn.Linear(hidden_size, hidden_size) for _ in range(decision["cross_attention_layers"]) + ) + self.routing_output_norm = nn.ModuleList( + nn.LayerNorm(hidden_size, eps=eps) for _ in range(decision["cross_attention_layers"]) + ) + self.query_mlp_in = nn.Linear(hidden_size, hidden_size) + self.query_mlp_out = nn.Linear(hidden_size, width) + self.key_mlp_in = nn.Linear(hidden_size, hidden_size) + self.key_mlp_out = nn.Linear(hidden_size, width) + self.query_norm = nn.LayerNorm(width, eps=eps) + self.key_norm = nn.LayerNorm(width, eps=eps) + self.projection_size = width + self.bf16_compute = config.head_compute_dtype == "bfloat16" + + def forward(self, state, question, decision, options): + dtype = torch.bfloat16 if self.bf16_compute else self.memory_projection.weight.dtype + with torch.autocast(device_type=state.device.type, dtype=torch.bfloat16, enabled=self.bf16_compute): + state, question, decision, options = (value.to(dtype) for value in (state, question, decision, options)) + memory = self.memory_projection(self.memory_norm(state)).unsqueeze(0) + query = self.question_seed(question)[None, None] + with sdpa_kernel([SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION]): + evidence = self.question_attention(query, memory, memory, need_weights=False)[0][0, 0] + context = self.context_norm( + self.decision_projection(decision) + + self.question_projection(question) + + self.question_evidence_projection(evidence) + ) + routed = self.option_norm(self.option_projection(options) + self.condition_projection(context)) + for attention, attention_norm, ffn_in, ffn_out, output_norm in zip( + self.routing_attention, + self.routing_attention_norm, + self.routing_ffn_in, + self.routing_ffn_out, + self.routing_output_norm, + strict=True, + ): + with sdpa_kernel([SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION]): + evidence = attention(routed[None], memory, memory, need_weights=False)[0][0] + updated = attention_norm(routed + evidence) + routed = output_norm(updated + ffn_out(F.gelu(ffn_in(updated)))) + query = self.query_norm(self.query_mlp_out(F.gelu(self.query_mlp_in(context)))) + keys = self.key_norm(self.key_mlp_out(F.gelu(self.key_mlp_in(routed)))) + with torch.autocast(device_type=state.device.type, enabled=False): + return (keys.float() @ query.float()) / math.sqrt(self.projection_size) + + +class FADepthRouter(nn.Module): + def __init__(self, hidden_size, eps): + super().__init__() + self.query = nn.Parameter(torch.zeros(hidden_size)) + self.eps = eps + + def forward(self, carry, sources): + values = torch.stack(sources).float() + keys = values * torch.rsqrt(values.square().mean(-1, keepdim=True) + self.eps) + alpha = torch.einsum("d,nbtd->nbt", self.query.float(), keys).softmax(dim=0) + correction = torch.einsum("nbt,nbtd->btd", (alpha - 1 / len(sources)) * len(sources), values) + return (carry.float() + correction).to(carry.dtype) + + +class GS1DecoderLayer(nn.Module): + """Reuse Qwen3.5 projections and kernels with GS1's residual topology.""" + + def __init__(self, source): + super().__init__() + self.block_type = source.block_type + self.input_layernorm = source.input_layernorm + self.post_attention_layernorm = source.post_attention_layernorm + self.mlp = source.mlp + if self.block_type == "full_attention": + self.self_attn = source.self_attn + else: + self.linear_attn = source.linear_attn + + +class GS1TextModel(nn.Module): + def __init__(self, config): + super().__init__() + text, decision = config.text_config, config.decision + self.config = config + self.full_layers = tuple(i for i, kind in enumerate(text.layer_types) if kind == "full_attention") + backbone = AutoModel.from_config(text) + self.layers = nn.ModuleList(GS1DecoderLayer(layer) for layer in backbone.layers) + self.embed_tokens = backbone.embed_tokens + self.norm = backbone.norm + self.rotary_emb = backbone.rotary_emb + self.gradient_checkpointing = False + self._gradient_checkpointing_func = checkpoint + receivers = decision["attnres_layers"] or self.full_layers + self.attnres_routers = nn.ModuleDict( + { + str(i): FADepthRouter(text.hidden_size, decision["attnres_eps"]) + for i in receivers + if decision["attnres"] + } + ) + + @staticmethod + def _run_layer(layer, carry, positional, mask, read, valid): + if layer.block_type == "full_attention": + mixed = layer.self_attn(layer.input_layernorm(read), position_embeddings=positional, attention_mask=mask)[ + 0 + ] + else: + mixed = layer.linear_attn(hidden_states=layer.input_layernorm(carry), attention_mask=valid) + hidden = carry + mixed + ffn = layer.mlp(layer.post_attention_layernorm(hidden)) + return hidden + ffn, mixed, ffn + + def forward(self, inputs_embeds, position_ids, roles, attention_mask): + batch, length = inputs_embeds.shape[:2] + valid = attention_mask.bool() + if not valid[:, -1].all() or (valid[:, :-1] & ~valid[:, 1:]).any(): + raise ValueError("GS1 requires left-padded nonempty sequences") + keep = valid.unsqueeze(-1) + hidden = inputs_embeds * keep + eye = torch.eye(length, dtype=torch.bool, device=hidden.device)[None] + selected = self.config.decision["bidirectional_layers"] or self.full_layers + bidirectional = self.config.decision["bidirectional"] + masks = {} + for value in {bidirectional and i in selected for i in self.full_layers}: + if value: + allowed = (roles[:, :, None] >= roles[:, None, :]) & (roles[:, None, :] != 3) + allowed |= eye + else: + allowed = torch.ones((batch, length, length), dtype=torch.bool, device=hidden.device).tril_() + allowed &= valid[:, None, :] + allowed |= ~valid[:, :, None] & eye + masks[value] = hidden.new_zeros((batch, 1, length, length)).masked_fill( + ~allowed[:, None], torch.finfo(hidden.dtype).min + ) + positional = self.rotary_emb(hidden, position_ids) + bank, partial = (hidden,), None + for index, layer in enumerate(self.layers): + read = ( + hidden + if str(index) not in self.attnres_routers + else self.attnres_routers[str(index)](hidden, bank if partial is None else (*bank, partial)) + ) + mask = masks.get(bidirectional and index in selected) + if self.training and self.gradient_checkpointing: + hidden, mixed, ffn = self._gradient_checkpointing_func( + self._run_layer, layer, hidden, positional, mask, read, valid + ) + else: + hidden, mixed, ffn = self._run_layer(layer, hidden, positional, mask, read, valid) + hidden, mixed, ffn = hidden * keep, mixed * keep, ffn * keep + if self.attnres_routers: + partial = mixed + ffn if partial is None else partial + mixed + ffn + if layer.block_type == "full_attention": + bank, partial = (*bank, partial), None + return self.norm(hidden) * keep + + +@auto_docstring +class GS1PreTrainedModel(PreTrainedModel): + config: GS1Config + base_model_prefix = "language_model" + supports_gradient_checkpointing = True + _no_split_modules = ["GS1DecoderLayer"] + _supports_flash_attn = True + _supports_sdpa = True + _keys_to_ignore_on_load_unexpected = [r"^mtp.*"] + _can_record_outputs = {"hidden_states": GS1DecoderLayer, "attentions": "self_attn"} + _is_stateful = True + + def _init_weights(self, module): + super()._init_weights(module) + if isinstance(module, nn.LayerNorm): + init.ones_(module.weight) + if module.bias is not None: + init.zeros_(module.bias) + elif isinstance(module, FADepthRouter): + init.zeros_(module.query) + + +@auto_docstring(checkpoint="bigai/GS1-9B") +class GS1ForDecision(decision.DecisionMixin, GS1PreTrainedModel): + accepts_loss_kwargs = False + + def __init__(self, config: GS1Config): + super().__init__(config) + self._newline_token_ids = () + self.language_model = GS1TextModel(config) + self.visual = AutoModel.from_config(config.vision_config) + self.decision_head = GS1DecisionHead(config) + if config.calibration["mode"] == "scalar_temperature": + self.calibration_beta = nn.Parameter(torch.zeros(())) + self.post_init() + + def get_input_embeddings(self): + return self.language_model.embed_tokens + + def set_input_embeddings(self, value): + self.language_model.embed_tokens = value + + def _decision_rows(self, input_ids, attention_mask): + names = ("", "", "", "", "", "<|decide|>") + try: + marker_ids = [self.config.structural_token_ids[name] for name in names] + except (TypeError, KeyError) as error: + raise ValueError("GS1 config must define all seven structural token IDs") from error + metadata, role_rows = [], [] + newline = self._newline_token_ids + for row, ids in enumerate(input_ids): + begin = int((~attention_mask[row].bool()).sum()) + values = ids[begin:] + + def find(token): + return torch.where(values == token)[0].tolist() + + state_starts, state_ends = find(marker_ids[0]), find(marker_ids[1]) + question_starts, question_ends = find(marker_ids[2]), find(marker_ids[3]) + option_starts, option_ends = find(marker_ids[4]), find(marker_ids[5]) + decisions = find(marker_ids[6]) + if not ( + len(state_starts) + == len(state_ends) + == len(question_starts) + == len(question_ends) + == len(decisions) + == 1 + ): + raise ValueError("A GS1 prompt needs one state, question, and decision marker") + if not option_starts or len(option_starts) != len(option_ends): + raise ValueError("GS1 prompt candidate markers are incomplete") + q0, q1, decision = question_starts[0], question_ends[0], decisions[0] + markers = [state_starts[0], state_ends[0], q0, q1] + markers.extend(pos for pair in zip(option_starts, option_ends, strict=True) for pos in pair) + markers.append(decision) + if any(left >= right for left, right in zip(markers, markers[1:])): + raise ValueError("GS1 prompt markers are out of order") + roles = torch.full_like(values, -1) + roles[:q0], roles[q0 : option_starts[0]], roles[option_starts[0] : decision], roles[decision] = 0, 1, 2, 3 + + def span(start, end): + start += 1 + if newline and tuple(values[start : start + len(newline)].tolist()) == newline: + start += len(newline) + if newline and tuple(values[end - len(newline) : end].tolist()) == newline: + end -= len(newline) + return (end, end + 1) if start >= end else (start, end) + + metadata.append( + ( + begin, + state_starts[0], + q0, + q1, + decision, + span(q0, q1), + option_starts, + option_ends, + [span(a, b) for a, b in zip(option_starts, option_ends, strict=True)], + ) + ) + role_rows.append(F.pad(roles, (begin, 0), value=-1)) + return metadata, torch.stack(role_rows) + + @staticmethod + def _pool_span(sequence, start, end, span): + return torch.stack((sequence[start], sequence[span[0] : span[1]].mean(0), sequence[end])).mean(0) + + def _vision_positions(self, input_ids, token_types, image_grid_thw): + positions = torch.zeros(3, *input_ids.shape, device=input_ids.device, dtype=torch.long) + grids = iter(image_grid_thw) + merge = self.config.vision_config.spatial_merge_size + for row in range(input_ids.shape[0]): + begin = offset = 0 + for kind, group in groupby(token_types[row].tolist()): + end = begin + sum(1 for _ in group) + if kind == 0: + part = torch.arange(end - begin, device=input_ids.device)[None].expand(3, -1) + offset + offset += end - begin + else: + t, h, w = map(int, next(grids)) + h, w = h // merge, w // merge + part = torch.stack( + ( + torch.full((t * h * w,), offset, device=input_ids.device), + torch.arange(offset, offset + h, device=input_ids.device).repeat_interleave(w * t), + torch.arange(offset, offset + w, device=input_ids.device).repeat(h * t), + ) + ) + offset += max(h, w) + positions[:, row, begin:end] = part + begin = end + return positions + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor, + attention_mask: torch.Tensor | None = None, + marks: torch.LongTensor | None = None, + num_options: torch.LongTensor | None = None, + question_type_ids: torch.LongTensor | None = None, + labels: torch.Tensor | None = None, + loss_weights: torch.Tensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_thw: torch.LongTensor | None = None, + mm_token_type_ids: torch.LongTensor | None = None, + **kwargs, + ) -> GS1DecisionOutput: + r""" + Args: + marks (`torch.LongTensor`, *optional*): Decision-marker positions produced by the decision input formatter. + num_options (`torch.LongTensor`, *optional*): Candidate count for each logical question. + question_type_ids (`torch.LongTensor`, *optional*): Encoded decision question types. + labels (`torch.FloatTensor`, *optional*): Flat concatenation of soft target distributions. + loss_weights (`torch.FloatTensor`, *optional*): Per-question objective weights. + pixel_values (`torch.FloatTensor`, *optional*): Processed image patches for visual states. + image_grid_thw (`torch.LongTensor`, *optional*): Temporal and spatial image grid sizes. + mm_token_type_ids (`torch.LongTensor`, *optional*): Text/image token type IDs. + """ + if attention_mask is None: + attention_mask = torch.ones_like(input_ids) + metadata, roles = self._decision_rows(input_ids, attention_mask) + hidden = self.get_input_embeddings()(input_ids) + position_ids = (attention_mask.long().cumsum(-1) - 1).clamp_min(0) + if pixel_values is not None: + features = self.visual( + pixel_values.to(self.visual.dtype), grid_thw=image_grid_thw, return_dict=True + ).pooler_output.to(hidden.device, hidden.dtype) + image_mask = (input_ids == self.config.image_token_id).unsqueeze(-1).expand_as(hidden) + if hidden[image_mask].numel() != features.numel(): + raise ValueError("Image feature count differs from GS1 image markers") + hidden = hidden.masked_scatter(image_mask, features) + if mm_token_type_ids is None: + raise ValueError("GS1 vision inputs require mm_token_type_ids") + position_ids = self._vision_positions(input_ids, mm_token_type_ids, image_grid_thw) + hidden = self.language_model(hidden, position_ids, roles, attention_mask) + logits = [] + for row, (begin, state_start, q0, q1, decision_position, qspan, starts, ends, spans) in enumerate(metadata): + sequence = hidden[row, begin:] + question = self._pool_span(sequence, q0, q1, qspan) + options = torch.stack( + [ + self._pool_span(sequence, start, end, span) + for start, end, span in zip(starts, ends, spans, strict=True) + ] + ) + logits.append(self.decision_head(sequence[state_start:q0], question, sequence[decision_position], options)) + logits = torch.cat(logits) + loss = None + if labels is not None: + option_counts = torch.tensor([len(row[-1]) for row in metadata], device=logits.device) + loss = self.loss_function( + logits=logits, + labels=labels, + num_options=option_counts, + loss_weights=loss_weights, + brier_weight=self.config.decision_brier_weight, + **kwargs, + ) + return GS1DecisionOutput(loss=loss, logits=logits) + + def post_init(self): + super().post_init() + self.decision_config = decision.configuration_utils.DecisionConfig( + chat_template=GS1_TEMPLATE, sanitize_control_tokens=True, noul_options=["false", "true"] + ) + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs): + result = super().from_pretrained(pretrained_model_name_or_path, *args, **kwargs) + model = result[0] if isinstance(result, tuple) else result + from ... import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained( + pretrained_model_name_or_path, **decision.modeling_utils._hub_kwargs(kwargs) + ) + model._newline_token_ids = tuple(tokenizer.encode("\n", add_special_tokens=False)) + if model.decision_config.chat_template is None: + model.decision_config.chat_template = GS1_TEMPLATE + model.decision_config.noul_options = ["false", "true"] + return result + + +__all__ = ["GS1Config", "GS1PreTrainedModel", "GS1ForDecision"] diff --git a/tests/models/gs1/test_modeling_gs1.py b/tests/models/gs1/test_modeling_gs1.py new file mode 100644 index 000000000000..c8b93dc27d00 --- /dev/null +++ b/tests/models/gs1/test_modeling_gs1.py @@ -0,0 +1,113 @@ +# 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 unittest + +import torch + +from transformers import GS1Config, GS1ForDecision, pipeline +from transformers.loss.loss_gs1 import GS1ForDecisionLoss +from transformers.testing_utils import slow, torch_device + + +class GS1DecisionLossTest(unittest.TestCase): + all_model_classes = (GS1ForDecision,) + + def test_hybrid_backbone_with_activation_checkpointing(self): + markers = ("", "", "", "", "", "<|decide|>") + config = GS1Config( + text_config={ + "vocab_size": 32, + "hidden_size": 32, + "intermediate_size": 64, + "num_hidden_layers": 2, + "layer_types": ["linear_attention", "full_attention"], + "num_attention_heads": 4, + "num_key_value_heads": 2, + "head_dim": 8, + "linear_num_key_heads": 2, + "linear_num_value_heads": 4, + "linear_key_head_dim": 8, + "linear_value_head_dim": 8, + }, + vision_config={"depth": 1, "hidden_size": 32, "intermediate_size": 64, "num_heads": 4}, + decision={"projection_size": 16}, + structural_token_ids=dict(zip(markers, range(1, 8), strict=True)), + ) + model = GS1ForDecision(config).train() + model.activation_checkpointing_enable(activation_checkpointing_kwargs={"use_reentrant": False}) + input_ids = torch.tensor([[1, 9, 2, 3, 9, 4, 5, 9, 6, 5, 10, 6, 7]]) + output = model(input_ids, labels=torch.tensor([0.25, 0.75])) + self.assertEqual(output.logits.shape, (2,)) + self.assertTrue(torch.isfinite(output.loss)) + output.loss.backward() + self.assertTrue(torch.isfinite(model.get_input_embeddings().weight.grad).all()) + + def test_loss_matches_distribution_nll_and_expected_brier(self): + logits = torch.tensor([0.2, -0.1, 1.0, 0.5, -0.5], requires_grad=True) + labels = torch.tensor([0.75, 0.25, 0.2, 0.3, 0.5]) + counts = torch.tensor([2, 3]) + weights = torch.tensor([2.0, 0.5]) + + loss = GS1ForDecisionLoss( + logits, + labels, + counts, + loss_weights=weights, + brier_weight=0.25, + ) + + expected = [] + offset = 0 + for count, weight in zip((2, 3), weights, strict=True): + scores = logits[offset : offset + count] + target = labels[offset : offset + count] + probability = scores.softmax(-1) + nll = -(target * scores.log_softmax(-1)).sum() + brier = (probability - target).square().sum() + 1 - target.square().sum() + expected.append((nll + 0.25 * brier) * weight) + offset += count + torch.testing.assert_close(loss, torch.stack(expected).mean()) + + loss.backward() + self.assertTrue(torch.isfinite(logits.grad).all()) + + +class GS1IntegrationTest(unittest.TestCase): + @slow + def test_published_checkpoint_decision_pipeline(self): + checkpoint = "bigai/GS1-0.8B" + model, loading_info = GS1ForDecision.from_pretrained(checkpoint, output_loading_info=True) + for name in ("missing_keys", "unexpected_keys", "mismatched_keys"): + self.assertFalse(loading_info[name]) + decide = pipeline("decision", model=model, tokenizer=checkpoint, device=torch_device) + answers = decide( + { + "state": "My package arrived damaged. Please send a replacement.", + "questions": { + "resolution": { + "type": "choice", + "instructions": "What does the customer want?", + "criteria": {"refund": "A refund", "replacement": "A replacement"}, + }, + "damage": {"type": "noul", "instructions": "Was the package damaged?"}, + }, + } + ) + self.assertEqual(answers["resolution"]["choice"], "replacement") + self.assertGreater(answers["damage"]["noul"], 0.5) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/check_config_attributes.py b/utils/check_config_attributes.py index a91a6124630b..87f61bba9025 100644 --- a/utils/check_config_attributes.py +++ b/utils/check_config_attributes.py @@ -42,6 +42,10 @@ # Usually of small list of allowed attrs, but can be True to allow all SPECIAL_CASES_TO_ALLOW = { + "GS1Config": [ + "initialization_seed", # Checkpoint initialization metadata consumed by the GS1 training stack. + "inference_limits", # Request bounds consumed by the GS1 inference service. + ], "Dots3NoteAudioConfig": ["feature_size"], # used in __post_init__ to compute conv_output_size "NemotronH_Omni_Reasoning_V3_Config": [ "sound_context_token", # used by the processor for `