p-doom/crowd-code-dataset-0.2 huggingface dataset:
[terminal_command] TERMINAL ()
/bin/python3 /hkfs/home/project/hk-project-p0023960/tum_cte0515/.cursor-server/extensions/ms-python.python-2024.12.3-linux-x64/python_files/printEnvVariablesToFile.py /hkfs/home/project/hk-project-p0023960/tum_cte0515/.cursor-server/extensions/ms-python.python-2024.12.3-linux-x64/python_files/deactivate/bash/envVars.txt
[tab] scripts_horeka/modelsize_scaling/tokenizer/train_tokenizer_37M.sbatch (shellscript)
#!/usr/bin/env bash

#SBATCH --nodes=2
#SBATCH --ntasks-per-node=4
#SBATCH --time=15:00:00
#SBATCH --partition=accelerated
#SBATCH --cpus-per-task=5
#SBATCH --gres=gpu:4
#SBATCH --output=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/logs/logs_mihir/%x_%j.log
#SBATCH --error=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/logs/logs_mihir/%x_%j.log
#SBATCH --job-name=train_tokenizer_model_size_scaling_37M

# Log the sbatch script
cat $0

module unload mpi/openmpi/5.0
module unload devel/cuda/12.4
source .venv/bin/activate

tf_records_dir=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/data/open_ai_minecraft_tfrecord
ws_dir='/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/'

job_name=$SLURM_JOB_NAME
slurm_job_id=$SLURM_JOB_ID

CHECKPOINT_DIR=$ws_dir/checkpoints/$job_name_$slurm_job_id
mkdir -p $CHECKPOINT_DIR

env | grep SLURM

srun python train_tokenizer.py \
    --ckpt_dir $CHECKPOINT_DIR \
    --batch_size=96 \
    --min_lr=1e-4 \
    --max_lr=1e-4 \
    --log_image_interval=500 \
    --log_checkpoint_interval=500 \
    --log \
    --name=tokenizer-model-size-scaling-38M-$slurm_job_id \
    --tags tokenizer model-size-scaling 38M \
    --entity instant-uv \
    --project jafar \
    --data_dir $tf_records_dir
[tab] scripts_horeka/modelsize_scaling/tokenizer/train_tokenizer_37M copy.sbatch (shellscript)
#!/usr/bin/env bash

#SBATCH --nodes=2
#SBATCH --ntasks-per-node=4
#SBATCH --time=15:00:00
#SBATCH --partition=accelerated
#SBATCH --cpus-per-task=5
#SBATCH --gres=gpu:4
#SBATCH --output=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/logs/logs_mihir/%x_%j.log
#SBATCH --error=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/logs/logs_mihir/%x_%j.log
#SBATCH --job-name=train_tokenizer_model_size_scaling_37M

# Log the sbatch script
cat $0

module unload mpi/openmpi/5.0
module unload devel/cuda/12.4
source .venv/bin/activate

tf_records_dir=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/data/open_ai_minecraft_tfrecord
ws_dir='/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/'

job_name=$SLURM_JOB_NAME
slurm_job_id=$SLURM_JOB_ID

CHECKPOINT_DIR=$ws_dir/checkpoints/$job_name_$slurm_job_id
mkdir -p $CHECKPOINT_DIR

env | grep SLURM

srun python train_tokenizer.py \
    --ckpt_dir $CHECKPOINT_DIR \
    --batch_size=96 \
    --min_lr=1e-4 \
    --max_lr=1e-4 \
    --log_image_interval=500 \
    --log_checkpoint_interval=500 \
    --log \
    --name=tokenizer-model-size-scaling-38M-$slurm_job_id \
    --tags tokenizer model-size-scaling 38M \
    --entity instant-uv \
    --project jafar \
    --data_dir $tf_records_dir
[tab] scripts_horeka/modelsize_scaling/tokenizer/tester.sh (shellscript)
#!/usr/bin/env bash

#SBATCH --nodes=2
#SBATCH --ntasks-per-node=4
#SBATCH --time=15:00:00
#SBATCH --partition=accelerated
#SBATCH --cpus-per-task=5
#SBATCH --gres=gpu:4
#SBATCH --output=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/logs/logs_mihir/%x_%j.log
#SBATCH --error=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/logs/logs_mihir/%x_%j.log
#SBATCH --job-name=train_tokenizer_model_size_scaling_37M

# Log the sbatch script
cat $0

module unload mpi/openmpi/5.0
module unload devel/cuda/12.4
source .venv/bin/activate

tf_records_dir=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/data/open_ai_minecraft_tfrecord
ws_dir='/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/'

job_name=$SLURM_JOB_NAME
slurm_job_id=$SLURM_JOB_ID

CHECKPOINT_DIR=$ws_dir/checkpoints/$job_name_$slurm_job_id
mkdir -p $CHECKPOINT_DIR

env | grep SLURM

srun python train_tokenizer.py \
    --ckpt_dir $CHECKPOINT_DIR \
    --batch_size=96 \
    --min_lr=1e-4 \
    --max_lr=1e-4 \
    --log_image_interval=500 \
    --log_checkpoint_interval=500 \
    --log \
    --name=tokenizer-model-size-scaling-38M-$slurm_job_id \
    --tags tokenizer model-size-scaling 38M \
    --entity instant-uv \
    --project jafar \
    --data_dir $tf_records_dir
[tab] scripts_horeka/batchsize_scaling/adjusted_lr/tester.sh (shellscript)
#!/usr/bin/env bash

module unload mpi/openmpi/5.0
module unload devel/cuda/12.4
source .venv/bin/activate

tf_records_dir=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/data/open_ai_minecraft_tfrecord
ws_dir='/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/'

job_name="debug"
slurm_job_id="0000"

CHECKPOINT_DIR=$ws_dir/checkpoints/$job_name/$slurm_job_id
mkdir -p $CHECKPOINT_DIR

env | grep SLURM

srun python train_tokenizer.py \
    --ckpt_dir $CHECKPOINT_DIR \
    --batch_size=48 \
    --min_lr=1e-4 \
    --max_lr=1e-4 \
    --log_image_interval=10 \
    --log \
    --name=tokenizer-batch-size-scaling-1-node-$slurm_job_id \
    --tags tokenizer batch-size-scaling 1-node debug \
    --entity instant-uv \
    --project jafar \
    --data_dir $tf_records_dir
[tab] scripts_horeka/overfit_sample_tiny/sample.sh (shellscript)
#!/usr/bin/env bash

# Unload modules that may interfere
module unload mpi/openmpi/5.0
module unload devel/cuda/12.4

# Activate virtual environment
source .venv/bin/activate

# Set workspace and checkpoint directory (update slurm_job_id as needed)
ws_dir='/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared'
# Replace the following with the actual job id/checkpoint you want to sample from
slurm_job_id=3301029

# job_name=train_dynamics_minecraft_overfit_sample_tiny
CHECKPOINT_DIR=$ws_dir/checkpoints/${slurm_job_id}

# Example: If you want to use a specific checkpoint, set it here
# CHECKPOINT_PATH=$ws_dir/checkpoints/3299272/dynamics-tiny-overfit-big-lr-3299272_50000/
# Or use the latest in the directory
# CHECKPOINT_PATH=$(ls -d $CHECKPOINT_DIR/*/ | sort | tail -n 1)
CHECKPOINT_PATH=$CHECKPOINT_DIR/genie_1751067601_200000/
# CHECKPOINT_PATH=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/checkpoints/0000/genie_1751301068_2000/
# CHECKPOINT_PATH=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/data/../checkpoints/3307618/genie_1751322003_15500/
# CHECKPOINT_PATH=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/checkpoints/3307619/genie_1751322003_200000/
CHECKPOINT_PATH=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/checkpoints/3309699/genie_1751384516_74500/


echo "Sampling from checkpoint: $CHECKPOINT_PATH"

python sample.py \
    --checkpoint "$CHECKPOINT_PATH" \
    --tokenizer_dim=384 \
    --latent_patch_dim=32 \
    --num_patch_latents=1024 \
    --patch_size=4 \
    --tokenizer_num_blocks=8 \
    --tokenizer_num_heads=8 \
    --lam_dim=384 \
    --latent_action_dim=32 \
    --lam_patch_size=16 \
    --lam_num_blocks=8 \
    --lam_num_heads=8 \
    --dyna_dim=128 \
    --dyna_num_blocks=2 \
    --dyna_num_heads=4 \
    --maskgit_steps=1000 \
    --num_latent_actions=6 \
    --seq_len=16 \
    --start_frame=0

# python sample.py \
    # --checkpoint "$CHECKPOINT_PATH" \
    # --data_dir=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/data/coinrun_episodes
[content] sample.py (python)
# tfrecord_files = [
    # os.path.join(args.data_dir, x)
    # for x in os.listdir(args.data_dir)
    # if x.endswith(".tfrecord")
# ]
# dataloader = get_dataloader(
    # tfrecord_files,
    # args.seq_len,
    # args.batch_size,
    # args.image_height,
    # args.image_width,
    # args.image_channels,
    # seed=args.seed,
# )
# video_batch = next(iter(dataloader))
video_batch = np.load("overfit_dir/single_sample_corner.npy")
[tab] scripts_horeka/modelsize_scaling/dynamics/model_sizes.md (markdown)
# Genie 1 - Model Sizes and their configs

## Tokenizer model: sizes

default: 
| Model | model_dim | num_blocks | num_heads | latent_dim | num_latents | Est. Params |
|-------|-----------|------------|-----------|------------|-------------|-------------|
| default | 512 | 8 | 8 | 32 | 1024 | ~38M |

### scaling up 
#### (not tested yet - TODO @mihir)

| Model | model_dim | num_blocks | num_heads | latent_dim | num_latents | Est. Params |
|-------|-----------|------------|-----------|------------|-------------|-------------|
| L1 | 768 | 12 | 12 | 64 | 2048 | ~80M |
| L2 | 1024 | 12 | 16 | 128 | 2048 | ~140M |
| L3 | 1152 | 16 | 16 | 128 | 4096 | ~200M |
| L4 | 896 | 16 | 14 | 96 | 4096 | ~120M |
| L5 | 1536 | 12 | 24 | 256 | 2048 | ~190M |


### tiny models
| Model | model_dim | num_blocks | num_heads | latent_dim | num_latents | Est. Params |
|-------|-----------|------------|-----------|------------|-------------|-------------|
| S1 | 128 | 2 | 2 | 8 | 128 | ~0.6M |
| S2 | 192 | 2 | 3 | 16 | 128 | ~1.3M |
| S3 | 256 | 3 | 4 | 16 | 256 | ~3.6M |
| S4 | 320 | 4 | 5 | 24 | 256 | ~7.4M |
| S5 | 384 | 4 | 6 | 32 | 512 | ~10M |


## Latent Action model: sizes
default: 
| Model | model_dim | num_blocks | num_heads | latent_dim | num_latents | Est. Params |
|-------|-----------|------------|-----------|------------|-------------|-------------|
| default | 512 | 8 | 8 | 32 | 6 | ~39M |

### scaling up 
#### (not tested yet - TODO @mihir)

| Name | model_dim | num_blocks | num_heads | latent_dim | num_latents | Est. Params |
|--------------|-----------|------------|-----------|------------|-------------|-------------|
| XL | 1024 | 12 | 16 | 64 | 12 | ~200M |
| L | 896 | 12 | 14 | 48 | 8 | ~150M |
| M+ | 768 | 10 | 12 | 48 | 8 | ~100M |
| M | 640 | 10 | 10 | 32 | 8 | ~70M |
| Base+ | 512 | 12 | 8 | 32 | 8 | ~55M |


### tiny models
| Name | model_dim | num_blocks | num_heads | latent_dim | num_latents | Est. Params |
|--------------|-----------|------------|-----------|------------|-------------|-------------|
| XS | 128 | 2 | 2 | 8 | 4 | ~0.9M |
| S | 160 | 2 | 2 | 8 | 4 | ~1.3M |
| S+ | 192 | 3 | 3 | 8 | 4 | ~2.4M |
| M- | 256 | 4 | 4 | 16 | 6 | ~5.4M |
| M | 320 | 6 | 4 | 16 | 6 | ~12M |


## Dynamics model: sizes 

| Config | dyna_dim | dyna_num_blocks | dyna_num_heads | Approx. Params |
|--------|----------|-----------------|---------------|----------------|
| 1 | 512 | 12 | 8   | ~36M  |
| 2 | 768 | 16 | 12  | ~110M |
| 3 | 1024 | 16 | 16 | ~180M |
| 4 | 1024 | 24 | 16 | ~270M |
| 5 | 1536 | 24 | 24 | ~500M |


### tiny models
| Config | dyna_dim | dyna_num_blocks | dyna_num_heads | Approx. Params |
|--------|----------|-----------------|---------------|----------------|
| A | 128 | 2 | 4 | ~1.5M |
| B | 256 | 2 | 4 | ~3.5M |
| C | 256 | 4 | 4 | ~6M   |
| D | 384 | 4 | 6 | ~12M  |
| E | 512 | 4 | 8 | ~18M  |
[content] genie.py (python)
    @nn.compact
    def sample(
        self,
        batch: Dict[str, Any],
        steps: int = 25,
        temperature: int = 1,
        sample_argmax: bool = False,
    ) -> Any:
        # --- Encode videos and actions ---
        tokenizer_out = self.tokenizer.vq_encode(batch["videos"], training=False)
        token_idxs = tokenizer_out["indices"]
        new_frame_idxs = jnp.zeros_like(token_idxs)[:, 0]
        action_tokens = self.lam.vq.get_codes(batch["latent_actions"])

        # --- Initialize MaskGIT ---
        init_mask = jnp.ones_like(token_idxs, dtype=bool)[:, 0]
        init_carry = (
            batch["rng"],
            new_frame_idxs,
            init_mask,
            token_idxs,
            action_tokens,
        )
        MaskGITLoop = nn.scan(
            MaskGITStep,
            variable_broadcast="params",
            split_rngs={"params": False},
            in_axes=0,
            out_axes=0,
            length=steps,
        )

        # --- Run MaskGIT loop ---
        loop_fn = MaskGITLoop(
            dynamics=self.dynamics,
            tokenizer=self.tokenizer,
            temperature=temperature,
            sample_argmax=sample_argmax,
            steps=steps,
        )
        final_carry, _ = loop_fn(init_carry, jnp.arange(steps))
        new_frame_idxs = final_carry[1]
        new_frame_pixels = self.tokenizer.decode(
            jnp.expand_dims(new_frame_idxs, 1),
            video_hw=batch["videos"].shape[2:4],
        )
        return new_frame_pixels
[content] sample.py (python)
# --- Define autoregressive sampling loop ---
def _autoreg_sample(rng, video_batch, action_batch):
    vid = video_batch[:, : args.start_frame + 1]
    for frame_idx in range(args.start_frame + 1, args.seq_len):
        # --- Sample next frame ---
        print("Frame", frame_idx)
        start_time = time.time()
        rng, _rng = jax.random.split(rng)
        batch = dict(videos=vid, latent_actions=action_batch[:, :1], rng=_rng)
        new_frame = genie.apply(
            params,
            batch,
            args.maskgit_steps,
            args.temperature,
            args.sample_argmax,
            method=Genie.sample,
        )
        elapsed = time.time() - start_time
        print(f"Frame {frame_idx} sampling took {elapsed:.3f} seconds")
        # vid = jnp.concatenate([vid, new_frame], axis=1)
    return vid
[content] sample.py (python)

        batch = dict(videos=vid, latent_actions=action_batch, rng=_rng)
        new_frame = genie.apply(
            params,
            batch,
            args.maskgit_steps,
            args.temperature,
            args.sample_argmax,
            method=Genie.sample_mihir,
        )
[content] genie.py (python)
class MaskGITStep(nn.Module):
    dynamics: nn.Module
    tokenizer: nn.Module
    temperature: float
    sample_argmax: bool
    steps: int

    @nn.compact
    def __call__(self, carry, x):
        rng, final_token_idxs, mask, token_idxs, action_tokens = carry
        step = x
        B, T, N = token_idxs.shape[:3]

        # --- Construct + encode video ---
        vid_token_idxs = jnp.concatenate(
            (token_idxs, jnp.expand_dims(final_token_idxs, 1)), axis=1
        )
        vid_embed = self.dynamics.patch_embed(vid_token_idxs)
        curr_masked_frame = jnp.where(
            jnp.expand_dims(mask, -1),
            self.dynamics.mask_token[0],
            vid_embed[:, -1],
        )
        vid_embed = vid_embed.at[:, -1].set(curr_masked_frame)

        # --- Predict transition ---
        act_embed = self.dynamics.action_up(action_tokens)
        vid_embed += jnp.pad(act_embed, ((0, 0), (1, 0), (0, 0), (0, 0)))
        unmasked_ratio = jnp.cos(jnp.pi * (step + 1) / (self.steps * 2))
        step_temp = self.temperature * (1.0 - unmasked_ratio)
        final_logits = self.dynamics.dynamics(vid_embed)[:, -1] / step_temp

        # --- Sample new tokens for final frame ---
        if self.sample_argmax:
            sampled_token_idxs = jnp.argmax(final_logits, axis=-1)
        else:
            rng, _rng = jax.random.split(rng)
            sampled_token_idxs = jnp.where(
                step == self.steps - 1,
                jnp.argmax(final_logits, axis=-1),
                jax.random.categorical(_rng, final_logits),
            )
        gather_fn = jax.vmap(jax.vmap(lambda x, y: x[y]))
        final_token_probs = gather_fn(jax.nn.softmax(final_logits), sampled_token_idxs)
        final_token_probs += ~mask
        # Update masked tokens only
        new_token_idxs = jnp.where(mask, sampled_token_idxs, final_token_idxs)

        # --- Update mask ---
        num_unmasked_tokens = jnp.round(N * (1.0 - unmasked_ratio)).astype(int)
        idx_mask = jnp.arange(final_token_probs.shape[-1]) > num_unmasked_tokens
        sorted_idxs = jnp.argsort(final_token_probs, axis=-1, descending=True)
        mask_update_fn = jax.vmap(lambda msk, ids: msk.at[ids].set(idx_mask))
        new_mask = mask_update_fn(mask, sorted_idxs)

        new_carry = (rng, new_token_idxs, new_mask, token_idxs, action_tokens)
        return new_carry, None
[tab] scripts_horeka/modelsize_scaling/tokenizer/train_tokenizer_80M.sbatch (shellscript)
#!/usr/bin/env bash

#SBATCH --nodes=4
#SBATCH --ntasks-per-node=4
#SBATCH --time=15:00:00
#SBATCH --partition=accelerated
#SBATCH --cpus-per-task=5
#SBATCH --gres=gpu:4
#SBATCH --output=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/logs/logs_mihir/%x_%j.log
#SBATCH --error=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/logs/logs_mihir/%x_%j.log
#SBATCH --job-name=train_tokenizer_model_size_scaling_80M

# Log the sbatch script
cat $0

module unload mpi/openmpi/5.0
module unload devel/cuda/12.4
source .venv/bin/activate

tf_records_dir=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/data/open_ai_minecraft_tfrecord
ws_dir='/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/'

job_name=$SLURM_JOB_NAME
slurm_job_id=$SLURM_JOB_ID

CHECKPOINT_DIR=$ws_dir/checkpoints/$job_name_$slurm_job_id
mkdir -p $CHECKPOINT_DIR

env | grep SLURM

srun python train_tokenizer.py \
    --ckpt_dir $CHECKPOINT_DIR \
    --batch_size=96 \
    --min_lr=1e-4 \
    --max_lr=1e-4 \
    --log_image_interval=500 \
    --log_checkpoint_interval=500 \
    --log \
    --name=tokenizer-modelsize-L1-$slurm_job_id \
    --tags tokenizer model-size-scaling L1 80M \
    --entity instant-uv \
    --project jafar \
    --data_dir $tf_records_dir \
    --model_dim=768 \
    --num_blocks=12 \
    --num_heads=12 \
    --latent_dim=64 \
    --num_latents=2048
[tab] scripts_horeka/modelsize_scaling/tokenizer/train_tokenizer_140M.sbatch (shellscript)
#!/usr/bin/env bash

#SBATCH --nodes=8
#SBATCH --ntasks-per-node=4
#SBATCH --time=15:00:00
#SBATCH --partition=accelerated
#SBATCH --cpus-per-task=5
#SBATCH --gres=gpu:4
#SBATCH --output=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/logs/logs_mihir/%x_%j.log
#SBATCH --error=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/logs/logs_mihir/%x_%j.log
#SBATCH --job-name=train_tokenizer_model_size_scaling_140M

# Log the sbatch script
cat $0

module unload mpi/openmpi/5.0
module unload devel/cuda/12.4
source .venv/bin/activate

tf_records_dir=/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/data/open_ai_minecraft_tfrecord
ws_dir='/hkfs/work/workspace/scratch/tum_ind3695-jafa_ws_shared/'

job_name=$SLURM_JOB_NAME
slurm_job_id=$SLURM_JOB_ID

CHECKPOINT_DIR=$ws_dir/checkpoints/$job_name_$slurm_job_id
mkdir -p $CHECKPOINT_DIR

env | grep SLURM

srun python train_tokenizer.py \
    --ckpt_dir $CHECKPOINT_DIR \
    --batch_size=96 \
    --min_lr=1e-4 \
    --max_lr=1e-4 \
    --log_image_interval=500 \
    --log_checkpoint_interval=500 \
    --log \
    --name=tokenizer-modelsize-L2-$slurm_job_id \
    --tags tokenizer model-size-scaling L1 80M \
    --entity instant-uv \
    --project jafar \
    --data_dir $tf_records_dir \
    --model_dim=768 \
    --num_blocks=12 \
    --num_heads=12 \
    --latent_dim=64 \
    --num_latents=2048