length_cdf.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # coding=utf-8
  2. # Copyright 2024 the LlamaFactory team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from collections import defaultdict
  16. import fire
  17. from tqdm import tqdm
  18. from llamafactory.data import get_dataset, get_template_and_fix_tokenizer
  19. from llamafactory.hparams import get_train_args
  20. from llamafactory.model import load_tokenizer
  21. def length_cdf(
  22. model_name_or_path: str,
  23. dataset: str = "alpaca_en_demo",
  24. dataset_dir: str = "data",
  25. template: str = "default",
  26. interval: int = 1000,
  27. ):
  28. r"""
  29. Calculates the distribution of the input lengths in the dataset.
  30. Usage: python length_cdf.py --model_name_or_path path_to_model --dataset alpaca_en_demo --template default
  31. """
  32. model_args, data_args, training_args, _, _ = get_train_args(
  33. dict(
  34. stage="sft",
  35. model_name_or_path=model_name_or_path,
  36. dataset=dataset,
  37. dataset_dir=dataset_dir,
  38. template=template,
  39. cutoff_len=1_000_000,
  40. output_dir="dummy_dir",
  41. overwrite_cache=True,
  42. do_train=True,
  43. )
  44. )
  45. tokenizer_module = load_tokenizer(model_args)
  46. template = get_template_and_fix_tokenizer(tokenizer_module["tokenizer"], data_args)
  47. trainset = get_dataset(template, model_args, data_args, training_args, "sft", **tokenizer_module)["train_dataset"]
  48. total_num = len(trainset)
  49. length_dict = defaultdict(int)
  50. for sample in tqdm(trainset["input_ids"]):
  51. length_dict[len(sample) // interval * interval] += 1
  52. length_tuples = list(length_dict.items())
  53. length_tuples.sort()
  54. count_accu, prob_accu = 0, 0
  55. for length, count in length_tuples:
  56. count_accu += count
  57. prob_accu += count / total_num * 100
  58. print("{:d} ({:.2f}%) samples have length < {}.".format(count_accu, prob_accu, length + interval))
  59. if __name__ == "__main__":
  60. fire.Fire(length_cdf)