Subtask Generation Issue: Missing first few words
Copied from pi0 and pi0-fast, I tried to reproduce the subtask generation capability of pi05. Here are my reproduced results:
pi05: to the center of the table.
Subtask Label: Move to the center of the table.
pi05: left side of the knife and place the knife and fork.
Subtask Label: Move to the left side of the knife and place the knife and fork.
pi05: to the right position and place the plate.
Subtask Label: Move to the right position and place the plate.
The overall sentence-level prediction is basically correct, but pi05 consistently forget to predict either the first word or the first few words. Is there any explanation to that?
The format of my high-level prompt+low-level prompt is like this:
<bos> {high-level prompt}. Subtask: {Low-level prompt}. <eos>
Is there any problem with my text prompting?
Here is my inference code:
@override
def sample_low_level_task(
self,
rng: at.KeyArrayLike,
observation: _model.Observation,
max_decoding_steps: int = 100,
PALIGEMMA_EOS_TOKEN: int = 1,
temperature: float = 0.1
) -> str:
assert observation.tokenized_prompt_mask.shape[-1] // 2 == max_decoding_steps, f'observation.tokenized_prompt_mask.shape[-1] // 2 must be equal to max_decoding_steps, but got {observation.tokenized_prompt_mask.shape[-1] // 2} and {max_decoding_steps}'
tokenizer = _tokenizer.PaligemmaTokenizer(200)
# Due to decode, we have to discard the low level task tokens
full_observation = observation
observation = _model.Observation(
images=observation.images,
image_masks=observation.image_masks,
state=observation.state,
tokenized_prompt=observation.tokenized_prompt[:, :-max_decoding_steps],
tokenized_prompt_mask=observation.tokenized_prompt_mask[:, :-max_decoding_steps],
token_ar_mask=observation.token_ar_mask[:, :-max_decoding_steps],
token_loss_mask=observation.token_loss_mask[:, :-max_decoding_steps],
)
observation = _model.preprocess_observation(None, observation, train=False, image_keys=list(observation.images.keys()))
# embed inputs [image] + [high-level prompt]
prefix_token_embeddings, prefix_mask, prefix_ar_mask = self.embed_prefix(observation)
prefix_attn_mask = make_attn_mask(prefix_mask, prefix_ar_mask)
# left to right align all input token sequences
prefix_token_embeddings, prefix_mask, prefix_attn_mask = left_to_right_align(
prefix_token_embeddings, prefix_mask, prefix_attn_mask
)
prefill_size = prefix_token_embeddings.shape[1]
prefill_len = jnp.sum(prefix_mask, axis=-1)
prefix_start = prefill_size - prefill_len
# first fill KV cache with a forward pass of the prefix
# pad attention mask to set the size of the KV cache (prefill_size + max_decoding_steps)
prefix_attn_mask = jnp.pad(prefix_attn_mask, ((0, 0), (0, 0), (0, max_decoding_steps)))
prefix_positions = jnp.cumsum(prefix_mask, axis=-1) - 1
(prefix_out, _), kv_cache = self.PaliGemma.llm(
[prefix_token_embeddings, None], mask=prefix_attn_mask, positions=prefix_positions, adarms_cond=[None, None]
)
# prepare decoding -- final logit decodes the first token
last_logit = prefix_out[:, -1:]
last_logit = self.PaliGemma.llm(last_logit, method='deembed')
output_tokens = jnp.zeros((last_logit.shape[0], max_decoding_steps))
def step(carry):
rng, last_logit, output_tokens, cache, _, step = carry
# Sample token from last logit
# Split RNG for this step
rng, rng_step = jax.random.split(rng)
token = jax.lax.cond(
temperature > 0.0,
lambda _: jax.random.categorical(rng_step, last_logit / temperature, axis=-1),
lambda _: jnp.argmax(last_logit, axis=-1),
operand=None,
)
output_tokens = put_along_last_axis(output_tokens, jnp.broadcast_to(step, (token.shape[0], 1)), token)
# Check for early stopping --> stop if all batch elements have EOS token
has_eos = jnp.any(token == PALIGEMMA_EOS_TOKEN, axis=-1)
all_eos = jnp.all(has_eos)
# Decode one step
token_embedding = self.PaliGemma.llm(token, method="embed")
positions = prefill_len[:, None] + step
mask = jnp.logical_and(
jnp.arange(prefill_size + max_decoding_steps)[None, None, :] >= prefix_start[:, None, None],
jnp.arange(prefill_size + max_decoding_steps)[None, None, :]
< (jnp.broadcast_to(prefill_size + step + 1, (prefix_start.shape[0], 1, 1))),
)
(prefix_out, _), kv_cache = self.PaliGemma.llm(
[token_embedding, None], mask=mask, positions=positions, adarms_cond=[None, None], kv_cache=cache
)
logits = self.PaliGemma.llm(prefix_out[:, -1:], method='deembed')
last_logit = logits
# jax.debug.breakpoint()
return rng, last_logit, output_tokens, kv_cache, all_eos, step + 1
def cond(carry):
_, _, _, _, all_eos, step = carry
return (~all_eos) & (step < max_decoding_steps)
# Use lax.while_loop so we can jit the full decoding loop.
_, _, output_tokens, _, _, _ = jax.lax.while_loop(
cond, step, (rng, last_logit, output_tokens, kv_cache, False, 0)
)
for i in range(output_tokens.shape[0]):
logging.info(tokenizer.detokenize(np.array(output_tokens[i], dtype=np.int32)))
logging.info('-'*50)
logging.info(tokenizer.detokenize(full_observation.tokenized_prompt[i][full_observation.token_loss_mask[i]]))
logging.info('-'*100)
Note that I did not use your default gemma.py for pi0, I wrote a new gemma05.py. If you need to take a look at that, I can post it in the following part.
@BrunoFANG1 I'm trying to reproduce your method, but the line:
(prefix_out, _), kv_cache = self.PaliGemma.llm(
[prefix_token_embeddings, None], mask=prefix_attn_mask, positions=prefix_positions, adarms_cond=[None, None]
)
ends up in the following error:
ValueError: Attention mask with shape (1, 1, 868, 968) but shapes for q and k are: (1, 868, 1, 8, 256) and (1, 868, 1, 256)
The shapes of the variables used in that computation are as follow:
prefix_token_embeddings shape: (1, 868, 2048)
prefix_attn_mask shape: (1, 868, 968)
prefix_positions shape: (1, 868)
I set max_decoding_steps = 100. What am I missing?
I have a different PaliGemma.llm written in a customer Gemma_05.py. I did not use the original Gemma.py
That's exciting! I am also working to reproduce this functionality, could you share your fork for review? Thanks
@tahsinkose @Everloom-129 My coding is messy, but you should be able to play around with subtask-generation according to this tmp repo and tmp code. Feel free to ask me questions.
https://github.com/BrunoFANG1/openpi_subtask_generation/blob/main/tmp_test/test_pi05_subtask_generation.py
spoiler alert: you cannot get perfect low-level prompt by directly using their default checkpoint, but you can train it to do that within a few gradient steps (less than 100 steps, you will get some normal English sentence).
@tahsinkose @Everloom-129 My coding is messy, but you should be able to play around with subtask-generation according to this tmp repo and tmp code. Feel free to ask me questions.
https://github.com/BrunoFANG1/openpi_subtask_generation/blob/main/tmp_test/test_pi05_subtask_generation.py
spoiler alert: you cannot get perfect low-level prompt by directly using their default checkpoint, but you can train it to do that within a few gradient steps (less than 100 steps, you will get some normal English sentence).
The core modification compared to original pi05 is that:
- I wrote my own gemma_05.py instead of reused the Gemma.py
- I wrote my own pi05.py instead of building on top of pi0.py (Please take a look at compute_loss and sample_low_level_prompt)
- Check the tokenizer.py (Please take a look at tokenize_high_low_prompt)
Note: For private reasons, the training code is not released, and you should write your own data loading code and training script. The provided repo only has the correct model + test code. The training code in the repo is absolutely incorrect and obsolete.
@BrunoFANG1 What is the amount of training data? Is it the high-level and low-level text data you collected yourself?
Awesome! Have you implemented a subtask generation that is not officially open source in OpenPI pi05?
@1018weijia I have not tried large scale training yet, but you should be able to feel the subtask generation capability from the original checkpoint of pi05.
@BrunoFANG1 thanks for your shared code. And I have seen the capability by finetuning it with a small dataset.
can this model output any English sentence without training just on the base checkpoint? I tried to adapt @BrunoFANG1 's method and was able to get only "⤙ߑ🪛立Ԇꓤ팹팹팹팹팹팹팹팹팹팹팹팹팹팹팹팹팹팹팹" as the output. Is there anything that I might be missing?
Hi! Great work! I wonder have you ever attempted to reproduce the ability of generating discretized action tokens and are they accurate? Thanks!
I didn't try the discretized action tokens, but I have tried flow action which works normal.
@BrunoFANG1 thanks for your shared code. And I have seen the capability by finetuning it with a small dataset.
hi, I also tried fine-tuning with this, but the fine-tuning performance is even worse than zero-shot. I wonder what data format did you use? ( standard lerobot format? ) And in the end, does it have the capability for subtask generation?
@BrunoFANG1 Thanks for your work! Have you tested the model's performance on manipulation tasks after fine-tuning backbone on 'subtask'? Does this type of fine-tuning improve or hinder the manipulation performance?
It definitely increased success rate for long-horizon tasks, especially for tasks that has clear boundaries.
@BrunoFANG1 , did you use the state in the prompt?
can this model output any English sentence without training just on the base checkpoint? I tried to adapt @BrunoFANG1 's method and was able to get only "⤙ߑ🪛立Ԇꓤ팹팹팹팹팹팹팹팹팹팹팹팹팹팹팹팹팹팹팹" as the output. Is there anything that I might be missing?
It's same to me. This is likely because the VLA model you loaded—which was fine-tuned on specific tasks like DROID or LIBERO—has significantly degraded language understanding. This happens because, during the fine-tuning process, the loss was only calculated for the actions.
I’ve polished the subtask's training and inference code and addressed this issue. If you find it helpful, please drop a star! ⭐https://github.com/LisavilaLee/openpi_with_subtask
The first subtask tokens were wrong because we took the hidden state from the wrong position. We used “number of valid tokens minus one” as a sequence index, but when the prefix has masked regions (e.g. unused camera), that index can land on a masked position. The fix is to use the index of the last valid token in the sequence instead.
File: src/openpi/models/pi0.py (in generate_subtask)
Before (wrong):
last_pos = jnp.sum(prefix_mask, axis=1) - 1 # count - 1, can point into a masked hole
last_hidden = prefix_out[jnp.arange(B), last_pos, :]
After (correct):
seq_indices = jnp.arange(prefix_S)[None, :] # [1, S]
last_pos = jnp.max(
jnp.where(prefix_mask, seq_indices, -1), axis=1
).astype(jnp.int32) # index of last valid token
last_hidden = prefix_out[jnp.arange(B), last_pos, :]
Hi @LisavilaLee , thanks for sharing your implementation of the subtask generation! I am curious what sub-task data for Libero did you train it on? Also, it seems in your implementation you removed the state in the tokenizer when creating the full prompt "task: < >. Subtask: <>", why is that? Curious if it works well with this style of tokenization.
Hi @LisavilaLee , thanks for sharing your implementation of the subtask generation! I am curious what sub-task data for Libero did you train it on? Also, it seems in your implementation you removed the state in the tokenizer when creating the full prompt "task: < >. Subtask: <>", why is that? Curious if it works well with this style of tokenization.
Hi @prachigarg23! Thanks for your interest in my work. To answer your questions:
- Regarding sub-task data: I’m not entirely sure if you're referring to the Libero task suites or the specific dataset used for subtask annotations.
Task suites: For my Pi0.5 implementation with subtasks, I followed the Physical Intelligence team's default settings, using all datasets except the Libero-90 suite. You can find the details in examples/libero/convert_libero_data_to_lerobot.py and the examples/libero/README.md.
Subtask annotations: Regarding the datasets, if you check the TokenizeSubtaskTraining(DataTransformFn) class in src/openpi/transforms.py within my repository (LisavilaLee/openpi_with_subtask), you will see the following code:
Python
# --- Identity subtask: high = low = prompt ---
# Swap in real subtask annotations here when available.
high_prompt = prompt
low_prompt = prompt
This means I haven't performed manual subtask annotation yet; I'm currently using identity tasks. Although Physical Intelligence mentioned their subtask-annotated datasets in their paper, it appears they haven't been released yet.
- Regarding the state in the tokenizer: I am also following Physical Intelligence’s default configuration here. While the Pi0.5 model usually enables discrete state input by default (discrete_state_input=True), the Libero-specific training configurations defined in src/openpi/training/config.py explicitly disable this option.
During the data loading process, the TokenizePrompt transform reads this configuration. Since discrete_state_input is set to False, it passes the state variable to the tokenizer as None. For pi05_libero training, the system treats the state as a continuous vector fed into the Action Expert (similar to the Pi0 architecture), rather than as discrete tokens within the language model prefix.