haiphamcse commited on
Commit
7e4c5ac
·
verified ·
1 Parent(s): 5d9a314

Upload jit_model_util.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. jit_model_util.py +137 -0
jit_model_util.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Adapted from JiT: https://github.com/LTH14/JiT/blob/main/util/model_util.py
3
+ # Lightning-DiT: https://github.com/hustvl/LightningDiT
4
+ # Changes: device-agnostic buffers (no hard-coded .cuda())
5
+ # --------------------------------------------------------
6
+
7
+ from __future__ import annotations
8
+
9
+ from math import pi
10
+
11
+ import numpy as np
12
+ import torch
13
+ from einops import rearrange, repeat
14
+ from torch import nn
15
+
16
+
17
+ def broadcat(tensors, dim=-1):
18
+ num_tensors = len(tensors)
19
+ shape_lens = set(list(map(lambda t: len(t.shape), tensors)))
20
+ assert len(shape_lens) == 1, "tensors must all have the same number of dimensions"
21
+ shape_len = list(shape_lens)[0]
22
+ dim = (dim + shape_len) if dim < 0 else dim
23
+ dims = list(zip(*map(lambda t: list(t.shape), tensors)))
24
+ expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
25
+ assert all(
26
+ [*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]
27
+ ), "invalid dimensions for broadcastable concatentation"
28
+ max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))
29
+ expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))
30
+ expanded_dims.insert(dim, (dim, dims[dim]))
31
+ expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))
32
+ tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes)))
33
+ return torch.cat(tensors, dim=dim)
34
+
35
+
36
+ def rotate_half(x):
37
+ x = rearrange(x, "... (d r) -> ... d r", r=2)
38
+ x1, x2 = x.unbind(dim=-1)
39
+ x = torch.stack((-x2, x1), dim=-1)
40
+ return rearrange(x, "... d r -> ... (d r)")
41
+
42
+
43
+ class VisionRotaryEmbeddingFast(nn.Module):
44
+ def __init__(
45
+ self,
46
+ dim,
47
+ pt_seq_len=16,
48
+ ft_seq_len=None,
49
+ custom_freqs=None,
50
+ freqs_for="lang",
51
+ theta=10000,
52
+ max_freq=10,
53
+ num_freqs=1,
54
+ num_cls_token=0,
55
+ ):
56
+ super().__init__()
57
+ if custom_freqs:
58
+ freqs = custom_freqs
59
+ elif freqs_for == "lang":
60
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim))
61
+ elif freqs_for == "pixel":
62
+ freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi
63
+ elif freqs_for == "constant":
64
+ freqs = torch.ones(num_freqs).float()
65
+ else:
66
+ raise ValueError(f"unknown modality {freqs_for}")
67
+
68
+ if ft_seq_len is None:
69
+ ft_seq_len = pt_seq_len
70
+ t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
71
+
72
+ freqs = torch.einsum("..., f -> ... f", t, freqs)
73
+ freqs = repeat(freqs, "... n -> ... (n r)", r=2)
74
+ freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1)
75
+
76
+ if num_cls_token > 0:
77
+ freqs_flat = freqs.view(-1, freqs.shape[-1])
78
+ cos_img = freqs_flat.cos()
79
+ sin_img = freqs_flat.sin()
80
+ n_img, d = cos_img.shape
81
+ cos_pad = torch.ones(num_cls_token, d, dtype=cos_img.dtype)
82
+ sin_pad = torch.zeros(num_cls_token, d, dtype=sin_img.dtype)
83
+ self.register_buffer("freqs_cos", torch.cat([cos_pad, cos_img], dim=0), persistent=False)
84
+ self.register_buffer("freqs_sin", torch.cat([sin_pad, sin_img], dim=0), persistent=False)
85
+ else:
86
+ self.register_buffer("freqs_cos", freqs.cos().view(-1, freqs.shape[-1]), persistent=False)
87
+ self.register_buffer("freqs_sin", freqs.sin().view(-1, freqs.shape[-1]), persistent=False)
88
+
89
+ def forward(self, t):
90
+ return t * self.freqs_cos + rotate_half(t) * self.freqs_sin
91
+
92
+
93
+ class RMSNorm(nn.Module):
94
+ def __init__(self, hidden_size, eps=1e-6):
95
+ super().__init__()
96
+ self.weight = nn.Parameter(torch.ones(hidden_size))
97
+ self.variance_epsilon = eps
98
+
99
+ def forward(self, hidden_states):
100
+ input_dtype = hidden_states.dtype
101
+ hidden_states = hidden_states.to(torch.float32)
102
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
103
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
104
+ return (self.weight * hidden_states).to(input_dtype)
105
+
106
+
107
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
108
+ grid_h = np.arange(grid_size, dtype=np.float32)
109
+ grid_w = np.arange(grid_size, dtype=np.float32)
110
+ grid = np.meshgrid(grid_w, grid_h)
111
+ grid = np.stack(grid, axis=0)
112
+ grid = grid.reshape([2, 1, grid_size, grid_size])
113
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
114
+ if cls_token and extra_tokens > 0:
115
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
116
+ return pos_embed
117
+
118
+
119
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
120
+ assert embed_dim % 2 == 0
121
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0])
122
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1])
123
+ emb = np.concatenate([emb_h, emb_w], axis=1)
124
+ return emb
125
+
126
+
127
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
128
+ assert embed_dim % 2 == 0
129
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
130
+ omega /= embed_dim / 2.0
131
+ omega = 1.0 / 10000**omega
132
+ pos = pos.reshape(-1)
133
+ out = np.einsum("m,d->md", pos, omega)
134
+ emb_sin = np.sin(out)
135
+ emb_cos = np.cos(out)
136
+ emb = np.concatenate([emb_sin, emb_cos], axis=1)
137
+ return emb