|
| 1 | +import glob |
| 2 | +import json |
| 3 | +import numpy as np |
| 4 | +import pandas as pd |
| 5 | +import matplotlib.pyplot as plt |
| 6 | +import re |
| 7 | +import os |
| 8 | +import argparse |
| 9 | +import sys |
| 10 | + |
| 11 | +# Only does plotting for AutoTunerBase variants |
| 12 | +AT_REGEX = r"variant-AutoTunerBase-([\w-]+)-\w+" |
| 13 | + |
| 14 | +# TODO: Make sure the distributed.py METRIC variable is consistent with this, single source of truth. |
| 15 | +METRIC = "metric" |
| 16 | + |
| 17 | +cur_dir = os.path.dirname(os.path.abspath(__file__)) |
| 18 | +root_dir = os.path.join(cur_dir, "../../../../../") |
| 19 | +os.chdir(root_dir) |
| 20 | + |
| 21 | + |
| 22 | +def load_dir(dir: str) -> pd.DataFrame: |
| 23 | + """ |
| 24 | + Load and merge progress, parameters, and metrics data from a specified directory. |
| 25 | + This function searches for `progress.csv`, `params.json`, and `metrics.json` files within the given directory, |
| 26 | + concatenates the data, and merges them into a single pandas DataFrame. |
| 27 | + Args: |
| 28 | + dir (str): The directory path containing the subdirectories with `progress.csv`, `params.json`, and `metrics.json` files. |
| 29 | + Returns: |
| 30 | + pd.DataFrame: A DataFrame containing the merged data from the progress, parameters, and metrics files. |
| 31 | + """ |
| 32 | + |
| 33 | + # Concatenate progress DFs |
| 34 | + progress_csvs = glob.glob(f"{dir}/*/progress.csv") |
| 35 | + if len(progress_csvs) == 0: |
| 36 | + print("No progress.csv files found.") |
| 37 | + sys.exit(1) |
| 38 | + progress_df = pd.concat([pd.read_csv(f) for f in progress_csvs]) |
| 39 | + |
| 40 | + # Concatenate params.json & metrics.json file |
| 41 | + params = [] |
| 42 | + failed = [] |
| 43 | + for params_fname in glob.glob(f"{dir}/*/params.json"): |
| 44 | + metrics_fname = params_fname.replace("params.json", "metrics.json") |
| 45 | + try: |
| 46 | + with open(params_fname, "r") as f: |
| 47 | + _dict = json.load(f) |
| 48 | + _dict["trial_id"] = re.search(AT_REGEX, params_fname).group(1) |
| 49 | + with open(metrics_fname, "r") as f: |
| 50 | + metrics = json.load(f) |
| 51 | + ws = metrics["finish"]["timing__setup__ws"] |
| 52 | + metrics["worst_slack"] = ws |
| 53 | + _dict.update(metrics) |
| 54 | + params.append(_dict) |
| 55 | + except Exception as e: |
| 56 | + failed.append(metrics_fname) |
| 57 | + continue |
| 58 | + |
| 59 | + # Merge all dataframe |
| 60 | + params_df = pd.DataFrame(params) |
| 61 | + try: |
| 62 | + progress_df = progress_df.merge(params_df, on="trial_id") |
| 63 | + except KeyError: |
| 64 | + print( |
| 65 | + "Unable to merge DFs due to missing trial_id in params.json (possibly due to failed trials.)" |
| 66 | + ) |
| 67 | + sys.exit(1) |
| 68 | + |
| 69 | + # Print failed, if any |
| 70 | + if failed: |
| 71 | + failed_files = "\n".join(failed) |
| 72 | + print(f"Failed to load {len(failed)} files:\n{failed_files}") |
| 73 | + return progress_df |
| 74 | + |
| 75 | + |
| 76 | +def preprocess(df: pd.DataFrame) -> pd.DataFrame: |
| 77 | + """ |
| 78 | + Preprocess the input DataFrame by renaming columns, removing unnecessary columns, |
| 79 | + filtering out invalid rows, and normalizing the timestamp. |
| 80 | + Args: |
| 81 | + df (pd.DataFrame): The input DataFrame to preprocess. |
| 82 | + Returns: |
| 83 | + pd.DataFrame: The preprocessed DataFrame with renamed columns, removed columns, |
| 84 | + filtered rows, and normalized timestamp. |
| 85 | + """ |
| 86 | + |
| 87 | + cols_to_remove = [ |
| 88 | + "done", |
| 89 | + "training_iteration", |
| 90 | + "date", |
| 91 | + "pid", |
| 92 | + "hostname", |
| 93 | + "node_ip", |
| 94 | + "time_since_restore", |
| 95 | + "time_total_s", |
| 96 | + "iterations_since_restore", |
| 97 | + ] |
| 98 | + rename_dict = { |
| 99 | + "time_this_iter_s": "runtime", |
| 100 | + "_SDC_CLK_PERIOD": "clk_period", # param |
| 101 | + } |
| 102 | + try: |
| 103 | + df = df.rename(columns=rename_dict) |
| 104 | + df = df.drop(columns=cols_to_remove) |
| 105 | + df = df[df[METRIC] != 9e99] |
| 106 | + df["timestamp"] -= df["timestamp"].min() |
| 107 | + return df |
| 108 | + except KeyError as e: |
| 109 | + print( |
| 110 | + f"KeyError: {e} in the DataFrame. Dataframe does not contain necessary columns." |
| 111 | + ) |
| 112 | + sys.exit(1) |
| 113 | + |
| 114 | + |
| 115 | +def plot(df: pd.DataFrame, key: str, dir: str): |
| 116 | + """ |
| 117 | + Plots a scatter plot with a linear fit and a box plot for a specified key from a DataFrame. |
| 118 | + Args: |
| 119 | + df (pd.DataFrame): The DataFrame containing the data to plot. |
| 120 | + key (str): The column name in the DataFrame to plot. |
| 121 | + dir (str): The directory where the plots will be saved. The directory must exist. |
| 122 | + Returns: |
| 123 | + None |
| 124 | + """ |
| 125 | + |
| 126 | + assert os.path.exists(dir), f"Directory {dir} does not exist." |
| 127 | + # Plot box plot and time series plot for key |
| 128 | + fig, ax = plt.subplots(1, figsize=(15, 10)) |
| 129 | + ax.scatter(df["timestamp"], df[key]) |
| 130 | + ax.set_xlabel("Time (s)") |
| 131 | + ax.set_ylabel(key) |
| 132 | + ax.set_title(f"{key} vs Time") |
| 133 | + |
| 134 | + try: |
| 135 | + coeff = np.polyfit(df["timestamp"], df[key], 1) |
| 136 | + poly_func = np.poly1d(coeff) |
| 137 | + ax.plot( |
| 138 | + df["timestamp"], |
| 139 | + poly_func(df["timestamp"]), |
| 140 | + "r--", |
| 141 | + label=f"y={coeff[0]:.2f}x+{coeff[1]:.2f}", |
| 142 | + ) |
| 143 | + ax.legend() |
| 144 | + except np.linalg.LinAlgError: |
| 145 | + print("Cannot fit a line to the data, plotting only scatter plot.") |
| 146 | + |
| 147 | + fig.savefig(f"{dir}/{key}.png") |
| 148 | + |
| 149 | + plt.figure(figsize=(15, 10)) |
| 150 | + plt.boxplot(df[key]) |
| 151 | + plt.ylabel(key) |
| 152 | + plt.title(f"{key} Boxplot") |
| 153 | + plt.savefig(f"{dir}/{key}-boxplot.png") |
| 154 | + |
| 155 | + |
| 156 | +def main(platform: str, design: str, experiment: str): |
| 157 | + """ |
| 158 | + Main function to process results from a specified directory and plot the results. |
| 159 | + Args: |
| 160 | + platform (str): The platform name. |
| 161 | + design (str): The design name. |
| 162 | + experiment (str): The experiment name. |
| 163 | + Returns: |
| 164 | + None |
| 165 | + """ |
| 166 | + |
| 167 | + results_dir = os.path.join( |
| 168 | + root_dir, f"./flow/logs/{platform}/{design}/{experiment}" |
| 169 | + ) |
| 170 | + img_dir = os.path.join( |
| 171 | + root_dir, f"./flow/reports/images/{platform}/{design}/{experiment}" |
| 172 | + ) |
| 173 | + print("Processing results from", results_dir) |
| 174 | + os.makedirs(img_dir, exist_ok=True) |
| 175 | + df = load_dir(results_dir) |
| 176 | + df = preprocess(df) |
| 177 | + keys = [METRIC] + ["runtime", "clk_period", "worst_slack"] |
| 178 | + |
| 179 | + # Plot only if more than one entry |
| 180 | + if len(df) < 2: |
| 181 | + print("Less than 2 entries, skipping plotting.") |
| 182 | + sys.exit(0) |
| 183 | + for key in keys: |
| 184 | + plot(df, key, img_dir) |
| 185 | + |
| 186 | + |
| 187 | +if __name__ == "__main__": |
| 188 | + parser = argparse.ArgumentParser(description="Plot AutoTuner results.") |
| 189 | + parser.add_argument("--platform", type=str, help="Platform name.", required=True) |
| 190 | + parser.add_argument("--design", type=str, help="Design name.", required=True) |
| 191 | + parser.add_argument( |
| 192 | + "--experiment", type=str, help="Experiment name.", required=True |
| 193 | + ) |
| 194 | + args = parser.parse_args() |
| 195 | + main(platform=args.platform, design=args.design, experiment=args.experiment) |
0 commit comments