Skip to content
Open
Show file tree
Hide file tree
Changes from 6 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 @@ -723,6 +723,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
37 changes: 37 additions & 0 deletions docs/source/en/model_doc/gs1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<!--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.

-->

# GS1

GS1 is a family of pretrained models from BIGAI for structured decision tasks. Given a state and a question, GS1
Comment thread
jacklanda marked this conversation as resolved.
Resolved
scores the available candidates for Choice, Noul, and Score questions instead of generating a text answer.
Comment thread
jacklanda marked this conversation as resolved.
Resolved

The models use a Qwen3.5 hybrid text/vision backbone with GS1-specific bidirectional decision-context processing,
Comment thread
jacklanda marked this conversation as resolved.
Resolved
attention-residual routing, and a cross-attention decision head. The head reads the question and candidate spans from
the compiled request and returns one score per candidate.
Comment thread
jacklanda marked this conversation as resolved.
Resolved

| 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) |

GS1 is developed by [BIGAI](https://gs1.mybigai.ac.cn). See the [open-source implementation](https://github.com/bigai-nlco/GS1)
Comment thread
jacklanda marked this conversation as resolved.
Resolved
for the model and inference reference.
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 @@ -220,6 +220,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
2 changes: 2 additions & 0 deletions src/transformers/models/auto/auto_mappings.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@
("gemma4_assistant", "Gemma4AssistantConfig"),
("gemma4_audio", "Gemma4AudioConfig"),
("gemma4_text", "Gemma4TextConfig"),
("gs1", "GS1Config"),
("gemma4_unified", "Gemma4UnifiedConfig"),
("gemma4_unified_assistant", "Gemma4UnifiedAssistantConfig"),
("gemma4_unified_audio", "Gemma4UnifiedAudioConfig"),
Expand Down Expand Up @@ -1056,6 +1057,7 @@
("qwen3_5_moe_vision", "qwen3_5_moe"),
("qwen3_5_text", "qwen3_5"),
("qwen3_5_vision", "qwen3_5"),
("gs1", "gs1"),
("qwen3_asr_encoder", "qwen3_asr"),
("qwen3_omni_moe_audio_encoder", "qwen3_omni_moe"),
("qwen3_omni_moe_talker_code_predictor", "qwen3_omni_moe"),
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 @@ -2171,6 +2171,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__)
84 changes: 84 additions & 0 deletions src/transformers/models/gs1/configuration_gs1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# 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

import math
from dataclasses import field

from huggingface_hub.dataclasses import strict

from ...configuration_utils import PreTrainedConfig, SubConfigSpec
from ...utils import auto_docstring

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(model_type="qwen3_5_text"),
"vision_config": SubConfigSpec(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):
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


__all__ = ["GS1Config"]
Loading
Loading