ml_switcheroo.frameworks.tensorflow

TensorFlow Framework Adapter.

This module implements the adapter for TensorFlow (Core & Keras), providing mappings for math operations, neural layers, and IO. It serves as the bridge between abstract operations and tf.* or tf.keras.* APIs.

It supports: 1. Live Inspection: Scanning installed TensorFlow modules for new operations. 2. Ghost Mode: Loading API signatures from JSON snapshots when TF is not installed. 3. Semantic Definitions: Static mappings for standard Math, NN, and Optimization ops. 4. Weight Migration: Loading checkpoints via tf.train.load_checkpoint.

Attributes

tf

Classes

TensorFlowAdapter

Adapter for TensorFlow (Core & Keras).

Module Contents

ml_switcheroo.frameworks.tensorflow.tf = None[source]
class ml_switcheroo.frameworks.tensorflow.TensorFlowAdapter[source]

Adapter for TensorFlow (Core & Keras).

Handles the specific idioms of TensorFlow 2.x, including: - mapping torch.nn.Module to keras.Layer. - mapping torch.* math to tf.math.*. - mapping IO operations to tf.io.*.

display_name: str = 'TensorFlow'
inherits_from: str | None = None
ui_priority: int = 30
property unsafe_submodules: Set[str]

Returns a set of submodule names to exclude from recursion.

These modules often contain C-Extensions, deprecated logic, or heavy dependencies that crash the GhostInspector or cause infinite recursion during discovery.

Returns:

Blacklisted submodule names.

Return type:

Set[str]

property search_modules: List[str]

Returns the list of top-level modules to scan during discovery.

If in GHOST mode, returns an empty list to prevent import errors.

Returns:

Module names (e.g. ['tensorflow', 'keras.layers']).

Return type:

List[str]

property import_alias: Tuple[str, str]

Returns the primary import statement configuration.

Returns:

The module name and its standard alias (e.g. ('tensorflow', 'tf')).

Return type:

Tuple[str, str]

property import_namespaces: Dict[str, ml_switcheroo.frameworks.base.ImportConfig]

Defines the semantic roles of TensorFlow namespaces.

This config guides the ImportFixer in resolving source imports to target imports based on their Semantic Tier.

Returns:

Mapping of namespace strings to configuration objects.

Return type:

Dict[str, ImportConfig]

property discovery_heuristics: Dict[str, List[str]]

Returns regex patterns used to categorize discovered APIs.

Used by the Scaffolder to blindly sort discovered functions into Math, Neural, or Extras tiers based on their path.

Returns:

Mapping of Tier names to regex patterns.

Return type:

Dict[str, List[str]]

property test_config: Dict[str, str]

Returns templates for generating physical verification tests.

These templates are used by gen-tests to create executable Python files that verify semantic correctness.

Returns:

Templates for imports and data conversion.

Return type:

Dict[str, str]

property harness_imports: List[str]

Returns extra imports required for the verification harness. TensorFlow requires no special initialization imports beyond the standard test config.

Returns:

Empty list.

Return type:

List[str]

get_harness_init_code() str[source]

Returns initialization logic for the verification harness. TensorFlow handles state implicitly, so no RNG setup code is needed.

Returns:

Empty string.

Return type:

str

get_to_numpy_code() str[source]

Returns code to convert TF tensors to NumPy.

Returns:

Code string using safe attribute check.

Return type:

str

property declared_magic_args: List[str]

Returns list of framework-specific ‘magic’ arguments to be stripped from other frameworks. TensorFlow generally uses explicit arguments or class attributes, not injected magic args.

Returns:

Empty list.

Return type:

List[str]

property structural_traits: ml_switcheroo.frameworks.base.StructuralTraits

Returns structural transformation rules for TensorFlow/Keras.

Defines how classes should be rewritten (e.g. inheriting from keras.Layer), what the forward method is named (call), and initialization requirements.

Returns:

The configuration object.

Return type:

StructuralTraits

property plugin_traits: ml_switcheroo.frameworks.base.PluginTraits

Returns capability flags for the TensorFlow ecosystem.

Indicates support for NumPy-compatible methods (allowing .astype via ops) but lack of functional state requirements.

Returns:

The capability flags.

Return type:

PluginTraits

property supported_tiers: List[ml_switcheroo.enums.SemanticTier]

Returns the Semantic Tiers supported by this adapter.

Returns:

Array API, Neural, and Extras.

Return type:

List[SemanticTier]

property definitions: Dict[str, ml_switcheroo.frameworks.base.StandardMap]

Returns the static dictionary of Operation Mappings. Loaded dynamically from frameworks/definitions/tensorflow.json.

Returns:

The mapping dictionary.

Return type:

Dict[str, StandardMap]

property rng_seed_methods: List[str]

Returns list of methods used to set global random seeds. Used by the PurityScanner to detect side-effects.

Returns:

Method names (e.g. set_seed).

Return type:

List[str]

collect_api(category: ml_switcheroo.frameworks.base.StandardCategory) List[ml_switcheroo.core.ghost.GhostRef][source]

Collects API definitions for the discovery process.

Delegates to _collect_ghost if in Ghost Mode, otherwise runs _collect_live to inspect the installed library.

Parameters:

category (StandardCategory) – The category of operations to scan (e.g. LOSS, LAYER).

Returns:

A list of discovered API signatures.

Return type:

List[GhostRef]

apply_wiring(snapshot: Dict[str, Any]) None[source]

Applies manual wiring patches to the generated snapshot. Updates tensorflow. API prefixes to tf. to match standard aliases.

Parameters:

snapshot (Dict[str, Any]) – The snapshot dictionary to modify in-place.

get_tiered_examples() Dict[str, str][source]

Returns example snippets for each semantic tier.

Used by the interactive web demo and documentation generator.

Returns:

Mapping of tier IDs to Python code strings.

Return type:

Dict[str, str]

get_device_syntax(device_type: str, device_index: str | None = None) str[source]

Generates Python code for defining a device context in TensorFlow.

Example: tf.device('GPU:0')

Parameters:
  • device_type (str) – The device type string (e.g. ‘cuda’, ‘cpu’).

  • device_index (Optional[str]) – The device index.

Returns:

Arguments for tf.device(...).

Return type:

str

get_device_check_syntax() str[source]

Returns Python code to check for GPU availability.

Returns:

len(tf.config.list_physical_devices('GPU')) > 0

Return type:

str

get_rng_split_syntax(rng_var: str, key_var: str) str[source]

Returns syntax for splitting RNG state. Since TF uses internal state, this returns ‘pass’ (no-op).

Parameters:
  • rng_var (str) – Variable name for current RNG.

  • key_var (str) – Variable name for new key.

Returns:

“pass”

Return type:

str

get_serialization_imports() List[str][source]

Returns imports required for IO operations.

Returns:

['import tensorflow as tf']

Return type:

List[str]

get_serialization_syntax(op: str, file_arg: str, object_arg: str | None = None) str[source]

Generates code for saving or loading artifacts.

Parameters:
  • op (str) – Operation type (‘save’ or ‘load’).

  • file_arg (str) – Path to file.

  • object_arg (Optional[str]) – Object to save.

Returns:

Generated code (e.g. tf.io.write_file).

Return type:

str

get_weight_conversion_imports() List[str][source]

Returns imports required for the generated weight migration script.

Returns:

List of import statements.

Return type:

List[str]

get_weight_load_code(path_var: str) str[source]

Returns Python code to load a TF checkpoint into a raw state dictionary. Attempt to load variable map if available.

Parameters:

path_var – Variable name containing the file path string.

Returns:

Block of python code setting ‘raw_state’.

get_tensor_to_numpy_expr(tensor_var: str) str[source]

Returns expression to convert a TF tensor to a NumPy array.

Parameters:

tensor_var – Variable name of the tensor.

Returns:

Conversion expression string.

get_weight_save_code(state_var: str, path_var: str) str[source]

Returns logic (stubbed with warning) for saving weights. TensorFlow checkpoint saving generally requires a model instance structure, so raw dictionary saving is not supported in the standalone migration script.

Parameters:
  • state_var – Unused state variable name.

  • path_var – Unused path variable name.

Returns:

Warning print code.

convert(data: Any) Any[source]

Converts input data (NumPy/List) into TensorFlow Tensors. Used by the Fuzzer for validation.

Parameters:

data (Any) – Input data.

Returns:

tf.Tensor or original data if conversion fails.

Return type:

Any

get_doc_url(api_name: str) str | None[source]

Generates TensorFlow API documentation URL. Corrects internal tensorflow path to tf for doc references.

Parameters:

api_name (str) – API Path.

Returns:

URL.

Return type:

Optional[str]