Sequence
int64 1
25.2k
| Time
int64 1
858M
| File
stringclasses 830
values | RangeOffset
int64 0
2.21M
| RangeLength
int64 0
168k
| Text
stringlengths 1
4.7M
⌀ | Language
stringclasses 20
values | Type
stringclasses 9
values |
|---|---|---|---|---|---|---|---|
242
| 466,998
|
utils/dataloader_new.py
| 3,414
| 0
| null |
python
|
selection_command
|
243
| 467,079
|
utils/dataloader_new.py
| 3,415
| 0
| null |
python
|
selection_command
|
244
| 904,870
|
utils/dataloader_new.py
| 3,487
| 0
| null |
python
|
selection_mouse
|
245
| 906,435
|
TERMINAL
| 0
| 0
|
bash
| null |
terminal_focus
|
246
| 919,192
|
models/tokenizer.py
| 0
| 0
|
from typing import Dict, Any, Tuple\n\nimport flax.linen as nn\n\nfrom utils.preprocess import patchify, unpatchify\nfrom utils.nn import STTransformer, VectorQuantizer\n\n\nclass TokenizerVQVAE(nn.Module):\n """ST-ViVit VQ-VAE"""\n\n in_dim: int\n model_dim: int\n latent_dim: int\n num_latents: int\n patch_size: int\n num_blocks: int\n num_heads: int\n dropout: float\n codebook_dropout: float\n\n def setup(self):\n self.encoder = STTransformer(\n self.model_dim,\n self.latent_dim,\n self.num_blocks,\n self.num_heads,\n self.dropout,\n )\n self.vq = VectorQuantizer(\n self.latent_dim,\n self.num_latents,\n self.codebook_dropout,\n )\n self.out_dim = self.in_dim * self.patch_size**2\n self.decoder = STTransformer(\n self.model_dim,\n self.out_dim,\n self.num_blocks,\n self.num_heads,\n self.dropout,\n )\n\n def __call__(self, batch: Dict[str, Any], training: bool = True) -> Dict[str, Any]:\n H, W = batch["videos"].shape[2:4]\n outputs = self.vq_encode(batch["videos"], training)\n recon = self.decoder(outputs["z_q"]) # (B, T, H_down * W_down, C)\n recon = nn.sigmoid(recon)\n outputs["recon"] = unpatchify(recon, self.patch_size, H, W)\n return outputs\n\n def vq_encode(self, videos: Any, training: bool = True) -> Dict[str, Any]:\n # --- Preprocess + encode ---\n B, T = videos.shape[:2]\n x = patchify(videos, self.patch_size)\n N = x.shape[2]\n x = self.encoder(x) # (B, T, N, E)\n\n # --- Vector quantize ---\n x = x.reshape(B * T * N, self.latent_dim)\n z_q, z, emb, indices = self.vq(x, training)\n z_q = z_q.reshape(B, T, N, self.latent_dim)\n indices = indices.reshape(B, T, N)\n return dict(z_q=z_q, z=z, emb=emb, indices=indices)\n\n def decode(self, indices: Any, video_hw: Tuple[int, int]):\n z = self.vq.codebook[indices]\n recon = self.decoder(z)\n recon = nn.sigmoid(recon)\n return unpatchify(recon, self.patch_size, *video_hw)\n
|
python
|
tab
|
247
| 926,801
|
train_tokenizer.py
| 0
| 0
|
from dataclasses import dataclass\nimport os\nimport time\n\nimport einops\nfrom flax.training import orbax_utils\nfrom flax.training.train_state import TrainState\nfrom jax.sharding import Mesh, PartitionSpec, NamedSharding\nfrom jax.experimental.mesh_utils import create_device_mesh\nimport optax\nimport orbax\nfrom orbax.checkpoint import PyTreeCheckpointer\nimport numpy as np\nimport dm_pix as pix\nimport jax\nimport jax.numpy as jnp\nimport tyro\nimport wandb\n\nfrom models.tokenizer import TokenizerVQVAE\nfrom utils.dataloader import get_dataloader\n\nts = int(time.time())\n\n\n@dataclass\nclass Args:\n # Experiment\n num_steps: int = 300_000\n seed: int = 0\n seq_len: int = 16\n image_channels: int = 3\n image_height: int = 90\n image_width: int = 160\n data_dir: str = "data_tfrecords/coinrun"\n checkpoint: str = ""\n # Optimization\n vq_beta: float = 0.25\n batch_size: int = 48\n min_lr: float = 3e-4\n max_lr: float = 3e-4\n warmup_steps: int = 10000\n # Tokenizer\n model_dim: int = 512\n latent_dim: int = 32\n num_latents: int = 1024\n patch_size: int = 4\n num_blocks: int = 8\n num_heads: int = 8\n dropout: float = 0.0\n codebook_dropout: float = 0.01\n # Logging\n log: bool = False\n entity: str = ""\n project: str = ""\n log_interval: int = 5\n log_image_interval: int = 250\n ckpt_dir: str = ""\n log_checkpoint_interval: int = 10000\n log_gradients: bool = False\n\n\nargs = tyro.cli(Args)\n\n\ndef tokenizer_loss_fn(params, state, inputs):\n # --- Compute loss ---\n outputs = state.apply_fn(\n params,\n inputs,\n training=True,\n rngs={"params": inputs["rng"], "dropout": inputs["dropout_rng"]},\n )\n mse = jnp.square(inputs["videos"] - outputs["recon"]).mean()\n q_loss = jnp.square(jax.lax.stop_gradient(outputs["emb"]) - outputs["z"]).mean()\n commitment_loss = jnp.square(\n outputs["emb"] - jax.lax.stop_gradient(outputs["z"])\n ).mean()\n loss = mse + q_loss + args.vq_beta * commitment_loss\n\n # --- Compute validation metrics ---\n gt = inputs["videos"].clip(0, 1).reshape(-1, *inputs["videos"].shape[2:])\n recon = outputs["recon"].clip(0, 1).reshape(-1, *outputs["recon"].shape[2:])\n psnr = pix.psnr(gt, recon).mean()\n ssim = pix.ssim(gt, recon).mean()\n _, index_counts = jnp.unique_counts(\n jnp.ravel(outputs["indices"]), size=args.num_latents, fill_value=0\n )\n codebook_usage = (index_counts != 0).mean()\n metrics = dict(\n loss=loss,\n mse=mse,\n q_loss=q_loss,\n commitment_loss=commitment_loss,\n psnr=psnr,\n ssim=ssim,\n codebook_usage=codebook_usage,\n )\n return loss, (outputs["recon"], metrics)\n\n\n@jax.jit\ndef train_step(state, inputs):\n grad_fn = jax.value_and_grad(tokenizer_loss_fn, has_aux=True, allow_int=True)\n (loss, (recon, metrics)), grads = grad_fn(state.params, state, inputs)\n state = state.apply_gradients(grads=grads)\n if args.log_gradients:\n metrics["encoder_gradients_std/"] = jax.tree.map(\n lambda x: x.std(), grads["params"]["encoder"]\n )\n metrics["vq_gradients_std/"] = jax.tree.map(\n lambda x: x.std(), grads["params"]["vq"]\n )\n metrics["decoder_gradients_std/"] = jax.tree.map(\n lambda x: x.std(), grads["params"]["decoder"]\n )\n return state, loss, recon, metrics\n\n\nif __name__ == "__main__":\n jax.distributed.initialize()\n num_devices = jax.device_count()\n if num_devices == 0:\n raise ValueError("No JAX devices found.")\n print(f"Running on {num_devices} devices.")\n\n if args.batch_size % num_devices != 0:\n raise ValueError(\n f"Global batch size {args.batch_size} must be divisible by "\n f"number of devices {num_devices}."\n )\n\n per_device_batch_size_for_init = args.batch_size // num_devices\n\n rng = jax.random.PRNGKey(args.seed)\n if args.log and jax.process_index() == 0:\n wandb.init(entity=args.entity, project=args.project, group="debug", config=args)\n\n # --- Initialize model ---\n tokenizer = TokenizerVQVAE(\n in_dim=args.image_channels,\n model_dim=args.model_dim,\n latent_dim=args.latent_dim,\n num_latents=args.num_latents,\n patch_size=args.patch_size,\n num_blocks=args.num_blocks,\n num_heads=args.num_heads,\n dropout=args.dropout,\n codebook_dropout=args.codebook_dropout,\n )\n rng, _rng = jax.random.split(rng)\n image_shape = (args.image_height, args.image_width, args.image_channels)\n inputs = dict(\n videos=jnp.zeros(\n (per_device_batch_size_for_init, args.seq_len, *image_shape),\n dtype=jnp.float32,\n ),\n )\n init_params = tokenizer.init(_rng, inputs)\n\n # --- Initialize optimizer ---\n lr_schedule = optax.warmup_cosine_decay_schedule(\n args.min_lr, args.max_lr, args.warmup_steps, args.num_steps\n )\n tx = optax.adamw(learning_rate=lr_schedule, b1=0.9, b2=0.9, weight_decay=1e-4)\n train_state = TrainState.create(apply_fn=tokenizer.apply, params=init_params, tx=tx)\n\n # FIXME: switch to create_hybrid_device_mesh for runs spanning multiple nodes\n device_mesh_arr = create_device_mesh((num_devices,))\n mesh = Mesh(devices=device_mesh_arr, axis_names=("data",))\n\n replicated_sharding = NamedSharding(mesh, PartitionSpec())\n train_state = jax.device_put(train_state, replicated_sharding)\n\n # --- Load checkpoint ---\n step = 0\n if args.checkpoint:\n restore_target = {"model": train_state}\n restore_args = orbax_utils.restore_args_from_target(restore_target)\n train_state.params["params"].update(\n PyTreeCheckpointer()\n .restore(args.checkpoint, item=restore_target, restore_args=restore_args)[\n "model"\n ]\n .params["params"]\n )\n # Assume checkpoint is of the form tokenizer_<timestamp>_<step>\n step += int(args.checkpoint.split("_")[-1])\n\n # --- TRAIN LOOP ---\n tfrecord_files = [\n os.path.join(args.data_dir, x)\n for x in os.listdir(args.data_dir)\n if x.endswith(".tfrecord")\n ]\n dataloader = get_dataloader(\n # NOTE: We deliberately pass the global batch size\n # The dataloader shards the dataset across all processes\n tfrecord_files,\n args.seq_len,\n args.batch_size,\n *image_shape,\n )\n print(f"Starting training from step {step}...")\n while step < args.num_steps:\n for videos in dataloader:\n # npy_path = "overfit_dir/single_sample_corner.npy"\n # videos = np.load(npy_path)\n # print("batch shape: ", videos.shape)\n # while(True):\n # --- Train step ---\n rng, _rng, _rng_dropout = jax.random.split(rng, 3)\n\n videos_sharding = NamedSharding(\n mesh, PartitionSpec("data", None, None, None, None)\n )\n videos = jax.make_array_from_process_local_data(videos_sharding, videos)\n\n inputs = dict(videos=videos, rng=_rng, dropout_rng=_rng_dropout)\n start_time = time.time()\n train_state, loss, recon, metrics = train_step(train_state, inputs)\n elapsed_time = (time.time() - start_time) * 1000\n print(f"Step {step}, loss: {loss}, step time: {elapsed_time}ms")\n step += 1\n\n # --- Logging ---\n if args.log:\n if step % args.log_interval == 0 and jax.process_index() == 0:\n wandb.log(\n {\n "loss": loss,\n "step": step,\n "step_time_ms": elapsed_time,\n **metrics,\n }\n )\n if step % args.log_image_interval == 0:\n gt_seq = inputs["videos"][0]\n recon_seq = recon[0].clip(0, 1)\n comparison_seq = jnp.concatenate((gt_seq, recon_seq), axis=1)\n comparison_seq = einops.rearrange(\n comparison_seq * 255, "t h w c -> h (t w) c"\n )\n # NOTE: Process-dependent control flow deliberately happens\n # after indexing operation since it must not contain code\n # sections that lead to cross-accelerator communication.\n if jax.process_index() == 0:\n log_images = dict(\n image=wandb.Image(np.asarray(gt_seq[0])),\n recon=wandb.Image(np.asarray(recon_seq[0])),\n true_vs_recon=wandb.Image(\n np.asarray(comparison_seq.astype(np.uint8))\n ),\n )\n wandb.log(log_images)\n if step % args.log_checkpoint_interval == 0:\n ckpt = {"model": train_state}\n orbax_checkpointer = orbax.checkpoint.PyTreeCheckpointer()\n save_args = orbax_utils.save_args_from_target(ckpt)\n orbax_checkpointer.save(\n os.path.join(os.getcwd(), args.ckpt_dir, f"tokenizer_{ts}_{step}"),\n ckpt,\n save_args=save_args,\n )\n if step >= args.num_steps:\n break\n
|
python
|
tab
|
248
| 928,576
|
train_tokenizer.py
| 9,423
| 0
| null |
python
|
selection_command
|
249
| 928,836
|
train_tokenizer.py
| 9,401
| 0
| null |
python
|
selection_command
|
250
| 929,327
|
train_tokenizer.py
| 9,362
| 0
| null |
python
|
selection_command
|
251
| 929,418
|
train_tokenizer.py
| 9,344
| 0
| null |
python
|
selection_command
|
252
| 929,419
|
train_tokenizer.py
| 9,303
| 0
| null |
python
|
selection_command
|
253
| 929,441
|
train_tokenizer.py
| 9,277
| 0
| null |
python
|
selection_command
|
254
| 929,477
|
train_tokenizer.py
| 9,189
| 0
| null |
python
|
selection_command
|
255
| 929,513
|
train_tokenizer.py
| 9,148
| 0
| null |
python
|
selection_command
|
256
| 929,577
|
train_tokenizer.py
| 9,080
| 0
| null |
python
|
selection_command
|
257
| 929,609
|
train_tokenizer.py
| 9,005
| 0
| null |
python
|
selection_command
|
258
| 929,610
|
train_tokenizer.py
| 8,959
| 0
| null |
python
|
selection_command
|
259
| 929,639
|
train_tokenizer.py
| 8,902
| 0
| null |
python
|
selection_command
|
260
| 929,671
|
train_tokenizer.py
| 8,856
| 0
| null |
python
|
selection_command
|
261
| 929,703
|
train_tokenizer.py
| 8,830
| 0
| null |
python
|
selection_command
|
262
| 929,734
|
train_tokenizer.py
| 8,799
| 0
| null |
python
|
selection_command
|
263
| 929,766
|
train_tokenizer.py
| 8,723
| 0
| null |
python
|
selection_command
|
264
| 929,798
|
train_tokenizer.py
| 8,668
| 0
| null |
python
|
selection_command
|
265
| 929,834
|
train_tokenizer.py
| 8,595
| 0
| null |
python
|
selection_command
|
266
| 929,866
|
train_tokenizer.py
| 8,525
| 0
| null |
python
|
selection_command
|
267
| 929,902
|
train_tokenizer.py
| 8,482
| 0
| null |
python
|
selection_command
|
268
| 929,934
|
train_tokenizer.py
| 8,433
| 0
| null |
python
|
selection_command
|
269
| 929,935
|
train_tokenizer.py
| 8,356
| 0
| null |
python
|
selection_command
|
270
| 929,969
|
train_tokenizer.py
| 8,278
| 0
| null |
python
|
selection_command
|
271
| 930,003
|
train_tokenizer.py
| 8,198
| 0
| null |
python
|
selection_command
|
272
| 930,035
|
train_tokenizer.py
| 8,176
| 0
| null |
python
|
selection_command
|
273
| 930,067
|
train_tokenizer.py
| 8,107
| 0
| null |
python
|
selection_command
|
274
| 930,099
|
train_tokenizer.py
| 8,052
| 0
| null |
python
|
selection_command
|
275
| 930,130
|
train_tokenizer.py
| 7,970
| 0
| null |
python
|
selection_command
|
276
| 930,162
|
train_tokenizer.py
| 7,918
| 0
| null |
python
|
selection_command
|
277
| 930,194
|
train_tokenizer.py
| 7,869
| 0
| null |
python
|
selection_command
|
278
| 930,226
|
train_tokenizer.py
| 7,813
| 0
| null |
python
|
selection_command
|
279
| 930,257
|
train_tokenizer.py
| 7,791
| 0
| null |
python
|
selection_command
|
280
| 930,289
|
train_tokenizer.py
| 7,765
| 0
| null |
python
|
selection_command
|
281
| 930,290
|
train_tokenizer.py
| 7,726
| 0
| null |
python
|
selection_command
|
282
| 930,321
|
train_tokenizer.py
| 7,668
| 0
| null |
python
|
selection_command
|
283
| 930,353
|
train_tokenizer.py
| 7,626
| 0
| null |
python
|
selection_command
|
284
| 930,385
|
train_tokenizer.py
| 7,584
| 0
| null |
python
|
selection_command
|
285
| 930,427
|
train_tokenizer.py
| 7,558
| 0
| null |
python
|
selection_command
|
286
| 930,458
|
train_tokenizer.py
| 7,527
| 0
| null |
python
|
selection_command
|
287
| 930,460
|
train_tokenizer.py
| 7,448
| 0
| null |
python
|
selection_command
|
288
| 930,523
|
train_tokenizer.py
| 7,423
| 0
| null |
python
|
selection_command
|
289
| 930,559
|
train_tokenizer.py
| 7,393
| 0
| null |
python
|
selection_command
|
290
| 930,594
|
train_tokenizer.py
| 7,392
| 0
| null |
python
|
selection_command
|
291
| 930,626
|
train_tokenizer.py
| 7,370
| 0
| null |
python
|
selection_command
|
292
| 930,627
|
train_tokenizer.py
| 7,293
| 0
| null |
python
|
selection_command
|
293
| 930,661
|
train_tokenizer.py
| 7,232
| 0
| null |
python
|
selection_command
|
294
| 930,700
|
train_tokenizer.py
| 7,152
| 0
| null |
python
|
selection_command
|
295
| 930,733
|
train_tokenizer.py
| 7,115
| 0
| null |
python
|
selection_command
|
296
| 930,766
|
train_tokenizer.py
| 7,038
| 0
| null |
python
|
selection_command
|
297
| 930,798
|
train_tokenizer.py
| 7,037
| 0
| null |
python
|
selection_command
|
298
| 930,830
|
train_tokenizer.py
| 6,952
| 0
| null |
python
|
selection_command
|
299
| 930,831
|
train_tokenizer.py
| 6,938
| 0
| null |
python
|
selection_command
|
300
| 930,861
|
train_tokenizer.py
| 6,870
| 0
| null |
python
|
selection_command
|
301
| 930,893
|
train_tokenizer.py
| 6,825
| 0
| null |
python
|
selection_command
|
302
| 930,925
|
train_tokenizer.py
| 6,824
| 0
| null |
python
|
selection_command
|
303
| 930,956
|
train_tokenizer.py
| 6,761
| 0
| null |
python
|
selection_command
|
304
| 930,989
|
train_tokenizer.py
| 6,728
| 0
| null |
python
|
selection_command
|
305
| 931,020
|
train_tokenizer.py
| 6,705
| 0
| null |
python
|
selection_command
|
306
| 931,052
|
train_tokenizer.py
| 6,658
| 0
| null |
python
|
selection_command
|
307
| 931,117
|
train_tokenizer.py
| 6,621
| 0
| null |
python
|
selection_command
|
308
| 931,118
|
train_tokenizer.py
| 6,561
| 0
| null |
python
|
selection_command
|
309
| 931,155
|
train_tokenizer.py
| 6,527
| 0
| null |
python
|
selection_command
|
310
| 931,191
|
train_tokenizer.py
| 6,494
| 0
| null |
python
|
selection_command
|
311
| 931,224
|
train_tokenizer.py
| 6,442
| 0
| null |
python
|
selection_command
|
312
| 931,258
|
train_tokenizer.py
| 6,436
| 0
| null |
python
|
selection_command
|
313
| 931,318
|
train_tokenizer.py
| 6,414
| 0
| null |
python
|
selection_command
|
314
| 931,318
|
train_tokenizer.py
| 6,389
| 0
| null |
python
|
selection_command
|
315
| 931,333
|
train_tokenizer.py
| 6,367
| 0
| null |
python
|
selection_command
|
316
| 931,654
|
train_tokenizer.py
| 6,389
| 0
| null |
python
|
selection_command
|
317
| 932,154
|
train_tokenizer.py
| 6,414
| 0
| null |
python
|
selection_command
|
318
| 932,185
|
train_tokenizer.py
| 6,436
| 0
| null |
python
|
selection_command
|
319
| 932,208
|
train_tokenizer.py
| 6,442
| 0
| null |
python
|
selection_command
|
320
| 932,247
|
train_tokenizer.py
| 6,494
| 0
| null |
python
|
selection_command
|
321
| 932,280
|
train_tokenizer.py
| 6,527
| 0
| null |
python
|
selection_command
|
322
| 932,333
|
train_tokenizer.py
| 6,561
| 0
| null |
python
|
selection_command
|
323
| 932,378
|
train_tokenizer.py
| 6,621
| 0
| null |
python
|
selection_command
|
324
| 932,688
|
train_tokenizer.py
| 6,561
| 0
| null |
python
|
selection_command
|
325
| 932,845
|
train_tokenizer.py
| 6,527
| 0
| null |
python
|
selection_command
|
326
| 933,177
|
train_tokenizer.py
| 6,535
| 0
| null |
python
|
selection_command
|
327
| 933,832
|
train_tokenizer.py
| 6,535
| 0
|
#
|
python
|
content
|
328
| 933,833
|
train_tokenizer.py
| 6,536
| 0
| null |
python
|
selection_keyboard
|
329
| 933,866
|
train_tokenizer.py
| 6,536
| 0
|
python
|
content
|
|
330
| 933,868
|
train_tokenizer.py
| 6,537
| 0
| null |
python
|
selection_keyboard
|
331
| 934,155
|
train_tokenizer.py
| 6,536
| 0
| null |
python
|
selection_command
|
332
| 934,404
|
train_tokenizer.py
| 6,572
| 0
| null |
python
|
selection_command
|
333
| 934,937
|
train_tokenizer.py
| 6,563
| 59
|
# npy_path = "overfit_dir/single_sample_corner.npy"
|
python
|
selection_command
|
334
| 935,161
|
train_tokenizer.py
| 6,563
| 96
|
# npy_path = "overfit_dir/single_sample_corner.npy"\n # videos = np.load(npy_path)
|
python
|
selection_command
|
335
| 935,263
|
train_tokenizer.py
| 6,563
| 143
|
# npy_path = "overfit_dir/single_sample_corner.npy"\n # videos = np.load(npy_path)\n # print("batch shape: ", videos.shape)
|
python
|
selection_command
|
336
| 935,412
|
train_tokenizer.py
| 6,563
| 166
|
# npy_path = "overfit_dir/single_sample_corner.npy"\n # videos = np.load(npy_path)\n # print("batch shape: ", videos.shape)\n # while(True):
|
python
|
selection_command
|
337
| 935,857
|
train_tokenizer.py
| 6,571
| 0
| null |
python
|
selection_command
|
338
| 936,552
|
train_tokenizer.py
| 6,715
| 1
| null |
python
|
content
|
339
| 936,553
|
train_tokenizer.py
| 6,668
| 1
| null |
python
|
content
|
340
| 936,553
|
train_tokenizer.py
| 6,631
| 1
| null |
python
|
content
|
341
| 936,553
|
train_tokenizer.py
| 6,571
| 1
| null |
python
|
content
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.