Download runtime/src/pixelone/runtime.py from KangHui2200/PixelOne: direct link, hf CLI and curl.
- Browser
- Download file 2.3 kB
-
https://huggingface.co/KangHui2200/PixelOne/resolve/main/runtime/src/pixelone/runtime.py
- Command line
-
hf download hf://KangHui2200/PixelOne/runtime/src/pixelone/runtime.py
-
curl -L -o runtime.py https://huggingface.co/KangHui2200/PixelOne/resolve/main/runtime/src/pixelone/runtime.py
2.3 kB
| from contextlib import ExitStack, contextmanager | |
| from importlib import import_module | |
| import torch | |
| from pixelone.attention import full_layer_attention | |
| from pixelone.kernels import qwen_kernel_backend | |
| def native_runtime(backend='torch', required_model=None, attention_mode='causal'): | |
| with ExitStack() as stack: | |
| for name in ('qwen3_5', 'qwen3_5_moe'): | |
| module = import_module(f'transformers.models.{name}.modeling_{name}') | |
| stack.enter_context(full_layer_attention(module, attention_mode)) | |
| runtime = stack.enter_context(qwen_kernel_backend(backend, module)) | |
| if backend == 'native' and (required_model is None or name == required_model): | |
| missing = [key for key, enabled in runtime['optional_kernels_enabled'].items() if not enabled] | |
| if missing: | |
| raise RuntimeError('Native Qwen kernels unavailable: ' + ', '.join(missing) + | |
| '. Install compatible flash-linear-attention and causal-conv1d in the active Python environment; ' | |
| 'use kernel_backend=torch only for an explicitly labelled baseline.') | |
| decoder = getattr(module, 'Qwen3_5DecoderLayer' if name == 'qwen3_5' else 'Qwen3_5MoeDecoderLayer') | |
| if not hasattr(decoder, 'block_type'): | |
| decoder.block_type = property(lambda layer: layer.layer_type) | |
| yield | |
| def cast_training_inputs(module, args, kwargs): | |
| from torch.utils._pytree import tree_map | |
| def cast(value): | |
| return value.to(torch.bfloat16) if isinstance(value, torch.Tensor) and value.is_floating_point() else value | |
| return tree_map(cast, args), tree_map(cast, kwargs) | |
| def inference_precision(model, recipe, precision): | |
| if precision != 'training_cuda': | |
| return | |
| blocks = list(model.native.backbone.language_model.layers) | |
| if recipe['train_vision']: | |
| blocks += list(model.native.backbone.visual.blocks) | |
| for block in blocks: | |
| block.register_forward_pre_hook(cast_training_inputs, with_kwargs=True) | |
| for module in block.modules(): | |
| for name, buffer in module.named_buffers(recurse=False): | |
| if buffer.is_floating_point(): | |
| setattr(module, name, buffer.to(torch.bfloat16)) | |