MCPcopy Create free account
hub / github.com/OpenBitSys/BitDistiller / forward

Method forward

inference/modules/fused_attn.py:99–163  ·  view source on GitHub ↗

Input shape: Batch x Time x Channel

(
        self,
        hidden_states,
        past_key_value=None,
        attention_mask=None,
        position_ids=None,
        output_attentions=False,
        use_cache=False,
    )

Source from the content-addressed store, hash-verified

97 )
98
99 def forward(
100 self,
101 hidden_states,
102 past_key_value=None,
103 attention_mask=None,
104 position_ids=None,
105 output_attentions=False,
106 use_cache=False,
107 ):
108 """Input shape: Batch x Time x Channel"""
109
110 bsz, q_len, _ = hidden_states.size()
111
112 qkv_states = self.qkv_proj(hidden_states)
113 qkv_states = qkv_states.view(bsz, q_len, 3, self.num_heads, self.head_dim)
114
115 # This updates the query and key states in-place, saving VRAM.
116 query_states, key_states, value_states = torch.split(qkv_states, 1, dim=2)
117 query_states, key_states = self.rotary_emb(
118 query_states, key_states, position_ids
119 )
120
121 del qkv_states
122 query_states = query_states.view(
123 bsz, q_len, self.num_heads, self.head_dim
124 ).transpose(1, 2)
125 key_states = key_states.view(
126 bsz, q_len, self.num_heads, self.head_dim
127 ).transpose(1, 2)
128 value_states = value_states.view(
129 bsz, q_len, self.num_heads, self.head_dim
130 ).transpose(1, 2)
131
132 is_causal = past_key_value is None
133
134 kv_seq_len = q_len
135 if past_key_value is not None:
136 kv_seq_len += past_key_value[0].shape[-2]
137
138 value_states = value_states.to("cuda:0")
139
140 if past_key_value is not None:
141 # reuse k, v, self_attention
142 key_states = torch.cat([past_key_value[0], key_states], dim=2)
143 value_states = torch.cat([past_key_value[1], value_states], dim=2)
144
145 if use_cache:
146 # Since qkv_proj is fused, query_states etc will hold a reference to the original qkv_states tensor
147 # which can cause excessive memory usage by the cache. `contiguous` is a convenient way to workaround this.
148 key_states = key_states.contiguous()
149 value_states = value_states.contiguous()
150 query_states = query_states.contiguous()
151
152 past_key_value = (key_states, value_states) if use_cache else None
153
154 # with torch.backends.cuda.sdp_kernel(enable_math=False):
155 attn_output = F.scaled_dot_product_attention(
156 query_states, key_states, value_states, is_causal=is_causal

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected