huggingface_to_pretrained.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # SPDX-FileCopyrightText: Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
  2. # SPDX-License-Identifier: Apache-2.0
  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. """
  16. python3 hf2pretrained.py --hf-cosyvoice2-llm-path /workspace/rl-exp/checkpoint-400 --output-path /workspace/CosyVoice2-0.5B/llm-new.pt
  17. """
  18. from argparse import ArgumentParser
  19. import torch
  20. from safetensors import safe_open
  21. from transformers import AutoTokenizer
  22. def get_args():
  23. parser = ArgumentParser()
  24. parser.add_argument(
  25. "--hf-cosyvoice2-llm-path",
  26. type=str,
  27. default=None,
  28. help="The RL trained CosyVoice2 model path in HuggingFace format",
  29. )
  30. parser.add_argument(
  31. "--output-path",
  32. type=str,
  33. default="./llm.pt",
  34. help="The path to save the llm.pt",
  35. )
  36. args = parser.parse_args()
  37. return args
  38. if __name__ == "__main__":
  39. args = get_args()
  40. tokenizer = AutoTokenizer.from_pretrained(args.hf_cosyvoice2_llm_path)
  41. speech_start_idx = tokenizer.convert_tokens_to_ids("<|s_0|>")
  42. cosyvoice2_token_size = 6561 + 3
  43. llm_embedding_vocab_size = 2
  44. hf_tensors = {}
  45. with safe_open(f"{args.hf_cosyvoice2_llm_path}/model.safetensors", framework="pt", device="cpu") as f:
  46. for k in f.keys():
  47. if k.startswith("lm_head.bias"):
  48. # RL trained model disable bias for lm_head
  49. continue
  50. new_k = "llm.model." + k
  51. hf_tensors[new_k] = f.get_tensor(k)
  52. if k.startswith("lm_head"):
  53. hf_tensors["llm_decoder.weight"] = f.get_tensor(k)[speech_start_idx:speech_start_idx + cosyvoice2_token_size]
  54. hf_tensors["llm_decoder.bias"] = torch.zeros_like(hf_tensors["llm_decoder.weight"][:, 0])
  55. if k.startswith("model.embed_tokens"):
  56. hf_tensors["speech_embedding.weight"] = f.get_tensor(k)[speech_start_idx:speech_start_idx + cosyvoice2_token_size]
  57. hf_tensors["llm_embedding.weight"] = f.get_tensor(k)[speech_start_idx + cosyvoice2_token_size:speech_start_idx + cosyvoice2_token_size + llm_embedding_vocab_size]
  58. # use tie_word_embeddings=True
  59. hf_tensors["llm.model.model.embed_tokens.weight"] = hf_tensors["llm.model.model.embed_tokens.weight"][:151936]
  60. hf_tensors["llm.model.lm_head.weight"] = hf_tensors["llm.model.model.embed_tokens.weight"]
  61. torch.save(hf_tensors, args.output_path)