File size: 2,297 Bytes
d3b61f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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


@contextmanager
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))