Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/source/en/_toctree.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
70 changes: 70 additions & 0 deletions docs/source/en/model_doc/gs1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<!--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.

⚠️ Note that this file is in Markdown but contains specific syntax for the doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.

-->
*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
7 changes: 7 additions & 0 deletions src/transformers/conversion_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
7 changes: 5 additions & 2 deletions src/transformers/decision/modeling_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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())
)
Expand Down
54 changes: 54 additions & 0 deletions src/transformers/loss/loss_gs1.py
Original file line number Diff line number Diff line change
@@ -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"]
2 changes: 2 additions & 0 deletions src/transformers/loss/loss_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -185,6 +186,7 @@ def ForSemanticSegmentationLoss(
"ForObjectDetection": ForObjectDetectionLoss,
"ForCTC": ForCTCLoss,
"ForConditionalGeneration": ForCausalLMLoss,
"ForDecision": GS1ForDecisionLoss,
"DeformableDetrForObjectDetection": DeformableDetrForObjectDetectionLoss,
"ConditionalDetrForObjectDetection": DeformableDetrForObjectDetectionLoss,
"DabDetrForObjectDetection": DeformableDetrForObjectDetectionLoss,
Expand Down
1 change: 1 addition & 0 deletions src/transformers/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 *
Expand Down
1 change: 1 addition & 0 deletions src/transformers/models/auto/auto_mappings.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@
("groupvit", "GroupViTConfig"),
("groupvit_text_model", "GroupViTTextConfig"),
("groupvit_vision_model", "GroupViTVisionConfig"),
("gs1", "GS1Config"),
("gte", "GteConfig"),
("helium", "HeliumConfig"),
("hgnet_v2", "HGNetV2Config"),
Expand Down
1 change: 1 addition & 0 deletions src/transformers/models/auto/modeling_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
27 changes: 27 additions & 0 deletions src/transformers/models/gs1/__init__.py
Original file line number Diff line number Diff line change
@@ -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__)
96 changes: 96 additions & 0 deletions src/transformers/models/gs1/configuration_gs1.py
Original file line number Diff line number Diff line change
@@ -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"]
Loading
Loading