RepoPilot

NVlabs/stylegan2

StyleGAN2 - Official TensorFlow Implementation

Mixed

Stale — last commit 2y ago

ConcernsDependency

non-standard license (Other); last commit was 2y ago…

HealthyFork & modify

Has a license, tests, and CI — clean foundation to fork and modify.

HealthyLearn from

Documented and popular — useful reference codebase to read through.

MixedDeploy as-is

last commit was 2y ago; Scorecard "Branch-Protection" is 0/10…

  • Stale — last commit 2y ago
  • Small team — 3 contributors active in recent commits
  • Single-maintainer risk — top contributor 89% of recent commits
  • Non-standard license (Other) — review terms
  • No CI workflows detected
  • Scorecard: marked unmaintained (0/10)
  • Scorecard: default branch unprotected (0/10)
  • 3 active contributors
  • Other licensed
  • Tests present

What would improve this?

  • Use as dependency ConcernsMixed if: clarify license terms
  • Deploy as-is MixedHealthy if: 1 commit in the last 180 days; bring "Branch-Protection" to ≥3/10 (see scorecard report)

Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests + OpenSSF Scorecard

Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.

Embed the "Forkable" badge

Paste into your README — live-updates from the latest cached analysis.

Variant:
RepoPilot: Forkable
[![RepoPilot: Forkable](https://repopilot.app/api/badge/nvlabs/stylegan2?axis=fork)](https://repopilot.app/r/nvlabs/stylegan2)

Paste at the top of your README.md — renders inline like a shields.io badge.

Preview social card

This card auto-renders when someone shares https://repopilot.app/r/nvlabs/stylegan2 on X, Slack, or LinkedIn.

Ask AI about NVlabs/stylegan2

Grounded in the actual source code. Pick a starter question or write your own.

Or write your own question →

Onboarding doc

Onboarding: NVlabs/stylegan2

Generated by RepoPilot · 2026-06-19 · Source

🎯Verdict

WAIT — Stale — last commit 2y ago

  • 3 active contributors
  • Other licensed
  • Tests present
  • ⚠ Stale — last commit 2y ago
  • ⚠ Small team — 3 contributors active in recent commits
  • ⚠ Single-maintainer risk — top contributor 89% of recent commits
  • ⚠ Non-standard license (Other) — review terms
  • ⚠ No CI workflows detected
  • ⚠ Scorecard: marked unmaintained (0/10)
  • ⚠ Scorecard: default branch unprotected (0/10)

<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests + OpenSSF Scorecard</sub>

TL;DR

StyleGAN2 is an improved generative adversarial network (GAN) that produces high-quality synthetic images via a style-based generator architecture. It addresses StyleGAN's artifacts through redesigned normalization (AdaIN), progressive training, and path length regularization. The core innovation is the ability to control image synthesis at multiple granularities—from coarse semantic features to fine details—through disentangled latent space manipulation. Monolithic structure: dnnlib/ is a custom deep-learning framework wrapping TensorFlow primitives (tflib/ with ops/, network.py); training/ contains the core model definitions (networks_stylegan2.py, loss.py, training_loop.py) and dataset handling; metrics/ provides evaluation (FID, IS, PPL, linear separability); run_*.py files are entry points for generation, projection, training, and metrics. Custom ops are in Cython/CUDA (fused_bias_act.cu, upfirdn_2d.cu) for performance.

👥Who it's for

Research scientists and machine learning engineers building generative models or studying adversarial training; practitioners needing pre-trained high-resolution image generators for synthesis tasks; AI researchers analyzing GAN conditioning, invertibility, and image quality metrics.

🌱Maturity & risk

This is an official, published research implementation (NVIDIA NVLabs, 2019–2020) at production quality for inference and research. The codebase is stable but no longer actively maintained—the team has moved to the PyTorch variant (stylegan2-ada-pytorch). However, the TensorFlow implementation remains the canonical reference for the paper and is suitable for reproducibility and study.

TensorFlow 1.x dependency (implied by dnnlib/tflib structure) means compatibility issues with modern TensorFlow 2.x environments without adaptation. Custom CUDA kernels (fused_bias_act.cu, upfirdn_2d.cu) require manual compilation and GPU matching. No visible CI/CD, test suite, or GitHub Actions—integration risk is high if forking for modifications. Heavily research-oriented with minimal production safety guards (no input validation, limited error handling).

Active areas of work

This repository is in maintenance mode. Development has shifted to stylegan2-ada-pytorch (PyTorch + adaptive discriminator augmentation). No active development visible in this TensorFlow implementation; it serves as a frozen reference for paper reproducibility and as a base for research extending StyleGAN2.

🚀Get running

Clone: git clone https://github.com/NVlabs/stylegan2.git && cd stylegan2. Install dependencies: pip install -r requirements.txt (if present; otherwise manually: pip install tensorflow==1.14 numpy pillow requests). Verify CUDA: python test_nvcc.cu. Generate images: python run_generator.py --network=pretrained_networks.pkl --seed=42. For training: python run_training.py --data-dir=/path/to/dataset --config=config-f.

Daily commands: For image generation (inference): python run_generator.py --network=/path/to/pretrained.pkl --seeds=0-3 --outdir=results. For projection (invvert images): python run_projector.py --network=/path/to/pretrained.pkl --target-image=target.png. For training: python run_training.py --data-dir=/path/to/tfrecords --total-kimg=25000 --config=config-f --gpu=0. For metrics (FID, IS, PPL): python run_metrics.py --network=/path/to/pretrained.pkl --metrics=fid50k_full.

🗺️Map of the codebase

  • training/networks_stylegan2.py: Defines Generator and Discriminator classes; implements style mixing, modulated convolution, AdaIN, progressive growing—core model logic
  • training/training_loop.py: Main training orchestration: gradient updates, checkpointing, metric evaluation, progressive layer freezing scheduling
  • training/loss.py: Implements discriminator loss (hinge), generator loss (non-saturating), regularization (R1 gradient penalty, path length penalty)
  • dnnlib/tflib/custom_ops.py: Bridges Python to CUDA kernels (fused_bias_act, upfirdn_2d); performance-critical for forward/backward passes
  • metrics/frechet_inception_distance.py: FID computation via pre-trained InceptionV3; primary metric for generative model quality assessment
  • training/dataset.py: TFRecord dataset loading, augmentation, minibatch construction; handles multi-resolution progressive training
  • run_training.py: CLI entry point; parses config (config-f, config-e, etc.), initializes training loop, handles distributed setup

🛠️How to make changes

Model changes: training/networks_stylegan2.py (generator and discriminator architecture). Loss/training: training/loss.py (discriminator and generator objectives, regularization). Data pipeline: training/dataset.py (loading, augmentation, preprocessing). Evaluation metrics: metrics/*.py (add new metric classes inheriting MetricBase). Entry points: run_training.py, run_generator.py for CLI argument handling and workflow orchestration.

🪤Traps & gotchas

TensorFlow version lock: Code targets TensorFlow 1.14 (eager execution off, session-based). TensorFlow 2.x incompatibility without major refactoring. CUDA compilation: Custom ops in fused_bias_act.cu and upfirdn_2d.cu must be compiled at import; NVCC version must match CUDA runtime. Failing silently if CUDA unavailable (falls back to slow CPU or stub). No input validation: run_generator.py and run_projector.py assume well-formed paths and PKL files; corrupt files cause cryptic TensorFlow serialization errors. Pretrained weights format: .pkl files are pickled TensorFlow variables; compatible with Python 3.6–3.8 only (pickle protocol compatibility). Dataset format: Requires TFRecord files; dataset_tool.py converts images to TFRecords but expects exact directory structure (per-resolution subdirs for progressive training).

💡Concepts to learn

  • Style-based generator (style mixing) — Core innovation of StyleGAN2: injecting distinct style codes w at each layer enables fine-grained control over semantic features vs. texture; understanding this enables modifying the synthesis process and reasoning about disentanglement
  • Adaptive Instance Normalization (AdaIN) — Replaces traditional batch norm in StyleGAN2 generator; enables style code injection via affine transform of layer activations; critical for reading training/networks_stylegan2.py modulated_conv2d_layer
  • Progressive growing — Training strategy that starts with low resolution and gradually adds layers; stabilizes GAN training and enables higher resolutions; implemented in training_loop.py phase scheduling
  • Path length regularization — StyleGAN2-specific regularizer encouraging smooth, invertible mapping from latent w to image space; implemented in training/loss.py; enables adversarial inversion and improves latent disentanglement
  • Spectral normalization — Weight normalization technique stabilizing GAN discriminator gradients; applied in dnnlib/tflib/custom_ops.py to bound Lipschitz constant; prevents discriminator divergence
  • Fused operations (CUDA kernels) — Custom fused_bias_act.cu and upfirdn_2d.cu kernels combine multiple operations into single GPU kernel to reduce memory bandwidth and increase throughput; critical for efficient large-batch training
  • Frechet Inception Distance (FID) — Standard metric for evaluating GAN image quality; measures Wasserstein distance between feature distributions of real and generated images via pre-trained InceptionV3; implemented in metrics/frechet_inception_distance.py
  • NVlabs/stylegan2-ada-pytorch — Official successor in PyTorch with adaptive discriminator augmentation (ADA); recommended for new projects and active development
  • NVlabs/stylegan — Original StyleGAN (predecessor); useful for understanding evolution of style-based synthesis and comparing architectural changes
  • tensorflow/tensorflow — Core dependency (TensorFlow 1.14); needed for understanding session semantics, ops, and debugging deep-learning execution
  • openai/glow — Alternative generative model (flow-based) in same era; useful for comparing autoregressive vs. GAN trade-offs
  • pomenka/stylegan2-pytorch — Community PyTorch port of StyleGAN2 for easier integration with modern PyTorch tools (torchscript, ONNX export)

🪄PR ideas

To work on one of these in Claude Code or Cursor, paste: Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.

Add unit tests for custom CUDA ops (fused_bias_act and upfirdn_2d)

The repo has critical custom CUDA operations in dnnlib/tflib/ops/ (fused_bias_act.cu, fused_bias_act.py, upfirdn_2d.cu, upfirdn_2d.py) but no visible test suite. These are performance-critical ops that could silently fail across different CUDA/GPU configurations. Adding tests would catch regressions and help new contributors understand expected behavior.

  • [ ] Create tests/ops/test_fused_bias_act.py with unit tests for bias and activation combinations
  • [ ] Create tests/ops/test_upfirdn_2d.py with upsampling/downsampling filter tests against known reference outputs
  • [ ] Add test_nvcc.cu integration into a pytest-based testing framework (currently standalone)
  • [ ] Document expected tensor shapes and dtypes for each op in tests as inline examples

Add integration tests for training/networks_stylegan2.py generator architecture

The repo has training/networks_stylegan2.py which implements the core architecture, but there are no tests validating that the generator produces correct output shapes, handles style mixing, or maintains latent space properties. This is risky for users adapting the code, as architectural bugs could go undetected.

  • [ ] Create tests/training/test_networks_stylegan2.py with tests for generator output shapes given various batch sizes
  • [ ] Add tests for style mixing functionality and latent code injection at different layers
  • [ ] Add test validating discriminator can process generator outputs without shape mismatches
  • [ ] Include a test loading pretrained weights and verifying architecture compatibility

Add metrics computation tests with baseline regression data

The metrics/ folder contains frechet_inception_distance.py, inception_score.py, perceptual_path_length.py, and precision_recall.py, but no tests validating these produce stable, correct outputs. Contributors often modify metrics code but have no way to verify correctness. Adding reference datasets and baseline values would prevent metric regressions.

  • [ ] Create tests/metrics/test_metric_stability.py with small synthetic image tensors and fixed expected metric outputs
  • [ ] Add tests/metrics/fixtures/ with pre-computed metric values for reference image sets
  • [ ] Create unit tests for each metric in metrics/metric_base.py ensuring deterministic outputs on fixed inputs
  • [ ] Add a test validating metric_defaults.py configuration values are reasonable ranges

🌿Good first issues

  • Add unit tests for training/loss.py gradients: verify R1 penalty and path length penalty compute correctly on toy tensors. Currently no test suite exists; start with pytest fixtures for fake discriminator/generator outputs.
  • Document CUDA compilation troubleshooting in README: add section explaining nvcc version matching, CUDA_HOME environment variable, and fallback behavior when custom ops fail to load. Include actual error messages and fixes.
  • Create notebook tutorial (Jupyter) for image projection: demonstrate run_projector.py step-by-step with visualization of loss curves and intermediate reconstructions. Current run_projector.py lacks inline comments on convergence criteria.

Top contributors

Click to expand

📝Recent commits

Click to expand
  • bf0fe0b — Update README.md (nurpax)
  • f2f751c — Update versions.html for StyleGAN3 (tkarras)
  • 81ae61d — Alias-Free GAN links (tkarras)
  • 315ac54 — Add link to stylegan2-ada-pytorch (tkarras)
  • 23f8bed — Workaround for NCCL bug in TF 1.15 (tkarras)
  • 6af5afc — Add links to stylegan2-ada (tkarras)
  • dae148b — Remove direct links to network pickles. (tkarras)
  • ca52625 — Update S3 links. (tkarras)
  • ec1901f — Update citation. (tkarras)
  • cec605e — Convert seed 'range' into a list (jannehellsten)

🔒Security observations

The StyleGAN2 codebase has critical security issues primarily related to severely outdated dependencies (5+ year old base image and packages with known CVEs). The use of TensorFlow 1.14.0 from 2019 and pinned versions of scipy, requests, and Pillow from the same era creates significant attack surface. There is no evidence of security scanning, vulnerability management, or secure development practices. Immediate action required to update all dependencies and implement automated security scanning. The codebase itself lacks obvious injection vulnerabilities but relies on unpatched, vulnerable foundations that negate any code-

  • High · Outdated TensorFlow Base Image with Known Vulnerabilities — Dockerfile. The Dockerfile uses tensorflow/tensorflow:1.14.0-gpu-py3, released in 2019. TensorFlow 1.14.0 contains multiple known security vulnerabilities and lacks security patches. This base image is severely outdated (5+ years old) and exposes the application to known exploits. Fix: Upgrade to a recent, actively maintained TensorFlow version (2.13+). Use tensorflow/tensorflow:latest-gpu-py3 or a specific recent stable version. Regularly update base images to receive security patches.
  • High · Outdated Dependencies with Known Vulnerabilities — Dockerfile. Multiple pinned dependencies are severely outdated: scipy==1.3.3 (2019), requests==2.22.0 (2019), and Pillow==6.2.1 (2019). These versions contain multiple CVEs including arbitrary code execution and denial of service vulnerabilities. For example, Pillow 6.2.1 has CVE-2021-28957 and other critical issues. Fix: Update all dependencies to recent stable versions: scipy>=1.9.0, requests>=2.28.0, Pillow>=9.5.0. Implement dependency scanning in CI/CD pipeline using tools like Snyk or OWASP Dependency-Check.
  • High · Missing Python Package Pinning for Base Image — Dockerfile. The Dockerfile installs pip packages without specifying versions for the base image's Python and pip packages. This can lead to unpredictable behavior and security issues from uncontrolled transitive dependencies. Fix: Pin Python version explicitly and use a requirements.txt file with all dependencies (direct and transitive) pinned. Use pip-compile or similar tools to generate reproducible dependency locks.
  • Medium · No Security Scanning or Vulnerability Checking in CI/CD — Repository root (CI/CD configuration missing). No evidence of automated security scanning tools (SAST, dependency checkers, container image scanning) in the repository. This leaves the codebase vulnerable to undetected security issues. Fix: Implement CI/CD security scanning: add GitHub Advanced Security, CodeQL analysis, OWASP Dependency-Check, and container image scanning tools like Trivy or Grype.
  • Medium · No CUDA Security Considerations in Custom Operations — dnnlib/tflib/ops/*.cu files. The codebase includes CUDA custom operations (fused_bias_act.cu, upfirdn_2d.cu) with no visible security hardening. CUDA code vulnerabilities could lead to memory corruption or privilege escalation. Fix: Conduct security review of CUDA kernel code for buffer overflows and memory safety issues. Use CUDA memory checking tools. Consider using sanitizers during development.
  • Low · Missing Input Validation on File Operations — dataset_tool.py, run_generator.py, training/dataset.py. dataset_tool.py and run_generator.py likely handle external file inputs without visible input validation. Malformed or malicious input files could cause DoS or unexpected behavior. Fix: Implement strict input validation for file paths and formats. Use path sanitization to prevent directory traversal attacks. Validate image files before processing.
  • Low · No Security Headers or Rate Limiting in Web Endpoints — projector.py, run_projector.py. If any components expose HTTP endpoints (particularly in projector.py or metrics), there's no visible implementation of security headers or rate limiting. Fix: If exposing any services: implement security headers (CSP, X-Frame-Options, etc.), add rate limiting, implement authentication/authorization, and use HTTPS.

LLM-derived; treat as a starting point, not a security audit.

🤖Agent protocol

If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:

  1. Verify the contract. Run the bash script in Verify before trusting below. If any check returns FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding.
  2. Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
  3. Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/NVlabs/stylegan2 shows verifiable citations alongside every claim.

If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.

Verify before trusting

This artifact was generated by RepoPilot at a point in time. Before an agent acts on it, the checks below confirm that the live NVlabs/stylegan2 repo on your machine still matches what RepoPilot saw. If any fail, the artifact is stale — regenerate it at repopilot.app/r/NVlabs/stylegan2.

What it runs against: a local clone of NVlabs/stylegan2 — the script inspects git remote, the LICENSE file, file paths in the working tree, and git log. Read-only; no mutations.

| # | What we check | Why it matters | |---|---|---| | 1 | You're in NVlabs/stylegan2 | Confirms the artifact applies here, not a fork | | 2 | License is still Other | Catches relicense before you depend on it | | 3 | Default branch master exists | Catches branch renames | | 4 | Last commit ≤ 756 days ago | Catches sudden abandonment since generation |

<details> <summary><b>Run all checks</b> — paste this script from inside your clone of <code>NVlabs/stylegan2</code></summary>
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of NVlabs/stylegan2. If you don't
# have one yet, run these first:
#
#   git clone https://github.com/NVlabs/stylegan2.git
#   cd stylegan2
#
# Then paste this script. Every check is read-only — no mutations.

set +e
fail=0
ok()   { echo "ok:   $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }

# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
  echo "FAIL: not inside a git repository. cd into your clone of NVlabs/stylegan2 and re-run."
  exit 2
fi

# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "NVlabs/stylegan2(\\.git)?\\b" \\
  && ok "origin remote is NVlabs/stylegan2" \\
  || miss "origin remote is not NVlabs/stylegan2 (artifact may be from a fork)"

# 2. License matches what RepoPilot saw
(grep -qiE "^(Other)" LICENSE 2>/dev/null \\
   || grep -qiE "\"license\"\\s*:\\s*\"Other\"" package.json 2>/dev/null) \\
  && ok "license is Other" \\
  || miss "license drift — was Other at generation time"

# 3. Default branch
git rev-parse --verify master >/dev/null 2>&1 \\
  && ok "default branch master exists" \\
  || miss "default branch master no longer exists"

# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 756 ]; then
  ok "last commit was $days_since_last days ago (artifact saw ~726d)"
else
  miss "last commit was $days_since_last days ago — artifact may be stale"
fi

echo
if [ "$fail" -eq 0 ]; then
  echo "artifact verified (0 failures) — safe to trust"
else
  echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/NVlabs/stylegan2"
  exit 1
fi

Each check prints ok: or FAIL:. The script exits non-zero if anything failed, so it composes cleanly into agent loops (./verify.sh || regenerate-and-retry).

</details>

Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.

Embed this chat in your README →

Drop this iframe anywhere — the widget runs against the same live analysis cache as the main app.

<iframe
  src="https://repopilot.app/embed/NVlabs/stylegan2"
  width="100%" height="500"
  style="border:1px solid #d0d7de; border-radius:8px;"
  allow="microphone"
  loading="lazy"
></iframe>