File size: 3,338 Bytes
9c890d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.

"""Step-dependent UCPE transition and evaluation restoration."""

from __future__ import annotations

import logging
import math
from dataclasses import dataclass

import torch
from torch import nn

from nets.ucpe_cd50.ucpe_transition import RelativeRayAttention

logger: logging.Logger = logging.getLogger(__name__)


@dataclass
class UCPETransitionConfig:
    start_step: int = 0
    warmup_steps: int = 1000

    def validate(self) -> None:
        if self.start_step < 0 or self.warmup_steps <= 0:
            raise ValueError(
                "UCPE transition requires nonnegative start and positive warmup"
            )

    def validate_trainer(self, trainer: object) -> None:
        self.validate()
        encoder = getattr(trainer, "encoder", None)
        if (
            not getattr(encoder, "ucpe_transition_supported", False)
            or getattr(encoder, "camera_encoding", None) != "ucpe_relative"
        ):
            raise ValueError(
                "UCPE transition requires the transition UCPE encoder"
            )

    def scale_at(self, step: int) -> float:
        if step < self.start_step:
            raise ValueError("step precedes UCPE transition start")
        return min(1.0, (step - self.start_step) / self.warmup_steps)


def set_ucpe_transition_scale(encoder: nn.Module, scale: float) -> None:
    if not math.isfinite(scale) or not 0.0 <= scale <= 1.0:
        raise ValueError("UCPE transition scale must be finite and in [0, 1]")
    branches = 0
    for module in encoder.modules():
        if isinstance(module, RelativeRayAttention):
            module.transition_scale = scale
            branches += 1
    if branches == 0:
        raise ValueError("encoder has no transition UCPE branches")


def restore_ucpe_transition_for_evaluation(
    encoder: nn.Module,
    config: UCPETransitionConfig | None,
    checkpoint_step: int,
) -> None:
    if config is not None:
        step = max(config.start_step, checkpoint_step - 1)
        set_ucpe_transition_scale(encoder, config.scale_at(step))


class UCPETransition:
    def __init__(self, config: UCPETransitionConfig) -> None:
        self.config = config

    def __call__(self, trainer: nn.Module, args: tuple[object, ...]) -> None:
        if not trainer.training:
            return
        if len(args) != 2 or not isinstance(args[1], int):
            raise TypeError(
                "UCPE transition expects a batch and integer global step"
            )
        encoder = getattr(trainer, "encoder", None)
        if not isinstance(encoder, nn.Module):
            raise TypeError("UCPE transition requires a trainer encoder")
        step = args[1]
        scale = self.config.scale_at(step)
        set_ucpe_transition_scale(encoder, scale)
        rank = (
            torch.distributed.get_rank()
            if torch.distributed.is_initialized()
            else 0
        )
        if rank == 0 and (step == self.config.start_step or step % 50 == 0):
            logger.info("UCPE transition: step=%d scale=%.6f", step, scale)


def install_ucpe_transition(
    trainer: nn.Module, config: UCPETransitionConfig
) -> None:
    config.validate_trainer(getattr(trainer, "config", None))
    trainer.register_forward_pre_hook(UCPETransition(config))