Skip to content
Merged
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
11 changes: 8 additions & 3 deletions src/mcore_bridge/model/gpts/glm_moe_dsa.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Copyright (c) ModelScope Contributors. All rights reserved.
import megatron.core
import torch
from contextlib import contextmanager
from packaging import version
from typing import Optional

from ..constant import ModelType
Expand All @@ -15,6 +17,8 @@
except ImportError:
DSAttention = object

mcore_019 = version.parse(megatron.core.__version__) >= version.parse('0.19.0rc0')


class GlmMoeDsaDSAttention(DSAttention):
"""DSAttention with shared indexer support for GLM 5.2.
Expand Down Expand Up @@ -86,12 +90,13 @@ def forward(
if self.training and torch.is_grad_enabled():
q, k, weights = self.indexer.forward_before_topk(x, qr, packed_seq_params)
indexer_loss_coeff = getattr(self.config, 'dsa_indexer_loss_coeff', 0.0)

kwargs = {}
if mcore_019:
kwargs['calculate_per_token_loss'] = self.config.calculate_per_token_loss

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using getattr(self.config, 'calculate_per_token_loss', False) is safer and more robust than direct attribute access. This prevents potential AttributeError if self.config is a mock object in unit tests or a custom configuration class that does not define calculate_per_token_loss.

Suggested change
kwargs['calculate_per_token_loss'] = self.config.calculate_per_token_loss
kwargs['calculate_per_token_loss'] = getattr(self.config, 'calculate_per_token_loss', False)

topk_indices, indexer_loss = FusedDSAIndexerLoss.apply(
q, weights, k, query.detach(), key.detach(), self.softmax_scale,
self.indexer.index_topk, indexer_loss_coeff, float_mask,
getattr(self.config, 'dsa_indexer_use_sparse_loss',
False), self.indexer.pg_collection, self.config.calculate_per_token_loss)
getattr(self.config, 'dsa_indexer_use_sparse_loss', False), self.indexer.pg_collection, **kwargs)
if indexer_loss_coeff > 0:
DSAIndexerLossLoggingHelper.save_loss_to_tracker(
loss=indexer_loss,
Expand Down
Loading