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

Method forward

inference/models/falcon.py:128–208  ·  view source on GitHub ↗
(
        self,
        x: torch.Tensor,
        start_pos: int,
        mask: Optional[torch.Tensor],
    )

Source from the content-addressed store, hash-verified

126 self.rotary_emb = RotaryEmbedding(self.head_dim)
127
128 def forward(
129 self,
130 x: torch.Tensor,
131 start_pos: int,
132 mask: Optional[torch.Tensor],
133 ):
134 bsz, seqlen, _ = x.shape
135
136 xqkv = self.query_key_value(x)
137 xqkv = xqkv.view(bsz, seqlen, self.n_local_heads + 2, self.head_dim)
138 xq = xqkv[:, :, :-2]
139 xk = xqkv[:, :, [-2]]
140 xv = xqkv[:, :, [-1]]
141
142 if seqlen > 1:
143 xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
144 xk = xk.view(bsz, seqlen, 1, self.head_dim)
145 xv = xv.view(bsz, seqlen, 1, self.head_dim)
146
147 xq, xk = self.rotary_emb(xq, xk)
148 xq = (
149 xq.reshape(bsz, self.n_local_heads, seqlen, self.head_dim)
150 .permute(0, 2, 1, 3)
151 .contiguous()
152 )
153 xk = (
154 xk.reshape(bsz, 1, seqlen, self.head_dim)
155 .permute(0, 2, 1, 3)
156 .contiguous()
157 )
158
159 self.cache_k = self.cache_k.to(xq)
160 self.cache_v = self.cache_v.to(xq)
161
162 values_store = xv.transpose(2, 1)
163 keys_store = (
164 xk.reshape(bsz, seqlen, 1, self.head_dim // 8, 8)
165 .permute(0, 2, 3, 1, 4)
166 .contiguous()
167 )
168
169 self.cache_v[:bsz, :, start_pos : start_pos + seqlen, :] = values_store
170 self.cache_k[:bsz, :, :, start_pos : start_pos + seqlen, :] = keys_store
171
172 keys = xk
173 values = xv
174
175 xq = xq.transpose(1, 2)
176 keys = keys.transpose(1, 2)
177 values = values.transpose(1, 2)
178 scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim)
179 if mask is not None:
180 scores = scores + mask # (bs, n_local_heads, slen, cache_len + slen)
181 scores = F.softmax(scores.float(), dim=-1).type_as(xq)
182 output = torch.matmul(scores, values) # (bs, n_local_heads, slen, head_dim)
183 output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
184 else:
185 # xq = xq[:, 0, :, :]

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected