code: def extract_xglm_weights(
      output_file,
      model_dir,
      head_num,
      generation_method,
      topk=10,
      topp=0.75,
      eos_id=50256,
      pad_id=50257,
      max_step=100,
      extra_decode_length=0,
  ):
      # load var names
      encoder_state_dict = XGLMForCausalLM.from_pretrained(
          model_dir
      ).state_dict()
      enc_var_name_list = list(encoder_state_dict.keys())
  
      # initialize output file
      output_file += ".hdf5"
      print("Saving model to hdf5...")
      print("Writing to {0}".format(output_file))
      hdf5_file = h5py.File(output_file, "w")
  
      # fill each encoder layer's params
      enc_tensor_names = {}
      for name in enc_var_name_list:
          name_split = name.split(".")
          if len(name_split) <= 2 or not name_split[2].isdigit():
              continue
          layer_id = int(name_split[2])
          enc_tensor_names.setdefault(layer_id, []).append(name)
  
      # fill encoder_stack
      for layer_id in sorted(enc_tensor_names.keys()):
          fill_hdf5_layer(
              enc_tensor_names[layer_id],
              encoder_state_dict,
              hdf5_file,
              f"encoder_stack/{layer_id}/",
              enc_layer_mapping_dict,
          )
  
      # fill src_embedding - except for position embedding
      fill_hdf5_layer(
          enc_var_name_list,
          encoder_state_dict,
          hdf5_file,
          "src_embedding/",
          src_emb_mapping_dict,
      )
  
      token_emb = encoder_state_dict["model.embed_tokens.weight"]
  
      # scale embedding
      scale = math.sqrt(token_emb.shape[1])
      token_embedding = (token_emb.flatten() * scale).tolist()
  
      hdf5_file.create_dataset(
          "src_embedding/token_embedding",
          data=token_embedding,
          dtype="f4",
      )
  
      # special handling for position embedding
      position_emb = encoder_state_dict["model.embed_positions.weights"]
      _max_allowed_step, _hidden_size = position_emb.shape
      if max_step > _max_allowed_step:
          print(f"max_step {max_step} exceed max allowed step, abort.")
          return
      # truncate position embedding for max_step
      position_emb = position_emb[:max_step, :]
      print(
          f"processed position_embedding with max_step constriant, shape: {position_emb.shape}"
      )
      position_emb = position_emb.flatten().tolist()
      hdf5_file.create_dataset(
          "src_embedding/position_embedding",
          data=position_emb,
          dtype="f4",
      )
  
      # save number of layers metadata
      hdf5_file.create_dataset(
          "model_conf/n_encoder_stack",
          data=len(enc_tensor_names),
          dtype="i4",
      )
      # fill in model_conf
      hdf5_file.create_dataset(
          "model_conf/head_num", data=head_num, dtype="i4"
      )
      hdf5_file.create_dataset(
          "model_conf/src_padding_id", data=pad_id, dtype="i4"
      )
      hdf5_file.create_dataset(
          "model_conf/sampling_method",
          data=np.array([ord(c) for c in generation_method]).astype(
              np.int8
          ),
          dtype="i1",
      )
      hdf5_file.create_dataset("model_conf/topp", data=topp, dtype="f4")
      hdf5_file.create_dataset("model_conf/topk", data=topk, dtype="i4")
      hdf5_file.create_dataset(
          "model_conf/eos_id", data=eos_id, dtype="i4"
      )
      hdf5_file.create_dataset(
          "model_conf/extra_decode_length",
          data=extra_decode_length,
          dtype="i4",
      )
  
      hdf5_file.close()
      # read-in again to double check
      hdf5_file = h5py.File(output_file, "r")
  
      def _print_pair(key, value):
          if key == "sampling_method":
              value = "".join(map(chr, value[()]))
          else:
              value = value[()]
          print(f"{key}: {value}")
  
      list(
          map(
              lambda x: _print_pair(*x), hdf5_file["model_conf"].items()
          )
      )
  
file_path: lightseq/examples/inference/python/export/huggingface/hf_xglm_export.py
imports: import os
  import h5py
  import numpy
  from collections import OrderedDict
  from transformers import AutoTokenizer, XGLMForCausalLM
  from lightseq.training.ops.pytorch.export import fill_hdf5_layer
  import math
label_desc: Use image node_id 1 for calling a global function with example usage: extract_xglm_weights(output_file, model_dir, head_num, generation_method, topk, topp, eos_id, pad_id, max_step, extra_decode_length) without return types