code: def write_sharded(
      self,
      filename: str,
      items: Iterable[T],
      *,
      key_fn: Callable[[T], str],
      env_callable: Callable[[T], Dict[str, List[str]]],
      num_shards: int,
      base_env: Optional[Dict[str, Any]] = None,
      sharded_keys: Set[str],
  ) -> None:
      everything: Dict[str, Any] = {"shard_id": "Everything"}
      shards: List[Dict[str, Any]] = [
          {"shard_id": f"_{i}"} for i in range(num_shards)
      ]
      all_shards = [everything] + shards
  
      if base_env is not None:
          for shard in all_shards:
              shard.update(base_env)
  
      for key in sharded_keys:
          for shard in all_shards:
              if key in shard:
                  assert isinstance(
                      shard[key], list
                  ), "sharded keys in base_env must be a list"
                  shard[key] = shard[key].copy()
              else:
                  shard[key] = []
  
      def merge_env(
          into: Dict[str, List[str]], from_: Dict[str, List[str]]
      ) -> None:
          for k, v in from_.items():
              assert k in sharded_keys, f"undeclared sharded key {k}"
              into[k] += v
  
      if self.dry_run:
          # Dry runs don't write any templates, so incomplete environments are fine
          items = ()
  
      for item in items:
          key = key_fn(item)
          sid = string_stable_hash(key) % num_shards
          env = env_callable(item)
  
          merge_env(shards[sid], env)
          merge_env(everything, env)
  
      dot_pos = filename.rfind(".")
      if dot_pos == -1:
          dot_pos = len(filename)
      base_filename = filename[:dot_pos]
      extension = filename[dot_pos:]
  
      for shard in all_shards:
          shard_id = shard["shard_id"]
          self.write_with_template(
              f"{base_filename}{shard_id}{extension}",
              filename,
              lambda: shard,
          )
  
      # filenames is used to track compiled files, but FooEverything.cpp isn't meant to be compiled
      self.filenames.discard(
          f"{self.install_dir}/{base_filename}Everything{extension}"
      )
  
imports: import contextlib
  import functools
  import hashlib
  import os
  import re
  import sys
  import textwrap
  from argparse import Namespace
  from dataclasses import fields, is_dataclass
  from enum import auto, Enum
  from typing import Any, Callable, Dict, Generic, Iterable, Iterator, List, Literal, NoReturn, Optional, Sequence, Set, Tuple, TypeVar, Union
  from typing_extensions import Self
  from torchgen.code_template import CodeTemplate
label_desc: Use image node_id 6 for calling the FileManager obj's underlying member method code with example usage: obj.write_sharded(filename, items) without return types