code: def topk_all(
      batches: Iterable[Any],
      batch_vals: Callable[[Any], Tuple[Sized, Sized, Sized]],
      out_f: callable,
      k: int = 1,
      order="rnd",
      sort_groups=True,
  ) -> Iterable[Any]:
      """Same as k but here we maintain top items across entire run"""
  
      # this dictionary will keep the best/worst per label we have so far
      merged_groups = {}
  
      # this iterator will keep going on for each batch in each epoch
      for batch in batches:
          unpacker = lambda a0, a1, a2=None: (a0, a1, a2)
          metric, items, labels = unpacker(*batch_vals(batch))
  
          # first run top in class for batch
          groups = topk(
              labels, metric, items, k=k, order=order, sort_groups=False
          )
  
          # update best/worst we have seen so far by sorting on metric
          reverse = True if order == "dsc" else False
          sort_key = (
              (lambda g: (g[1]))
              if order != "rnd"
              else lambda g: random.random()
          )
          combine_groups(
              merged_groups,
              groups,
              sort_key=sort_key,
              reverse=reverse,
              k=k,
          )
  
          # sort best/worst by label
          sorted_groups = (
              sorted(merged_groups.items(), key=lambda g: g[0])
              if sort_groups
              else merged_groups
          )
          sorted_groups = list(sorted_groups)
          # output best/worst after each batch
          if out_f:
              yield (
                  out_f(*val)
                  for key, vals in sorted_groups
                  for val in vals
              )  # out_f takes label, metric, item
          else:
              yield sorted_groups
  
imports: import math
  import numpy
  import random
  import heapq
  from .None import utils
  from .lv_types import ImageData, PointData
  from collections import OrderedDict
  from itertools import groupby, islice
  import operator
  from typing import Callable, List, Iterable, Any, Sized, Tuple
  from .None import utils
  from .None import tensor_utils
label_desc: Use image node_id 6 for calling a global function with example usage: topk_all(batches, batch_vals, out_f, k, order, sort_groups) without return types