code: def main(args, task=None, model_state=None):
      check_args(args)
  
      use_fp16 = args.fp16
      if args.max_tokens is None and args.batch_size is None:
          args.max_tokens = 4000000
      logger.info(args)
  
      use_cuda = torch.cuda.is_available() and not args.cpu
  
      logger.info("| decoding with criterion {}".format(args.criterion))
  
      task = tasks.setup_task(args)
  
      # Load ensemble
      if args.load_emissions:
          models, criterions = [], []
          task.load_dataset(args.gen_subset)
      else:
          logger.info("| loading model(s) from {}".format(args.path))
          (
              models,
              saved_cfg,
              task,
          ) = checkpoint_utils.load_model_ensemble_and_task(
              utils.split_paths(args.path, separator="\\"),
              arg_overrides=ast.literal_eval(args.model_overrides),
              task=task,
              suffix=args.checkpoint_suffix,
              strict=(args.checkpoint_shard_count == 1),
              num_shards=args.checkpoint_shard_count,
              state=model_state,
          )
          optimize_models(args, use_cuda, models)
          task.load_dataset(args.gen_subset, task_cfg=saved_cfg.task)
  
      # Set dictionary
      tgt_dict = task.target_dictionary
  
      logger.info(
          "| {} {} {} examples".format(
              args.data,
              args.gen_subset,
              len(task.dataset(args.gen_subset)),
          )
      )
  
      # hack to pass transitions to W2lDecoder
      if args.criterion == "asg_loss":
          raise NotImplementedError(
              "asg_loss is currently not supported"
          )
          # trans = criterions[0].asg.trans.data
          # args.asg_transitions = torch.flatten(trans).tolist()
  
      # Load dataset (possibly sharded)
      itr = get_dataset_itr(args, task, models)
  
      # Initialize generator
      gen_timer = StopwatchMeter()
  
      def build_generator(args):
          w2l_decoder = getattr(args, "w2l_decoder", None)
          if w2l_decoder == "viterbi":
              from examples.speech_recognition.w2l_decoder import (
                  W2lViterbiDecoder,
              )
  
              return W2lViterbiDecoder(args, task.target_dictionary)
          elif w2l_decoder == "kenlm":
              from examples.speech_recognition.w2l_decoder import (
                  W2lKenLMDecoder,
              )
  
              return W2lKenLMDecoder(args, task.target_dictionary)
          elif w2l_decoder == "fairseqlm":
              from examples.speech_recognition.w2l_decoder import (
                  W2lFairseqLMDecoder,
              )
  
              return W2lFairseqLMDecoder(args, task.target_dictionary)
          else:
              print(
                  "only flashlight decoders with (viterbi, kenlm, fairseqlm) options are supported at the moment"
              )
  
      # please do not touch this unless you test both generate.py and infer.py with audio_pretraining task
      generator = build_generator(args)
  
      if args.load_emissions:
          generator = ExistingEmissionsDecoder(
              generator, np.load(args.load_emissions, allow_pickle=True)
          )
          logger.info("loaded emissions from " + args.load_emissions)
  
      num_sentences = 0
  
      if args.results_path is not None and not os.path.exists(
          args.results_path
      ):
          os.makedirs(args.results_path)
  
      max_source_pos = (
          utils.resolve_max_positions(
              task.max_positions(),
              *[model.max_positions() for model in models],
          ),
      )
  
      if max_source_pos is not None:
          max_source_pos = max_source_pos[0]
          if max_source_pos is not None:
              max_source_pos = max_source_pos[0] - 1
  
      if args.dump_emissions:
          emissions = {}
      if args.dump_features:
          features = {}
          models[0].bert.proj = None
      else:
          res_files = prepare_result_files(args)
      errs_t = 0
      lengths_t = 0
      with progress_bar.build_progress_bar(args, itr) as t:
          wps_meter = TimeMeter()
          for sample in t:
              sample = (
                  utils.move_to_cuda(sample) if use_cuda else sample
              )
              if use_fp16:
                  sample = utils.apply_to_sample(apply_half, sample)
              if "net_input" not in sample:
                  continue
  
              prefix_tokens = None
              if args.prefix_size > 0:
                  prefix_tokens = sample["target"][
                      :, : args.prefix_size
                  ]
  
              gen_timer.start()
              if args.dump_emissions:
                  with torch.no_grad():
                      encoder_out = models[0](**sample["net_input"])
                      emm = models[0].get_normalized_probs(
                          encoder_out, log_probs=True
                      )
                      emm = emm.transpose(0, 1).cpu().numpy()
                      for i, id in enumerate(sample["id"]):
                          emissions[id.item()] = emm[i]
                      continue
              elif args.dump_features:
                  with torch.no_grad():
                      encoder_out = models[0](**sample["net_input"])
                      feat = (
                          encoder_out["encoder_out"]
                          .transpose(0, 1)
                          .cpu()
                          .numpy()
                      )
                      for i, id in enumerate(sample["id"]):
                          padding = (
                              encoder_out["encoder_padding_mask"][i]
                              .cpu()
                              .numpy()
                              if encoder_out["encoder_padding_mask"]
                              is not None
                              else None
                          )
                          features[id.item()] = (feat[i], padding)
                      continue
              hypos = task.inference_step(
                  generator, models, sample, prefix_tokens
              )
              num_generated_tokens = sum(
                  len(h[0]["tokens"]) for h in hypos
              )
              gen_timer.stop(num_generated_tokens)
  
              for i, sample_id in enumerate(sample["id"].tolist()):
                  speaker = None
                  # id = task.dataset(args.gen_subset).ids[int(sample_id)]
                  id = sample_id
                  toks = (
                      sample["target"][i, :]
                      if "target_label" not in sample
                      else sample["target_label"][i, :]
                  )
                  target_tokens = (
                      utils.strip_pad(toks, tgt_dict.pad()).int().cpu()
                  )
                  # Process top predictions
                  errs, length = process_predictions(
                      args,
                      hypos[i],
                      None,
                      tgt_dict,
                      target_tokens,
                      res_files,
                      speaker,
                      id,
                  )
                  errs_t += errs
                  lengths_t += length
  
              wps_meter.update(num_generated_tokens)
              t.log({"wps": round(wps_meter.avg)})
              num_sentences += (
                  sample["nsentences"]
                  if "nsentences" in sample
                  else sample["id"].numel()
              )
  
      wer = None
      if args.dump_emissions:
          emm_arr = []
          for i in range(len(emissions)):
              emm_arr.append(emissions[i])
          np.save(args.dump_emissions, emm_arr)
          logger.info(
              f"saved {len(emissions)} emissions to {args.dump_emissions}"
          )
      elif args.dump_features:
          feat_arr = []
          for i in range(len(features)):
              feat_arr.append(features[i])
          np.save(args.dump_features, feat_arr)
          logger.info(
              f"saved {len(features)} emissions to {args.dump_features}"
          )
      else:
          if lengths_t > 0:
              wer = errs_t * 100.0 / lengths_t
              logger.info(f"WER: {wer}")
  
          logger.info(
              "| Processed {} sentences ({} tokens) in {:.1f}s ({:.2f}"
              "sentences/s, {:.2f} tokens/s)".format(
                  num_sentences,
                  gen_timer.n,
                  gen_timer.sum,
                  num_sentences / gen_timer.sum,
                  1.0 / gen_timer.avg,
              )
          )
          logger.info(
              "| Generate {} with beam={}".format(
                  args.gen_subset, args.beam
              )
          )
      return task, wer
  
imports: import ast
  import logging
  import math
  import os
  import sys
  import editdistance
  import numpy
  import torch
  from fairseq import checkpoint_utils, options, progress_bar, tasks, utils
  from fairseq.data.data_utils import post_process
  from fairseq.logging.meters import StopwatchMeter, TimeMeter
label_desc: Use image node_id 8 for calling a global function with example usage: main(args, task, model_state) and returns: task,  wer, W2lViterbiDecoder, W2lKenLMDecoder, W2lFairseqLMDecoder