Download runtime/src/pixelone/attention.py from KangHui2200/PixelOne: direct link, hf CLI and curl.
- Browser
- Download file 1.48 kB
-
https://huggingface.co/KangHui2200/PixelOne/resolve/main/runtime/src/pixelone/attention.py
- Command line
-
hf download hf://KangHui2200/PixelOne/runtime/src/pixelone/attention.py
-
curl -L -o attention.py https://huggingface.co/KangHui2200/PixelOne/resolve/main/runtime/src/pixelone/attention.py
1.48 kB
| """Bidirectional masks for existing full-attention layers only.""" | |
| from contextlib import contextmanager | |
| import torch | |
| def bidirectional_mask(config, inputs_embeds, attention_mask=None, past_key_values=None, **kwargs): | |
| if past_key_values is not None: | |
| raise ValueError('Bidirectional inference does not support autoregressive KV caches') | |
| if config._attn_implementation not in ('sdpa', 'eager'): | |
| raise ValueError('Bidirectional full layers currently require SDPA or eager attention') | |
| batch, length = inputs_embeds.shape[:2] | |
| if attention_mask is None: | |
| valid = torch.ones((batch, length), device=inputs_embeds.device, dtype=torch.bool) | |
| else: | |
| if attention_mask.shape != (batch, length): | |
| raise ValueError('Expected independent per-sample 2D padding mask') | |
| valid = attention_mask.to(device=inputs_embeds.device, dtype=torch.bool) | |
| mask = torch.zeros((batch, 1, 1, length), device=inputs_embeds.device, dtype=inputs_embeds.dtype) | |
| return mask.masked_fill(~valid[:, None, None, :], torch.finfo(inputs_embeds.dtype).min) | |
| def full_layer_attention(module, mode): | |
| if mode == 'causal': | |
| yield | |
| return | |
| if mode != 'bidirectional_full_layers': | |
| raise ValueError('Unknown attention mode: ' + mode) | |
| original = module.create_causal_mask | |
| module.create_causal_mask = bidirectional_mask | |
| try: | |
| yield | |
| finally: | |
| module.create_causal_mask = original | |