Changes in modelling_RW.py to be able to handle past_key_values for faster model generations

#60
by purunfer22 - opened

The current code has missed out passing past_key_values in every forward pass for fast generation of tokens. This results in lot of recompute. This "modelling_RW.py" I am uploading deals with this in the way pytorch huggingface transformers package generation/utils.py wants. All the changes are basically around including past_key_values everywhere. I think this will apply on all falcon models These are the changes specifically

  1. Class RotaryEmbedding forward method
    Include past_seq_length in forward pass and apply rotary embedding according to the position of the query token ---- if else condition added (line number 100-103)

  2. _make_causal_mask function
    to give masking according to the way F.scaled dot product attention behaves. F.scaled_dot_product attention treats the attention_mask matrix as receiving attentions. For example if attention_mask is
    [[True, False], [True, True]]. It would mean the first token is "receiving" attentions from first token and not second token. This is unlike what we generally end up thinking which is first token is giving attention to itself and not to the second one. Due to reason the past_key_values attentions are all True in make_causal mask function. Also I have reversed the inequality above that due to the same reason. ---- (line number 114 inequality, line number 117 attention mask to be True)

  3. Class Attention forward method
    a) past_key_value length is passed in rotary function ---- if,else loop added (line number 271-277)
    b) concatenation of past key and current key is done after permuting the past key shape to match the current key shape ---- (line number 280-284)
    c) to keep key_layer shape consistent with the output expectation which is (batch_size, head_dim, seq_length), another permutation done before creating "present" to return in the output ---- (line number 289-293)

  4. RW Model prepare_attn_mask
    Have removed src_length > 1 criteria for making causal mask (line number 554).

  5. RW causal LM prepare inputs for generation
    Read pastkey values from the input coming from huggingface generate method and dont call convert_to_rw_cache method (line number 740-748)

purunfer22 changed pull request status to closed

There are some excerpts in the file which should be removed and hence I have closed this pull request and will raise another

Sign up or log in to comment