config.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. from typing import Optional
  2. from transformers import AutoConfig, PretrainedConfig
  3. from transformers.models.auto.configuration_auto import CONFIG_MAPPING
  4. from aphrodite.common.gguf import GGUFReader
  5. from aphrodite.transformers_utils.configs import (BaiChuanConfig,
  6. ChatGLMConfig, DbrxConfig,
  7. JambaConfig, MPTConfig,
  8. QWenConfig, RWConfig)
  9. _CONFIG_REGISTRY = {
  10. "baichuan": BaiChuanConfig,
  11. "chatglm": ChatGLMConfig,
  12. "dbrx": DbrxConfig,
  13. "mpt": MPTConfig,
  14. "qwen": QWenConfig,
  15. "RefinedWeb": RWConfig, # For tiiuae/falcon-40b(-instruct)
  16. "RefinedWebModel": RWConfig, # For tiiuae/falcon-7b(-instruct)
  17. "jamba": JambaConfig,
  18. }
  19. def extract_gguf_config(checkpoint):
  20. result = GGUFReader(checkpoint)
  21. architecture = result.fields['general.architecture']
  22. architecture = str(bytes(architecture.parts[architecture.data[0]]),
  23. encoding='utf-8')
  24. # Only support llama so far
  25. if architecture != "llama":
  26. raise RuntimeError(f"Unsupported architecture {architecture}, "
  27. "only llama is supported.")
  28. # write config
  29. vocab_size = len(result.fields['tokenizer.ggml.token_type'].data)
  30. context_length = int(result.fields['llama.context_length'].parts[-1])
  31. n_layer = int(result.fields['llama.block_count'].parts[-1])
  32. n_head = int(result.fields['llama.attention.head_count'].parts[-1])
  33. n_local_heads = int(
  34. result.fields['llama.attention.head_count_kv'].parts[-1])
  35. intermediate_size = int(
  36. result.fields['llama.feed_forward_length'].parts[-1])
  37. norm_eps = float(
  38. result.fields['llama.attention.layer_norm_rms_epsilon'].parts[-1])
  39. dim = int(result.fields['llama.embedding_length'].parts[-1])
  40. arch = "MixtralForCausalLM"
  41. if 'llama.expert_count' in result.fields:
  42. arch = "MixtralForCausalLM"
  43. name = "mixtral"
  44. else:
  45. arch = "LlamaForCausalLM"
  46. name = "llama"
  47. model_config = {
  48. "architectures": [arch],
  49. "bos_token_id": 1,
  50. "eos_token_id": 2,
  51. "hidden_act": "silu",
  52. "hidden_size": dim,
  53. "intermediate_size": intermediate_size,
  54. "max_position_embeddings": context_length,
  55. "model_type": name,
  56. "num_attention_heads": n_head,
  57. "num_hidden_layers": n_layer,
  58. "num_key_value_heads": n_local_heads,
  59. "rms_norm_eps": norm_eps,
  60. "torch_dtype": "float16",
  61. "vocab_size": vocab_size
  62. }
  63. if 'llama.rope.freq_base' in result.fields:
  64. model_config['rope_theta'] = float(
  65. result.fields['llama.rope.freq_base'].parts[-1])
  66. if 'llama.expert_count' in result.fields:
  67. model_config['num_local_experts'] = int(
  68. result.fields['llama.expert_count'].parts[-1])
  69. model_config['num_experts_per_tok'] = int(
  70. result.fields['llama.expert_used_count'].parts[-1])
  71. if name in _CONFIG_REGISTRY:
  72. config_class = _CONFIG_REGISTRY[name]
  73. else:
  74. config_class = CONFIG_MAPPING[name]
  75. hf_config = config_class.from_dict(model_config)
  76. return hf_config
  77. def get_config(model: str,
  78. trust_remote_code: bool,
  79. revision: Optional[str] = None,
  80. code_revision: Optional[str] = None) -> PretrainedConfig:
  81. if model.endswith("gguf"):
  82. return extract_gguf_config(model)
  83. try:
  84. config = AutoConfig.from_pretrained(
  85. model,
  86. trust_remote_code=trust_remote_code,
  87. revision=revision,
  88. code_revision=code_revision)
  89. except ValueError as e:
  90. if (not trust_remote_code and
  91. "requires you to execute the configuration file" in str(e)):
  92. err_msg = (
  93. "Failed to load the model config. If the model is a custom "
  94. "model not yet available in the HuggingFace transformers "
  95. "library, consider setting `trust_remote_code=True` in LLM "
  96. "or using the `--trust-remote-code` flag in the CLI.")
  97. raise RuntimeError(err_msg) from e
  98. else:
  99. raise e
  100. if config.model_type in _CONFIG_REGISTRY:
  101. config_class = _CONFIG_REGISTRY[config.model_type]
  102. config = config_class.from_pretrained(model,
  103. revision=revision,
  104. code_revision=code_revision)
  105. return config
  106. def get_hf_text_config(config: PretrainedConfig):
  107. """Get the `sub` config relevant to multimodal models.
  108. No-op for text models.
  109. """
  110. if hasattr(config, "text_config"):
  111. # The code operates under the assumption that
  112. # text_config should have `num_attention_heads`
  113. # (among others). Assert here to fail early
  114. # if transformer config doesn't align with
  115. # the assumption.
  116. assert hasattr(config.text_config, "num_attention_heads")
  117. return config.text_config
  118. else:
  119. return config