CivArchive
    โ† All articles
    Published July 27, 2026by Herrscher_AGGA

    ๐Ÿ› ๏ธ AGGA OMNI-TOOL v3: The Complete Forensic & Spectral DNA Suite for LoRAs

    243 views10 reactions1 comments on CivitAI5 collected
    tool guidescannerlora

    Ever downloaded a LoRA from Civitai and wondered what is actually under the hood? Why does one LoRA burn prompt understanding while another changes line-art? Why do some merged LoRAs crash with NaN errors while others act like high-speed acceleration engines?

    Most LoRA tools only tell you file size or basic metadata. The AGGA OMNI-TOOL v3 treats .safetensors files like biological specimens: performing deep matrix inspection, layer-by-layer L2 energy profiling, block mapping, and spectral DNA categorization.


    ๐Ÿ”ฌ What is AGGA OMNI-TOOL v3?

    The AGGA OMNI-TOOL v3 is a dual-mode forensic analyzer and graphic comparative suite built for Stable Diffusion (SD1.5, SDXL, Illustrious, NoobAI, and Flux LoRAs).

    It offers two primary operational modules:

    1. ๐Ÿ”ฌ FORENSIC MODE (Full Audit): Scans a single or batch of LoRAs to extract metadata, rank breakdowns, structural block counts, tensor magnitudes, and assigns a Clinical Diagnosis to the model based on its L2 spectral energy distribution.

    2. ๐Ÿ“Š VISUALIZER MODE (Graphical Compare): Plots layer-by-layer weight intensity across the UNet architecture (Input, Middle, Output blocks) for multiple LoRAs on a single dark-mode graph (AGGA_PLOT.png) to visually identify weight spikes, anomalies, or extraction drops.


    ๐Ÿ”‘ Key Features Breakdown

    1. Header & Architecture Mapping

    • Safe Header Extraction: Reads the metadata header directly from disk in milliseconds without loading gigabytes of weights into system RAM.

    • Multi-Rank Detection: Automatically inventories tensor shapes and identifies mixed-rank models (e.g., $R32$ attention with $R128$ feed-forward layers).

    • Block Allocation: Categorizes every tensor into Input, Middle, Output, Text Encoder, or Other blocks.

    2. Sectional Strength (Impact Magnitude)

    Measures the average absolute mean intensity ($\frac{1}{N} \sum \vert{}W_i\vert{}$) across each structural block:

    • TE (Text Encoder): Concept associations and prompt reactivity.

    • IN (Input Blocks): Initial feature processing and coarse composition.

    • MID (Middle Block): High-level abstraction and spatial relationships.

    • OUT (Output Blocks): Fine details, line weight, shading, and final image reconstruction.

    3. Spectral DNA ("Telescope v1")

    The tool calculates the Frobenius / L2 Norm energy ($\Vert{}W\Vert{}_2 = \sqrt{\sum W_i^2}$) of lora_up matrices and separates them into fundamental sub-networks:

    • Structure (Attn1 - Self-Attention): Controls spatial layout, pose retention, and geometric integrity.

    • Prompt (Attn2 - Cross-Attention): Governs how text prompts bind to visual concepts.

    • Style/Color (FF - Feed-Forward): Governs brushstrokes, lighting, shading gradients, and color palettes.

    • ResNet (Conv Layers): Controls high-frequency textures and feature filtering.

    4. Clinical Diagnosis Engine

    Based on energy distribution ratios, the tool categorizes the LoRA into one of four functional classes:


    ๐Ÿ“Š Visualizer Mode: Comparative Vector Plotting

    When comparing two versions of a LoRA (e.g., Original vs. Merged or Rank 32 vs. Rank 128), text logs aren't enough.

    Visualizer Mode calculates the average weight magnitude per UNet block (IN_00 to IN_08, MID_00, OUT_00 to OUT_11) and plots a line chart.

              AGGA VECTOR COMPARISON
      0.08 +--+-------+-------+-------+-------+--+
           |                               *     |  -- Model_A (Stylist)
      0.06 |+  *---*                     *   *  +|  -- Model_B (Brain)
           |        *                 *          |
      0.04 |+         *             *           +|
           |            *---*---*-*              |
      0.02 +--+-------+-------+-------+-------+--+
             IN_0    IN_4    MID_0   OUT_4   OUT_8
    

    This chart instantly reveals:

    • Layer Overbaking: Spikes on specific output blocks causing burnt pixels.

    • Underflow Losses: Collapsed lines where $FP16$ conversion erased thin style layers.

    • Merge Discrepancies: Unintended weight shifts introduced by merging tools.


    ๐Ÿ Fully Translated Python / Colab Script

    Copy and paste this script into Google Colab or run it locally in your Python environment:

    # @title ๐Ÿ› ๏ธ **AGGA OMNI-TOOL v3: The Complete Forensic Suite** {"display-mode":"form"}
    # Dual-Mode Forensic Auditor & Visual Vector Comparator for LoRAs (.safetensors)
    
    import torch
    from safetensors.torch import load_file
    import os
    import json
    import pandas as pd
    import glob
    from tqdm import tqdm
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    import numpy as np
    import re
    
    # ==============================================================================
    # ๐ŸŽ›๏ธ CONTROL PANEL
    # ==============================================================================
    TOOL_MODE = "๐Ÿ”ฌ FORENSIC (Full Audit)" # @param ["๐Ÿ”ฌ FORENSIC (Full Audit)", "๐Ÿ“Š VISUALIZER (Graphical Compare)"]
    INPUT_MODE = "Specific_Files" # @param ["Folder", "Specific_Files"]
    INPUT_PATH = "/content/input_lora.safetensors" # @param {type:"string"}
    SMART_CROP = "" # @param {type:"string"}
    
    
    # ==============================================================================
    # ๐Ÿ› ๏ธ HELPER FUNCTIONS
    # ==============================================================================
    
    def get_file_list(mode, path_input):
        targets = []
        if mode == "Folder":
            if not os.path.exists(path_input):
                print(f"โŒ Folder does not exist: {path_input}")
                return []
            targets = sorted(glob.glob(os.path.join(path_input, "*.safetensors")))
        else:
            raw_list = path_input.split(",")
            for f in raw_list:
                clean = f.strip()
                if clean: targets.append(clean)
        return targets
    
    def parse_block_name(key):
        if "input_blocks" in key:
            m = re.search(r"input_blocks_(\d+)", key)
            return "IN", int(m.group(1)) if m else 0
        if "middle_block" in key: return "MID", 0
        if "output_blocks" in key:
            m = re.search(r"output_blocks_(\d+)", key)
            return "OUT", int(m.group(1)) if m else 0
        return "OTHER", 0
    
    def get_smart_label(filepath):
        filename = os.path.basename(filepath).replace(".safetensors", "")
        trigger = SMART_CROP.strip()
        if trigger and trigger in filename:
            idx = filename.find(trigger)
            return filename[idx:]
        if len(filename) > 35: return "..." + filename[-30:]
        return filename
    
    
    # ==============================================================================
    # ๐Ÿ”ฌ FORENSIC ENGINE
    # ==============================================================================
    
    def run_forensic(files):
        print(f"\n๐Ÿ”ฌ RUNNING FULL FORENSIC AUDIT ({len(files)} files)...")
    
        for file_path in tqdm(files, desc="Auditing Models"):
            if not os.path.exists(file_path): 
                print(f"โš ๏ธ File not found: {file_path}")
                continue
            filename = os.path.basename(file_path)
    
            print(f"\n{'='*65}")
            print(f"๐Ÿ“„ FILE: {filename}")
            print(f"{'='*65}")
    
            try:
                # 1. HEADER INSPECTION
                with open(file_path, 'rb') as f:
                    h_size = int.from_bytes(f.read(8), 'little')
                    header_json = json.loads(f.read(h_size).decode('utf-8'))
                    meta = header_json.get("__metadata__", {})
    
                print(f"๐Ÿ“‚ METADATA: Base Model: {meta.get('base_model','Unknown')} | Format: {meta.get('format','Unknown')}")
                if 'desc' in meta: print(f"   Description: {meta['desc'][:80]}...")
    
                # 2. BODY ANALYSIS
                t = load_file(file_path, device="cpu")
                total_params = 0
                ranks = {}
                blocks_map = {"Input": 0, "Middle": 0, "Output": 0, "TextEnc": 0, "Other": 0}
                sample_data = []
    
                # Sectional Strength Variables
                stats = {
                    "TE":  {"count": 0, "magnitude": 0.0, "abs_mean": 0.0},
                    "IN":  {"count": 0, "magnitude": 0.0, "abs_mean": 0.0},
                    "MID": {"count": 0, "magnitude": 0.0, "abs_mean": 0.0},
                    "OUT": {"count": 0, "magnitude": 0.0, "abs_mean": 0.0},
                    "OTH": {"count": 0, "magnitude": 0.0, "abs_mean": 0.0},
                }
    
                # Spectral DNA Variables (Telescope v1)
                telescope = {
                    "Structure (Attn1)": [], "Prompt (Attn2)": [],
                    "Style/Color (FF)": [], "ResNet (Conv)": [], "Time/Embs": []
                }
                total_energy_l2 = 0
    
                for k, v in t.items():
                    shape = list(v.shape)
                    params = v.numel()
                    total_params += params
    
                    # Random Layer Sampling
                    sample_data.append({"Name": k, "Rank": min(shape) if len(shape)>1 else "N/A", "Shape": str(shape)})
    
                    # Rank Detection
                    if "lora_" in k and len(shape) >= 2:
                        r = min(shape)
                        r_key = f"R{r}" if r > 1 else "Bias/Alpha"
                        ranks[r_key] = ranks.get(r_key, 0) + 1
    
                    # Block Mapping
                    b = "Other"
                    if "input" in k: b = "Input"
                    elif "middle" in k: b = "Middle"
                    elif "output" in k: b = "Output"
                    elif "text" in k or "te" in k: b = "TextEnc"
                    blocks_map[b] += 1
    
                    # Deep Stats & Telescope Math
                    try:
                        t_float = v.float()
                        val_norm = torch.linalg.norm(t_float).item()
                        val_abs_mean = t_float.abs().mean().item()
    
                        # Section Categorization
                        if "text_model" in k or "te1" in k or "te2" in k: cat = "TE"
                        elif "input_blocks" in k: cat = "IN"
                        elif "middle_block" in k: cat = "MID"
                        elif "output_blocks" in k: cat = "OUT"
                        else: cat = "OTH"
    
                        stats[cat]["count"] += 1
                        stats[cat]["magnitude"] += val_norm
                        stats[cat]["abs_mean"] += val_abs_mean
    
                        # Telescope Spectral Classification
                        if "lora_up" in k or ("weight" in k and "lora" in k and "down" not in k):
                            total_energy_l2 += val_norm
                            if "attn1" in k: telescope["Structure (Attn1)"].append(val_norm)
                            elif "attn2" in k: telescope["Prompt (Attn2)"].append(val_norm)
                            elif "ff" in k: telescope["Style/Color (FF)"].append(val_norm)
                            elif "resnets" in k or "conv" in k: telescope["ResNet (Conv)"].append(val_norm)
                            else: telescope["Time/Embs"].append(val_norm)
                    except: pass
    
                # --- REPORT GENERATION ---
                print(f"\n๐Ÿง  INTERNAL STRUCTURE:")
                print(f"   ๐Ÿงฎ Parameters: {total_params:,} | ๐Ÿงฑ Tensors: {len(t)}")
                if ranks:
                    print(f"   ๐Ÿ“Š Rank Breakdown: " + ", ".join([f"{k}:{v}" for k,v in sorted(ranks.items())]))
    
                print(f"\n๐Ÿ—๏ธ Architecture Map:")
                for b, c in blocks_map.items():
                    if c > 0: print(f"   ๐Ÿ”ธ {b:<10}: {c} layers")
    
                print(f"\n๐Ÿ’ช SECTIONAL STRENGTH (Visual Impact):")
                print(f"   Block       | Layers   | Avg. Intensity  | Total Magnitude")
                print(f"   ----------- | -------- | --------------- | ---------------")
                for cat, data in stats.items():
                    if data["count"] > 0:
                        avg_mean = data["abs_mean"] / data["count"]
                        print(f"   {cat:<11} | {data['count']:<8} | {avg_mean:.6f}        | {data['magnitude']:.2f}")
    
                print(f"\n๐Ÿ”ญ SPECTRAL DNA (Telescope v1):")
                print(f"   โšก Total L2 Energy: {total_energy_l2:.2f}")
    
                max_val = max([sum(v) for v in telescope.values() if v] or [1])
    
                for cat, values in telescope.items():
                    if not values: continue
                    cat_sum = sum(values)
                    percentage = (cat_sum / total_energy_l2) * 100 if total_energy_l2 > 0 else 0
                    bar_len = int((cat_sum / max_val) * 20) if max_val > 0 else 0
                    bar = "โ–ˆ" * bar_len
                    print(f"   ๐Ÿ”น {cat:<18}: {bar:<20} {percentage:.1f}% ({len(values)} layers)")
    
                # Diagnostic Inference
                p_attn2 = sum(telescope["Prompt (Attn2)"])
                p_ff = sum(telescope["Style/Color (FF)"])
                p_res = sum(telescope["ResNet (Conv)"]) + sum(telescope["Time/Embs"])
    
                print(f"\n๐Ÿฉบ CLINICAL DIAGNOSIS:")
                if p_res > (total_energy_l2 * 0.4):
                    print("   ๐ŸŽ๏ธ  CLASS: 'ACCELERATOR' (High ResNet energy; optimized for speed/step reduction).")
                elif p_attn2 > p_ff:
                    print("   ๐Ÿง  CLASS: 'CONCEPTUALIZER' (Prioritizes prompt understanding and concept accuracy).")
                elif p_ff > p_attn2:
                    print("   ๐ŸŽจ CLASS: 'STYLIST' (Prioritizes aesthetics, line-art, brushstrokes, and shading).")
                else:
                    print("   โš–๏ธ CLASS: 'HYBRID' (Balanced weight distribution across all blocks).")
    
                # Layer Sample Printout
                df = pd.DataFrame(sample_data)
                if not df.empty:
                    print(f"\n๐Ÿ” Random Layer Sample (3 layers):")
                    print(df.sample(min(3, len(df))).to_string(index=False))
    
                print(f"{'='*65}\n")
                del t
    
            except Exception as e:
                print(f"โŒ Error during forensic audit: {e}")
    
    
    # ==============================================================================
    # ๐Ÿ“Š VISUALIZER ENGINE
    # ==============================================================================
    
    def run_visualizer(files):
        print(f"\n๐Ÿ“Š PREPARING GRAPHICAL COMPARISON ({len(files)} files)...")
        plt.style.use('dark_background')
        fig, ax = plt.subplots(figsize=(16, 9))
        colors = cm.rainbow(np.linspace(0, 1, len(files)))
    
        for idx, file_path in enumerate(files):
            if not os.path.exists(file_path): continue
            clean_name = get_smart_label(file_path)
            print(f"   โžก๏ธ Plotting: {clean_name} ...")
            try:
                t = load_file(file_path, device="cpu")
                blocks = {}
                for k, v in t.items():
                    if "lora_unet" not in k or "alpha" in k: continue
                    mag = torch.abs(v).float().mean().item()
                    b_type, b_idx = parse_block_name(k)
                    if b_type == "OTHER": continue
                    ident = (b_type, b_idx)
                    if ident not in blocks: blocks[ident] = []
                    blocks[ident].append(mag)
    
                if not blocks: continue
                s_keys = sorted(blocks.keys(), key=lambda x: ({"IN":0,"MID":1,"OUT":2}.get(x[0],3), x[1]))
                x = [f"{k[0]}_{k[1]}" for k in s_keys]
                y = [sum(blocks[k])/len(blocks[k]) for k in s_keys]
                ax.plot(x, y, marker='o', lw=2, color=colors[idx], label=clean_name, alpha=0.8)
                del t
            except Exception as e:
                print(f"   โŒ Skipping {clean_name}: {e}")
    
        ax.set_title("AGGA VECTOR COMPARISON (UNet Block Intensity)", fontsize=16, color='white', pad=15)
        ax.set_xlabel("UNet Architecture Blocks", fontsize=12, color='white')
        ax.set_ylabel("Average Absolute Tensor Magnitude", fontsize=12, color='white')
        ax.legend(bbox_to_anchor=(1.01, 1), loc='upper left')
        ax.grid(True, alpha=0.2)
        plt.xticks(rotation=45, ha='right')
        plt.tight_layout()
        plt.savefig("AGGA_PLOT.png", dpi=150)
        print("\nโœจ Comparison plot successfully exported to: AGGA_PLOT.png")
        plt.show()
    
    
    # ==============================================================================
    # ๐Ÿš€ EXECUTION ENTRY POINT
    # ==============================================================================
    
    targets = get_file_list(INPUT_MODE, INPUT_PATH)
    if targets:
        if "FORENSIC" in TOOL_MODE: 
            run_forensic(targets)
        else: 
            run_visualizer(targets)
    else:
        print("โš ๏ธ No valid target files found. Please check your INPUT_PATH settings.")
    

    ๐Ÿš€ Quick Step-by-Step Guide


    Running Forensic Mode

    1. Set TOOL_MODE = "๐Ÿ”ฌ FORENSIC (Full Audit)".

    2. Set INPUT_PATH to your .safetensors file path (or a folder containing multiple files).

    3. Run the cell to view metadata, L2 spectral energy bars, and the clinical diagnosis.


    Running Visualizer Mode (Comparing Multiple LoRAs)

    1. Set TOOL_MODE = "๐Ÿ“Š VISUALIZER (Graphical Compare)".

    2. Set INPUT_MODE = "Specific_Files".

    3. In INPUT_PATH, provide comma-separated paths to your files:

      /content/LoRA_VersionA.safetensors, /content/LoRA_VersionB.safetensors
    4. Run the cell to generate AGGA_PLOT.png.


    ๐ŸŽฏ Summary

    The AGGA OMNI-TOOL v3 turns opaque .safetensors files into fully readable data. Whether you are debugging merged LoRAs, verifying rank consistency, or optimizing modular model releases, this tool provides complete technical visibility over your models.

    Archived from CivitAI ยท Updated July 27, 2026View source