| 106 | |
| 107 | |
| 108 | class CogDiT(torch.nn.Module): |
| 109 | def __init__(self): |
| 110 | super().__init__() |
| 111 | self.patchify = CogPatchify(16, 3072, 2) |
| 112 | self.time_embedder = TimestepEmbeddings(3072, 512) |
| 113 | self.context_embedder = torch.nn.Linear(4096, 3072) |
| 114 | self.blocks = torch.nn.ModuleList([CogDiTBlock(3072, 512, 48) for _ in range(42)]) |
| 115 | self.norm_final = torch.nn.LayerNorm((3072,), eps=1e-05, elementwise_affine=True) |
| 116 | self.norm_out = CogAdaLayerNorm(3072, 512, single=True) |
| 117 | self.proj_out = torch.nn.Linear(3072, 64, bias=True) |
| 118 | |
| 119 | |
| 120 | def get_resize_crop_region_for_grid(self, src, tgt_width, tgt_height): |
| 121 | tw = tgt_width |
| 122 | th = tgt_height |
| 123 | h, w = src |
| 124 | r = h / w |
| 125 | if r > (th / tw): |
| 126 | resize_height = th |
| 127 | resize_width = int(round(th / h * w)) |
| 128 | else: |
| 129 | resize_width = tw |
| 130 | resize_height = int(round(tw / w * h)) |
| 131 | |
| 132 | crop_top = int(round((th - resize_height) / 2.0)) |
| 133 | crop_left = int(round((tw - resize_width) / 2.0)) |
| 134 | |
| 135 | return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width) |
| 136 | |
| 137 | |
| 138 | def get_3d_rotary_pos_embed( |
| 139 | self, embed_dim, crops_coords, grid_size, temporal_size, theta: int = 10000, use_real: bool = True |
| 140 | ): |
| 141 | start, stop = crops_coords |
| 142 | grid_h = np.linspace(start[0], stop[0], grid_size[0], endpoint=False, dtype=np.float32) |
| 143 | grid_w = np.linspace(start[1], stop[1], grid_size[1], endpoint=False, dtype=np.float32) |
| 144 | grid_t = np.linspace(0, temporal_size, temporal_size, endpoint=False, dtype=np.float32) |
| 145 | |
| 146 | # Compute dimensions for each axis |
| 147 | dim_t = embed_dim // 4 |
| 148 | dim_h = embed_dim // 8 * 3 |
| 149 | dim_w = embed_dim // 8 * 3 |
| 150 | |
| 151 | # Temporal frequencies |
| 152 | freqs_t = 1.0 / (theta ** (torch.arange(0, dim_t, 2).float() / dim_t)) |
| 153 | grid_t = torch.from_numpy(grid_t).float() |
| 154 | freqs_t = torch.einsum("n , f -> n f", grid_t, freqs_t) |
| 155 | freqs_t = freqs_t.repeat_interleave(2, dim=-1) |
| 156 | |
| 157 | # Spatial frequencies for height and width |
| 158 | freqs_h = 1.0 / (theta ** (torch.arange(0, dim_h, 2).float() / dim_h)) |
| 159 | freqs_w = 1.0 / (theta ** (torch.arange(0, dim_w, 2).float() / dim_w)) |
| 160 | grid_h = torch.from_numpy(grid_h).float() |
| 161 | grid_w = torch.from_numpy(grid_w).float() |
| 162 | freqs_h = torch.einsum("n , f -> n f", grid_h, freqs_h) |
| 163 | freqs_w = torch.einsum("n , f -> n f", grid_w, freqs_w) |
| 164 | freqs_h = freqs_h.repeat_interleave(2, dim=-1) |
| 165 | freqs_w = freqs_w.repeat_interleave(2, dim=-1) |