code: def _instantiate_KG(
      model: Model,
      objective: Optional[MCAcquisitionObjective] = None,
      posterior_transform: Optional[PosteriorTransform] = None,
      qmc: bool = True,
      n_fantasies: int = 64,
      mc_samples: int = 256,
      num_trace_observations: int = 0,
      seed_inner: Optional[int] = None,
      seed_outer: Optional[int] = None,
      X_pending: Optional[Tensor] = None,
      current_value: Optional[Tensor] = None,
      target_fidelities: Optional[Dict[int, float]] = None,
      fidelity_weights: Optional[Dict[int, float]] = None,
      cost_intercept: float = 1.0,
  ) -> qKnowledgeGradient:
      r"""Instantiate either a `qKnowledgeGradient` or `qMultiFidelityKnowledgeGradient`
      acquisition function depending on whether `target_fidelities` is defined.
      """
      sampler_cls = SobolQMCNormalSampler if qmc else IIDNormalSampler
      fantasy_sampler = sampler_cls(
          sample_shape=torch.Size([n_fantasies]), seed=seed_outer
      )
      if isinstance(objective, MCAcquisitionObjective):
          inner_sampler = sampler_cls(
              sample_shape=torch.Size([mc_samples]), seed=seed_inner
          )
      else:
          inner_sampler = None
      if target_fidelities:
          if fidelity_weights is None:
              fidelity_weights = {f: 1.0 for f in target_fidelities}
          if not set(target_fidelities) == set(fidelity_weights):
              raise RuntimeError(
                  "Must provide the same indices for target_fidelities "
                  f"({set(target_fidelities)}) and fidelity_weights "
                  f" ({set(fidelity_weights)})."
              )
          cost_model = AffineFidelityCostModel(
              fidelity_weights=fidelity_weights,
              fixed_cost=cost_intercept,
          )
          cost_aware_utility = InverseCostWeightedUtility(
              cost_model=cost_model
          )
  
          def project(X: Tensor) -> Tensor:
              return project_to_target_fidelity(
                  X=X, target_fidelities=target_fidelities
              )
  
          def expand(X: Tensor) -> Tensor:
              return expand_trace_observations(
                  X=X,
                  fidelity_dims=sorted(
                      target_fidelities
                  ),  # pyre-ignore: [6]
                  num_trace_obs=num_trace_observations,
              )
  
          return qMultiFidelityKnowledgeGradient(
              model=model,
              num_fantasies=n_fantasies,
              sampler=fantasy_sampler,
              objective=objective,
              posterior_transform=posterior_transform,
              inner_sampler=inner_sampler,
              X_pending=X_pending,
              current_value=current_value,
              cost_aware_utility=cost_aware_utility,
              project=project,
              expand=expand,
          )
  
      return qKnowledgeGradient(
          model=model,
          num_fantasies=n_fantasies,
          sampler=fantasy_sampler,
          objective=objective,
          posterior_transform=posterior_transform,
          inner_sampler=inner_sampler,
          X_pending=X_pending,
          current_value=current_value,
      )
  
imports: import dataclasses
  from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  import torch
  from ax.core.search_space import SearchSpaceDigest
  from ax.models.torch.botorch import BotorchModel, get_rounding_func
  from ax.models.torch.botorch_defaults import recommend_best_out_of_sample_point
  from ax.models.torch.utils import _get_X_pending_and_observed, _to_inequality_constraints, get_botorch_objective_and_transform, get_out_of_sample_best_point_acqf, subset_model
  from ax.models.torch_base import TorchGenResults, TorchOptConfig
  from ax.utils.common.typeutils import not_none
  from botorch.acquisition.acquisition import AcquisitionFunction
  from botorch.acquisition.cost_aware import InverseCostWeightedUtility
  from botorch.acquisition.knowledge_gradient import qKnowledgeGradient, qMultiFidelityKnowledgeGradient
  from botorch.acquisition.objective import MCAcquisitionObjective, PosteriorTransform
  from botorch.acquisition.utils import expand_trace_observations, project_to_target_fidelity
  from botorch.exceptions.errors import UnsupportedError
  from botorch.models.cost import AffineFidelityCostModel
  from botorch.models.model import Model
  from botorch.optim.initializers import gen_one_shot_kg_initial_conditions
  from botorch.optim.optimize import optimize_acqf
  from botorch.sampling.normal import IIDNormalSampler, SobolQMCNormalSampler
  from torch import Tensor
label_desc: Use image node_id 1 for calling a global function with example usage: _instantiate_KG(model, objective, posterior_transform, qmc, n_fantasies, mc_samples, num_trace_observations, seed_inner, seed_outer, X_pending, current_value, target_fidelities, fidelity_weights, cost_intercept) and returns: qKnowledgeGradient, qMultiFidelityKnowledgeGradient, project_to_target_fidelity, expand_trace_observations