Download inference/loading.py from jinbo2277/HybridRSC: direct link, hf CLI and curl.
- Browser
- Download file 3.59 kB
-
https://huggingface.co/jinbo2277/HybridRSC/resolve/main/inference/loading.py
- Command line
-
hf download hf://jinbo2277/HybridRSC/inference/loading.py
-
curl -L -o loading.py https://huggingface.co/jinbo2277/HybridRSC/resolve/main/inference/loading.py
3.59 kB
| """Load the paper's selected HybridRSC and comparison checkpoints.""" | |
| from pathlib import Path | |
| import torch | |
| from torch import nn | |
| from .hybridrsc import HybridRSC | |
| from .mixers import GatedLocalMixer | |
| class MeanHeads(nn.Module): | |
| def __init__(self, heads): | |
| super().__init__() | |
| self.heads = nn.ModuleList(heads) | |
| def forward(self, features): | |
| return (self.heads[0](features) + self.heads[1](features)) / 2 | |
| class NativeClassifier(nn.Module): | |
| def __init__(self, configuration): | |
| super().__init__() | |
| import timm | |
| native = timm.create_model( | |
| configuration["variant"], pretrained=False, num_classes=27, | |
| drop_path_rate=configuration.get("drop_path_rate", 0.1), | |
| ) | |
| if configuration["variant"] == "mobilevit_xs": | |
| self.head = native.head | |
| native.head = nn.Identity() | |
| else: | |
| heads = native.get_classifier() | |
| self.head = MeanHeads(heads) if isinstance(heads, tuple) else heads | |
| native.reset_classifier(0) | |
| self.backbone = native | |
| def forward(self, images): | |
| return self.head(self.backbone(images)) | |
| def _mamba_control(state): | |
| """Construct the row-scan controls using the installed mixer dependency.""" | |
| from mambavision.models import mamba_vision | |
| from mamba_ssm.ops.selective_scan_interface import selective_scan_fn, selective_scan_ref | |
| def scan(inputs, *args, **kwargs): | |
| implementation = selective_scan_fn if inputs.is_cuda else selective_scan_ref | |
| return implementation(inputs, *args, **kwargs) | |
| mamba_vision.selective_scan_fn = scan | |
| model = HybridRSC("M") | |
| for stage_index in (2, 3): | |
| for block_index, block in enumerate(model.backbone.levels[stage_index].blocks): | |
| prefix = f"backbone.levels.{stage_index}.blocks.{block_index}.mixer." | |
| if prefix + "A_log" in state: | |
| dim = 32 * 2 ** stage_index | |
| block.mixer = mamba_vision.MambaVisionMixer( | |
| d_model=dim, | |
| d_state=state[prefix + "A_log"].shape[1], | |
| d_conv=state[prefix + "conv1d_x.weight"].shape[-1], | |
| expand=state[prefix + "in_proj.weight"].shape[0] / dim, | |
| dt_rank=state[prefix + "dt_proj.weight"].shape[1], | |
| ) | |
| return model | |
| def load_checkpoint(path, device="cpu"): | |
| """Return an evaluation model with a tensor of 27 logits per crop. | |
| Mamba controls B/C/D use installed mambavision and mamba-ssm packages. | |
| """ | |
| checkpoint = torch.load(Path(path), map_location="cpu", weights_only=True) | |
| configuration = checkpoint["config"]["model"] | |
| state = checkpoint["model"] | |
| if configuration.get("variant") != "road_hybrid": | |
| model = NativeClassifier(configuration) | |
| elif any(".mixer.A_log" in name for name in state): | |
| model = _mamba_control(state) | |
| else: | |
| widths = {20: "T", 24: "S", 32: "M", 48: "L"} | |
| width = state["backbone.patch_embed.conv_down.3.weight"].shape[0] | |
| model = HybridRSC(widths[width]) | |
| for stage_index in (2, 3): | |
| for block_index, block in enumerate(model.backbone.levels[stage_index].blocks): | |
| prefix = f"backbone.levels.{stage_index}.blocks.{block_index}.mixer." | |
| if prefix + "input.weight" in state and not isinstance(block.mixer, GatedLocalMixer): | |
| block.mixer = GatedLocalMixer(width * 2 ** stage_index, 56 // 2 ** stage_index) | |
| model.load_state_dict(state, strict=True) | |
| return model.to(device).eval() | |