Add multi-backend benchmark comparison support#22346
Add multi-backend benchmark comparison support#22346MarcosAsh wants to merge 1 commit intokeras-team:masterfrom
Conversation
Summary of ChangesHello, 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 Highlights
🧠 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
Activity
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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 Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
5728f61 to
75cd1c2
Compare
| module_path="benchmarks.layer_benchmark.conv_benchmark", | ||
| benchmark_fn_map=BENCHMARK_NAMES, | ||
| ) | ||
| return |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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!
9a069bd to
26cc59b
Compare
9a03b0e to
307d85e
Compare
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.