code: def get_tensors_as_ndarray_1d(
      tensors: Union[Iterator[Tensor], Dict[str, Tensor]],
      out: Optional[ndarray] = None,
      dtype: Optional[Union[np.dtype, str]] = None,
      as_array: Callable[[Tensor], ndarray] = as_ndarray,
  ) -> ndarray:
      # Create a pair of iterators, one for setup and one for data transfer
      named_tensors_iter, named_tensors_iter2 = tee(
          iter(tensors.items())
          if isinstance(tensors, dict)
          else enumerate(tensors),
          2,
      )
  
      # Use `named_tensors_iter` to get size of `out` and `dtype` when None
      try:
          name, tnsr = next(named_tensors_iter)
      except StopIteration:
          raise RuntimeError(
              f"Argument `tensors` with type {type(tensors)} is empty."
          )
      size = tnsr.numel() + sum(
          tnsr.numel() for _, tnsr in named_tensors_iter
      )
      dtype = (
          torch_to_numpy_dtype_dict[tnsr.dtype]
          if dtype is None
          else dtype
      )
  
      # Preallocate or validate `out`
      if (
          out is None
      ):  # use first tensor as a reference when `dtype` is None
          out = np.empty([size], dtype=dtype)
      elif out.ndim != 1:
          raise ValueError(
              f"Expected a vector for `out`, but out.shape={out.shape}."
          )
      elif out.size != size:
          raise ValueError(
              f"Size of `parameters` ({size}) does not match size of `out` ({out.size})."
          )
  
      # Use `named_tensors_iter2` to transfer data from `tensors` to `out`
      index = 0
      for name, tnsr in named_tensors_iter2:
          try:
              size = tnsr.numel()
              out[index : index + size] = as_array(tnsr.view(-1))
              index += size
          except Exception as e:
              raise RuntimeError(
                  "`get_tensors_as_ndarray_1d` failed while copying values from "
                  f"tensor {name}; rethrowing original exception."
              ) from e
  
      return out
  
file_path: botorch/botorch/optim/utils/numpy_utils.py
imports: from __future__ import annotations
  from itertools import tee
  from typing import Callable, Dict, Iterator, Optional, Tuple, Union
  import numpy
  import torch
  from botorch.utils.types import NoneType
  from numpy import ndarray
  from torch import Tensor
label_desc: Use image node_id 2 for calling a global function with example usage: get_tensors_as_ndarray_1d(tensors, out, dtype, as_array) and returns: out