Skip to content

Add multi-backend benchmark comparison support#22346

Open
MarcosAsh wants to merge 1 commit intokeras-team:masterfrom
MarcosAsh:benchmark-multi-backend
Open

Add multi-backend benchmark comparison support#22346
MarcosAsh wants to merge 1 commit intokeras-team:masterfrom
MarcosAsh:benchmark-multi-backend

Conversation

@MarcosAsh
Copy link
Contributor

Refactors LayerBenchmark to support running the same benchmark across jax, torch, and tensorflow backends via a --backend flag. Each backend runs in its own subprocess and results are displayed as a comparison table (or JSON with --output_format=json). The existing Keras 3 vs tf.keras default is preserved.

Phase 1 of #22307. Updated conv_benchmark.py as a reference implementation.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the Keras benchmarking system by introducing robust support for multi-backend comparisons. It refactors the LayerBenchmark to allow users to specify a comma-separated list of backends (JAX, PyTorch, TensorFlow) via a new command-line flag. Each specified backend is then benchmarked in an isolated subprocess, and the results are aggregated and presented either as a clear comparison table or a machine-readable JSON output. This change provides a powerful tool for evaluating Keras layer performance across different deep learning frameworks while maintaining the existing Keras 3 vs tf.keras comparison as a default behavior.

Highlights

  • Multi-Backend Benchmarking: Introduced support for running benchmarks across multiple Keras backends (JAX, PyTorch, TensorFlow) using a new --backend flag.
  • Subprocess Execution: Each backend benchmark now runs in its own subprocess to ensure isolation and proper environment setup.
  • Flexible Output Formats: Added an --output_format flag to display comparison results as a formatted table or a JSON object.
  • Conditional TensorFlow Integration: Modified base_benchmark.py to conditionally import TensorFlow and define TFKerasBenchmarkMetricsCallback only if TensorFlow is available, improving flexibility.
  • Refactored LayerBenchmark: Updated the LayerBenchmark class to distinguish between single-backend mode (for multi-backend comparisons) and the legacy Keras 3 vs tf.keras comparison mode.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • benchmarks/layer_benchmark/base_benchmark.py
    • Added imports for json, os, platform, subprocess, sys
    • Introduced _RESULT_PREFIX, _BENCHMARK_BACKEND_ENV, and _single_backend_mode constants
    • Made TensorFlow import conditional to handle environments without TF
    • Defined new command-line flags: --backend for multi-backend comparison and --output_format for result presentation
    • Added _get_hardware_info function to capture system architecture
    • Wrapped TFKerasBenchmarkMetricsCallback definition in a tf is not None check
    • Modified LayerBenchmark initialization to conditionally build _tf_keras_model based on _single_backend_mode
    • Updated benchmark_predict and benchmark_train methods to output JSON results in single-backend mode or continue with Keras 3 vs tf.keras comparison otherwise
    • Implemented _print_comparison_table for formatted output
    • Added run_multi_backend_benchmark to manage subprocess execution and result aggregation for multi-backend comparisons
  • benchmarks/layer_benchmark/conv_benchmark.py
    • Updated the module docstring with examples for multi-backend and JSON output
    • Imported run_multi_backend_benchmark
    • Modified the main function to invoke run_multi_backend_benchmark if the --backend flag is used, otherwise proceeding with existing benchmark logic
    • Corrected iteration over BENCHMARK_NAMES from list to dictionary items
Activity
  • No specific activity (comments, reviews, or progress updates) has been provided for this pull request.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the layer benchmark framework to support comparisons across multiple backends (JAX, PyTorch, TensorFlow) by running benchmarks in separate subprocesses. However, the dynamic command construction for these subprocesses carries a risk of command injection if the validation logic for module_path is compromised or if the utility is used with untrusted inputs in the future. It is recommended to ensure module_path is strictly validated or restricted to an allowlist. Additionally, consider improving error reporting for failed benchmark subprocesses to enhance debuggability.

Comment on lines +406 to +475
def run_multi_backend_benchmark(module_path, benchmark_fn_map):
"""Run benchmarks across multiple Keras backends and display comparison.

Spawns a separate process for each backend with the appropriate
KERAS_BACKEND environment variable and collects results.

Args:
module_path: Python module path for the benchmark script
(e.g. "benchmarks.layer_benchmark.conv_benchmark").
benchmark_fn_map: Dict mapping benchmark names to functions, used
to validate the benchmark_name flag.
"""
backends = [b.strip() for b in FLAGS.backend.split(",")]
valid_backends = {"jax", "torch", "tensorflow"}
for b in backends:
if b not in valid_backends:
raise ValueError(
f"Invalid backend: {b}. Must be one of {valid_backends}."
)

benchmark_name = FLAGS.benchmark_name
if benchmark_name is not None and benchmark_name not in benchmark_fn_map:
raise ValueError(
f"Invalid benchmark name: {benchmark_name}, `benchmark_name` "
f"must be one of {benchmark_fn_map.keys()}"
)
print(
f"TF Keras throughput of forward & backward pass of "
f"{self.layer_name}: {tf_keras_throughput:.2f} samples/sec."

all_results = []

for backend in backends:
env = os.environ.copy()
env["KERAS_BACKEND"] = backend
env[_BENCHMARK_BACKEND_ENV] = backend

cmd = [
sys.executable,
"-m",
module_path,
f"--num_samples={FLAGS.num_samples}",
f"--batch_size={FLAGS.batch_size}",
f"--jit_compile={FLAGS.jit_compile}",
]
if benchmark_name:
cmd.append(f"--benchmark_name={benchmark_name}")

print(f"Running benchmarks with {backend} backend...")
proc = subprocess.run(
cmd, capture_output=True, text=True, env=env
)

if proc.returncode != 0:
print(f" Warning: {backend} backend failed:")
stderr_lines = proc.stderr.strip().splitlines()
for line in stderr_lines[-5:]:
print(f" {line}")
continue

for line in proc.stdout.splitlines():
if line.startswith(_RESULT_PREFIX):
result = json.loads(line[len(_RESULT_PREFIX) :])
all_results.append(result)

if not all_results:
print("No benchmark results collected.")
return

if FLAGS.output_format == "json":
print(json.dumps(all_results, indent=2))
else:
_print_comparison_table(all_results)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The run_multi_backend_benchmark function constructs a command line for a subprocess, and the module_path argument is used directly. If module_path were ever user-controlled, it could lead to arbitrary module execution, posing a command injection risk. While the use of subprocess.run with a list is generally safe, the overall pattern of spawning subprocesses based on environment variables and flags should be carefully monitored for any potential injection if validation logic is ever bypassed or weakened. Additionally, the current error reporting for a failed backend process only shows the last 5 lines of stderr. This might not be sufficient for debugging, as error messages can sometimes be on stdout, or more context from both streams might be needed. To improve debuggability, consider printing the exit code and the last few lines of both stdout and stderr if they are not empty.

@codecov-commenter
Copy link

codecov-commenter commented Mar 4, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.97%. Comparing base (3c4f2cc) to head (307d85e).
⚠️ Report is 19 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #22346   +/-   ##
=======================================
  Coverage   82.97%   82.97%           
=======================================
  Files         596      596           
  Lines       66330    66330           
  Branches    10334    10334           
=======================================
  Hits        55038    55038           
  Misses       8663     8663           
  Partials     2629     2629           
Flag Coverage Δ
keras 82.80% <ø> (ø)
keras-jax 60.74% <ø> (ø)
keras-numpy 54.95% <ø> (-0.01%) ⬇️
keras-openvino 49.25% <ø> (ø)
keras-tensorflow 61.97% <ø> (ø)
keras-torch 60.79% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@MarcosAsh MarcosAsh force-pushed the benchmark-multi-backend branch 3 times, most recently from 5728f61 to 75cd1c2 Compare March 5, 2026 12:43
Copy link
Member

@jeffcarp jeffcarp left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Added an idea

module_path="benchmarks.layer_benchmark.conv_benchmark",
benchmark_fn_map=BENCHMARK_NAMES,
)
return
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if a simpler approach is to call this script multiple times with different backends set via KERAS_BACKEND, instead of adding the multi-backend support in the script. There could be a separate bash script that invokes this script for each backend. That would also better isolate memory and prevent any cross-contamination while switching between backends in the same process.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review! Each backend runs in its own subprocess via subprocess.run() with KERAS_BACKEND set in the env (lines 428-445 in base_benchmark.py), so there's no shared state between backends.

The main reason I went with Python was to handle the result aggregation. Each subprocess outputs a JSON line that the parent collects and formats into the comparison table or JSON output. I didnt think of making it in bash but it would make it dependable on bash. Even tough it would be easier to run with a bash script.

Happy to rethink the approach if you'd prefer something different though!

@MarcosAsh MarcosAsh force-pushed the benchmark-multi-backend branch 2 times, most recently from 9a069bd to 26cc59b Compare March 10, 2026 18:22
@MarcosAsh MarcosAsh force-pushed the benchmark-multi-backend branch from 9a03b0e to 307d85e Compare March 10, 2026 20:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants