Datasets:
Download model_scripts/stnn/patchstg/timm_fallback.py from tjtrans/Traffic-Demand-Bench: direct link, hf CLI and curl.
- Browser
- Download file 1.56 kB
-
https://huggingface.co/datasets/tjtrans/Traffic-Demand-Bench/resolve/main/model_scripts/stnn/patchstg/timm_fallback.py
- Command line
-
hf download hf://datasets/tjtrans/Traffic-Demand-Bench/model_scripts/stnn/patchstg/timm_fallback.py
-
curl -L -o timm_fallback.py https://huggingface.co/datasets/tjtrans/Traffic-Demand-Bench/resolve/main/model_scripts/stnn/patchstg/timm_fallback.py
1.56 kB
| """Minimal Attention / Mlp matching timm.models.vision_transformer (old API). | |
| Used only if `timm` is not installed. Same call signature PatchSTG expects. | |
| """ | |
| import torch.nn as nn | |
| class Attention(nn.Module): | |
| def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0.0, proj_drop=0.0): | |
| super().__init__() | |
| self.num_heads = num_heads | |
| self.scale = (dim // num_heads) ** -0.5 | |
| self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) | |
| self.attn_drop = nn.Dropout(attn_drop) | |
| self.proj = nn.Linear(dim, dim) | |
| self.proj_drop = nn.Dropout(proj_drop) | |
| def forward(self, x): | |
| b, n, c = x.shape | |
| qkv = self.qkv(x).reshape(b, n, 3, self.num_heads, c // self.num_heads) | |
| qkv = qkv.permute(2, 0, 3, 1, 4) | |
| q, k, v = qkv[0], qkv[1], qkv[2] | |
| attn = self.attn_drop((q @ k.transpose(-2, -1) * self.scale).softmax(dim=-1)) | |
| x = (attn @ v).transpose(1, 2).reshape(b, n, c) | |
| return self.proj_drop(self.proj(x)) | |
| class Mlp(nn.Module): | |
| def __init__(self, in_features, hidden_features=None, act_layer=nn.GELU, drop=0.0): | |
| super().__init__() | |
| hidden_features = hidden_features or in_features | |
| self.fc1 = nn.Linear(in_features, hidden_features) | |
| self.act = act_layer() | |
| self.drop1 = nn.Dropout(drop) | |
| self.fc2 = nn.Linear(hidden_features, in_features) | |
| self.drop2 = nn.Dropout(drop) | |
| def forward(self, x): | |
| return self.drop2(self.fc2(self.drop1(self.act(self.fc1(x))))) | |