class_docstr: Abstract TorchRankerAgent class; only meant to be extended.
  
  TorchRankerAgents aim to provide convenient functionality for building ranking
  models. This includes:
  
  - Training/evaluating on candidates from a variety of sources.
  - Computing hits@1, hits@5, mean reciprical rank (MRR), and other metrics.
  - Caching representations for fast runtime when deploying models to production.
class_docstr_tok: ["Abstract","TorchRankerAgent","class",";","only","meant","to","be","extended",".","TorchRankerAgents","aim","to","provide","convenient","functionality","for","building","ranking","models",".","This","includes",":","-","Training\/evaluating","on","candidates","from","a","variety","of","sources",".","-","Computing","hits","@","1",",","hits","@","5",",","mean","reciprical","rank","(","MRR",")",",","and","other","metrics",".","-","Caching","representations","for","fast","runtime","when","deploying","models","to","production","."]
docstr: Add CLI args.
docstr_tok: ["Add","CLI","args","."]
code: def add_cmdline_args(
      cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None
  ) -> ParlaiParser:
      """
      Add CLI args.
      """
      super().add_cmdline_args(parser, partial_opt=partial_opt)
      agent = parser.add_argument_group("TorchRankerAgent")
      agent.add_argument(
          "-cands",
          "--candidates",
          type=str,
          default="inline",
          choices=["batch", "inline", "fixed", "batch-all-cands"],
          help="The source of candidates during training "
          "(see TorchRankerAgent._build_candidates() for details).",
      )
      agent.add_argument(
          "-ecands",
          "--eval-candidates",
          type=str,
          default="inline",
          choices=[
              "batch",
              "inline",
              "fixed",
              "vocab",
              "batch-all-cands",
          ],
          help="The source of candidates during evaluation (defaults to the same"
          "value as --candidates if no flag is given)",
      )
      agent.add_argument(
          "-icands",
          "--interactive-candidates",
          type=str,
          default="fixed",
          choices=["fixed", "inline", "vocab"],
          help="The source of candidates during interactive mode. Since in "
          "interactive mode, batchsize == 1, we cannot use batch candidates.",
      )
      agent.add_argument(
          "--repeat-blocking-heuristic",
          type="bool",
          default=True,
          help="Block repeating previous utterances. "
          "Helpful for many models that score repeats highly, so switched "
          "on by default.",
      )
      agent.add_argument(
          "-fcp",
          "--fixed-candidates-path",
          type=str,
          help="A text file of fixed candidates to use for all examples, one "
          "candidate per line",
      )
      agent.add_argument(
          "--fixed-candidate-vecs",
          type=str,
          default="reuse",
          help='One of "reuse", "replace", or a path to a file with vectors '
          "corresponding to the candidates at --fixed-candidates-path. "
          "The default path is a /path/to/model-file.<cands_name>, where "
          "<cands_name> is the name of the file (not the full path) passed by "
          "the flag --fixed-candidates-path. By default, this file is created "
          'once and reused. To replace it, use the "replace" option.',
      )
      agent.add_argument(
          "--encode-candidate-vecs",
          type="bool",
          default=True,
          help="Cache and save the encoding of the candidate vecs. This "
          "might be used when interacting with the model in real time "
          "or evaluating on fixed candidate set when the encoding of "
          "the candidates is independent of the input.",
      )
      agent.add_argument(
          "--encode-candidate-vecs-batchsize",
          type=int,
          default=256,
          hidden=True,
          help="Batchsize when encoding candidate vecs",
      )
      agent.add_argument(
          "--init-model",
          type=str,
          default=None,
          help="Initialize model with weights from this file.",
      )
      agent.add_argument(
          "--train-predict",
          type="bool",
          default=False,
          help="Get predictions and calculate mean rank during the train "
          "step. Turning this on may slow down training.",
      )
      agent.add_argument(
          "--cap-num-predictions",
          type=int,
          default=100,
          help="Limit to the number of predictions in output.text_candidates",
      )
      agent.add_argument(
          "--ignore-bad-candidates",
          type="bool",
          default=False,
          help="Ignore examples for which the label is not present in the "
          "label candidates. Default behavior results in RuntimeError. ",
      )
      agent.add_argument(
          "--rank-top-k",
          type=int,
          default=-1,
          help="Ranking returns the top k results of k > 0, otherwise sorts every "
          "single candidate according to the ranking.",
      )
      agent.add_argument(
          "--inference",
          choices={"max", "topk"},
          default="max",
          help="Final response output algorithm",
      )
      agent.add_argument(
          "--topk",
          type=int,
          default=5,
          help="K used in Top K sampling inference, when selected",
      )
      agent.add_argument(
          "--return-cand-scores",
          type="bool",
          default=False,
          help="Return sorted candidate scores from eval_step",
      )
      return parser
  
imports: from typing import Optional
  from parlai.core.params import ParlaiParser
  from typing import Dict, Any
  from abc import abstractmethod
  from itertools import islice
  import os
  from tqdm import tqdm
  import random
  import torch
  from parlai.core.opt import Opt
  from parlai.utils.distributed import is_distributed
  from parlai.core.torch_agent import TorchAgent, Output
  from parlai.utils.misc import warn_once
  from parlai.utils.io import PathManager
  from parlai.utils.torch import padded_3d, total_parameters, trainable_parameters, PipelineHelper
  from parlai.utils.fp16 import FP16SafeCrossEntropy
  from parlai.core.metrics import AverageMetric
  import parlai.utils.logging
label_desc: Use image node_id 1 for calling the TorchRankerAgent obj's underlying member method code with example usage: obj.add_cmdline_args(cls, parser, partial_opt) and returns: parser