Debian Codegraph @

infra/bots/task_drivers/perf_puppeteer_render_skps/perf_puppeteer_render_skps.go

raw
1 // Copyright 2020 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // This executable is meant to be a general way to gather perf data using puppeteer. The logic
6 // (e.g. what bench to run, how to process that particular output) is selected using the ExtraConfig
7 // part of the task name.
8 package main
9
10 import (
11 "context"
12 "encoding/json"
13 "flag"
14 "fmt"
15 "io/ioutil"
16 "math"
17 "os"
18 "path/filepath"
19 "sort"
20 "strings"
21
22 "go.skia.org/infra/go/exec"
23 "go.skia.org/infra/go/skerr"
24 "go.skia.org/infra/go/sklog"
25 "go.skia.org/infra/go/util"
26 "go.skia.org/infra/task_driver/go/lib/os_steps"
27 "go.skia.org/infra/task_driver/go/td"
28 )
29
30 const perfKeyWebGLVersion = "webgl_version"
31
32 func main() {
33 var (
34 // Required properties for this task.
35 projectID = flag.String("project_id", "", "ID of the Google Cloud project.")
36 taskName = flag.String("task_name", "", "Name of the task.")
37 benchmarkPath = flag.String("benchmark_path", "", "Path to location of the benchmark files (e.g. //tools/perf-puppeteer).")
38 outputPath = flag.String("output_path", "", "Perf Output will be produced here")
39 gitHash = flag.String("git_hash", "", "Git hash this data corresponds to")
40 taskID = flag.String("task_id", "", "task id this data was generated on")
41 nodeBinPath = flag.String("node_bin_path", "", "Path to the node bin directory (should have npm also). This directory *must* be on the PATH when this executable is called, otherwise, the wrong node or npm version may be found (e.g. the one on the system), even if we are explicitly calling npm with the absolute path.")
42
43 // These flags feed into the perf trace keys associated with the output data.
44 osTrace = flag.String("os_trace", "", "OS this is running on.")
45 modelTrace = flag.String("model_trace", "", "Description of host machine.")
46 cpuOrGPUTrace = flag.String("cpu_or_gpu_trace", "", "If this is a CPU or GPU configuration.")
47 cpuOrGPUValueTrace = flag.String("cpu_or_gpu_value_trace", "", "The hardware of this CPU/GPU")
48 webGLVersion = flag.String("webgl_version", "", "Major WebGL version to use when creating gl drawing context. 1 or 2")
49
50 // Flags that may be required for certain configs
51 canvaskitBinPath = flag.String("canvaskit_bin_path", "", "The location of a canvaskit.js and canvaskit.wasm")
52 skpsPath = flag.String("skps_path", "", "Path to location of skps.")
53
54 // Debugging flags.
55 local = flag.Bool("local", false, "True if running locally (as opposed to on the bots)")
56 outputSteps = flag.String("o", "", "If provided, dump a JSON blob of step data to the given file. Prints to stdout if '-' is given.")
57 )
58
59 // Setup.
60 ctx := td.StartRun(projectID, taskID, taskName, outputSteps, local)
61 defer td.EndRun(ctx)
62
63 keys := map[string]string{
64 "os": *osTrace,
65 "model": *modelTrace,
66 perfKeyCpuOrGPU: *cpuOrGPUTrace,
67 "cpu_or_gpu_value": *cpuOrGPUValueTrace,
68 perfKeyWebGLVersion: *webGLVersion,
69 }
70
71 outputWithoutResults, err := makePerfObj(*gitHash, *taskID, os.Getenv("SWARMING_BOT_ID"), keys)
72 if err != nil {
73 td.Fatal(ctx, skerr.Wrap(err))
74 }
75 // Absolute paths work more consistently than relative paths.
76 nodeBinAbsPath := td.MustGetAbsolutePathOfFlag(ctx, *nodeBinPath, "node_bin_path")
77 benchmarkAbsPath := td.MustGetAbsolutePathOfFlag(ctx, *benchmarkPath, "benchmark_path")
78 canvaskitBinAbsPath := td.MustGetAbsolutePathOfFlag(ctx, *canvaskitBinPath, "canvaskit_bin_path")
79 skpsAbsPath := td.MustGetAbsolutePathOfFlag(ctx, *skpsPath, "skps_path")
80 outputAbsPath := td.MustGetAbsolutePathOfFlag(ctx, *outputPath, "output_path")
81
82 if err := setup(ctx, benchmarkAbsPath, nodeBinAbsPath); err != nil {
83 td.Fatal(ctx, skerr.Wrap(err))
84 }
85
86 if err := benchSKPs(ctx, outputWithoutResults, benchmarkAbsPath, canvaskitBinAbsPath, skpsAbsPath, nodeBinAbsPath); err != nil {
87 td.Fatal(ctx, skerr.Wrap(err))
88 }
89
90 // outputFile name should be unique between tasks, so as to avoid having duplicate name files
91 // uploaded to GCS.
92 outputFile := filepath.Join(outputAbsPath, fmt.Sprintf("perf-%s.json", *taskID))
93 if err := processSKPData(ctx, outputWithoutResults, benchmarkAbsPath, outputFile); err != nil {
94 td.Fatal(ctx, skerr.Wrap(err))
95 }
96 }
97
98 const perfKeyCpuOrGPU = "cpu_or_gpu"
99
100 func makePerfObj(gitHash, taskID, machineID string, keys map[string]string) (perfJSONFormat, error) {
101 rv := perfJSONFormat{}
102 if gitHash == "" {
103 return rv, skerr.Fmt("Must provide --git_hash")
104 }
105 if taskID == "" {
106 return rv, skerr.Fmt("Must provide --task_id")
107 }
108 rv.GitHash = gitHash
109 rv.SwarmingTaskID = taskID
110 rv.SwarmingMachineID = machineID
111 rv.Key = keys
112 rv.Key["arch"] = "wasm"
113 rv.Key["browser"] = "Chromium"
114 rv.Key["configuration"] = "Release"
115 rv.Key["extra_config"] = "RenderSKP"
116 rv.Key["binary"] = "CanvasKit"
117 rv.Results = map[string]map[string]perfResult{}
118 return rv, nil
119 }
120
121 func setup(ctx context.Context, benchmarkPath, nodeBinPath string) error {
122 ctx = td.StartStep(ctx, td.Props("setup").Infra())
123 defer td.EndStep(ctx)
124
125 if _, err := exec.RunCwd(ctx, benchmarkPath, filepath.Join(nodeBinPath, "npm"), "ci"); err != nil {
126 return td.FailStep(ctx, skerr.Wrap(err))
127 }
128
129 // This is very important to make sure chrome is not running because we want to run chrome
130 // with an unlocked framerate (see --disable-frame-rate-limit and --disable-gpu-vsync in
131 // perf-canvaskit-with-puppeteer.js) and that won't happen if there is already an existing
132 // chrome instance running when we try to run puppeteer. killall will return an error (e.g.
133 // a non-zero error code) if there isn't already a chrome instance running. We can safely
134 // ignore that error as we never expect there to be chrome running.
135 _, _ = exec.RunSimple(ctx, "killall chrome")
136
137 if err := os.MkdirAll(filepath.Join(benchmarkPath, "out"), 0777); err != nil {
138 return td.FailStep(ctx, skerr.Wrap(err))
139 }
140 return nil
141 }
142
143 var cpuSkiplist = []string{
144 // When the SKPs were generated on Sept 27 2020, this started to timeout on CPU
145 "desk_carsvg.skp",
146 // This started timing out the week of Feb 10, 2021 on CPU.
147 "desk_micrographygirlsvg.skp",
148 // Started timing out the week of Mar 25 2021 on CPU.
149 "desk_motionmarkpaths.skp",
150 // Started timing out the week of July 26 2021 on CPU.
151 "desk_motionmarksuits.skp",
152 // Started timing out on Nov 3, 2021 on CPU.
153 "desk_motionmarkleaves.skp",
154 // Started timing out on Nov 4, 2022 on CPU.
155 "desk_motionmarkarcs.skp",
156 }
157 var gpuSkiplist = []string{}
158
159 // benchSKPs serves skps from a folder and runs the RenderSKPs benchmark on each of them
160 // individually. The benchmark is run N times to reduce the noise of the resulting data.
161 // The output for each will be a JSON file in $benchmarkPath/out/ corresponding to the skp name
162 // and the iteration it was.
163 func benchSKPs(ctx context.Context, perf perfJSONFormat, benchmarkPath, canvaskitBinPath, skpsPath, nodeBinPath string) error {
164 ctx = td.StartStep(ctx, td.Props("perf skps in "+skpsPath))
165 defer td.EndStep(ctx)
166
167 // We expect the skpsPath to a directory with skp files in it.
168 var skpFiles []string
169 err := td.Do(ctx, td.Props("locate skpfiles"), func(ctx context.Context) error {
170 return filepath.Walk(skpsPath, func(path string, info os.FileInfo, _ error) error {
171 if path == skpsPath {
172 return nil
173 }
174 if info.IsDir() {
175 return filepath.SkipDir
176 }
177 skpFiles = append(skpFiles, path)
178 return nil
179 })
180 })
181 if err != nil {
182 return td.FailStep(ctx, skerr.Wrap(err))
183 }
184 skiplist := cpuSkiplist
185 if perf.Key[perfKeyCpuOrGPU] != "CPU" {
186 skiplist = gpuSkiplist
187 }
188 sklog.Infof("Identified %d skp files to benchmark", len(skpFiles))
189
190 for _, skp := range skpFiles {
191 name := filepath.Base(skp)
192 if util.In(name, skiplist) {
193 sklog.Infof("Skipping skp %s", name)
194 continue
195 }
196 err = td.Do(ctx, td.Props(fmt.Sprintf("Benchmark %s", name)), func(ctx context.Context) error {
197 // See comment in setup about why we specify the absolute path for node.
198 args := []string{filepath.Join(nodeBinPath, "node"),
199 "perf-canvaskit-with-puppeteer",
200 "--bench_html", "render-skp.html",
201 "--canvaskit_js", filepath.Join(canvaskitBinPath, "canvaskit.js"),
202 "--canvaskit_wasm", filepath.Join(canvaskitBinPath, "canvaskit.wasm"),
203 "--timeout", "90", // 90 seconds before timeout
204 "--input_skp", skp,
205 "--output", filepath.Join(benchmarkPath, "out", name+".json"),
206 }
207 if perf.Key[perfKeyCpuOrGPU] != "CPU" {
208 args = append(args, "--use_gpu")
209 if perf.Key[perfKeyWebGLVersion] == "1" {
210 args = append(args, "--query_params webgl1")
211 }
212 }
213 _, err := exec.RunCwd(ctx, benchmarkPath, args...)
214 if err != nil {
215 return skerr.Wrap(err)
216 }
217 return nil
218 })
219 if err != nil {
220 return td.FailStep(ctx, skerr.Wrap(err))
221 }
222 }
223 return nil
224 }
225
226 // TODO(kjlubick,jcgregorio) Could this code directly refer to the struct in Perf?
227 type perfJSONFormat struct {
228 GitHash string `json:"gitHash"`
229 SwarmingTaskID string `json:"swarming_task_id"`
230 SwarmingMachineID string `json:"swarming_machine_id"`
231 Key map[string]string `json:"key"`
232 // Maps bench name -> "config" -> result key -> value
233 Results map[string]map[string]perfResult `json:"results"`
234 }
235
236 type perfResult map[string]float32
237
238 // processSKPData looks at the result of benchSKPs, computes summary data on
239 // those files and adds them as Results into the provided perf object. The perf object is then
240 // written in JSON format to outputPath.
241 func processSKPData(ctx context.Context, perf perfJSONFormat, benchmarkPath, outputFilePath string) error {
242 perfJSONPath := filepath.Join(benchmarkPath, "out")
243 ctx = td.StartStep(ctx, td.Props("process perf output "+perfJSONPath))
244 defer td.EndStep(ctx)
245
246 var jsonInputs []string
247 err := td.Do(ctx, td.Props("locate input JSON files"), func(ctx context.Context) error {
248 return filepath.Walk(perfJSONPath, func(path string, info os.FileInfo, _ error) error {
249 if strings.HasSuffix(path, ".json") {
250 jsonInputs = append(jsonInputs, path)
251 return nil
252 }
253 return nil
254 })
255 })
256 if err != nil {
257 return td.FailStep(ctx, skerr.Wrap(err))
258 }
259
260 sklog.Infof("Identified %d JSON inputs to process", len(jsonInputs))
261
262 for _, skp := range jsonInputs {
263 err = td.Do(ctx, td.Props("Process "+skp), func(ctx context.Context) error {
264 name := strings.TrimSuffix(filepath.Base(skp), ".json")
265 config := "software"
266 if perf.Key[perfKeyCpuOrGPU] != "CPU" {
267 config = "webgl2"
268 if perf.Key[perfKeyWebGLVersion] == "1" {
269 config = "webgl1"
270 }
271 }
272
273 b, err := os_steps.ReadFile(ctx, skp)
274 if err != nil {
275 return skerr.Wrap(err)
276 }
277 metrics, err := parseSKPData(b)
278 if err != nil {
279 return skerr.Wrap(err)
280 }
281
282 perf.Results[name] = map[string]perfResult{
283 config: metrics,
284 }
285 return nil
286 })
287 if err != nil {
288 return td.FailStep(ctx, skerr.Wrap(err))
289 }
290 }
291
292 err = td.Do(ctx, td.Props("Writing perf JSON file to "+outputFilePath), func(ctx context.Context) error {
293 if err := os.MkdirAll(filepath.Dir(outputFilePath), 0777); err != nil {
294 return skerr.Wrap(err)
295 }
296 b, err := json.MarshalIndent(perf, "", " ")
297 if err != nil {
298 return skerr.Wrap(err)
299 }
300 if err = ioutil.WriteFile(outputFilePath, b, 0666); err != nil {
301 return skerr.Wrap(err)
302 }
303 return nil
304 })
305 if err != nil {
306 return td.FailStep(ctx, skerr.Wrap(err))
307 }
308
309 return nil
310 }
311
312 type skpPerfData struct {
313 WithoutFlushMS []float32 `json:"without_flush_ms"`
314 WithFlushMS []float32 `json:"with_flush_ms"`
315 TotalFrameMS []float32 `json:"total_frame_ms"`
316 SKPLoadMS float32 `json:"skp_load_ms"`
317 }
318
319 func parseSKPData(b []byte) (perfResult, error) {
320 var data skpPerfData
321 if err := json.Unmarshal(b, &data); err != nil {
322 return nil, skerr.Wrap(err)
323 }
324
325 avgWithoutFlushMS, medianWithoutFlushMS, stddevWithoutFlushMS := summarize(data.WithoutFlushMS)
326 avgWithFlushMS, medianWithFlushMS, stddevWithFlushMS := summarize(data.WithFlushMS)
327 avgTotalFrameMS, medianTotalFrameMS, stddevTotalFrameMS := summarize(data.TotalFrameMS)
328
329 return map[string]float32{
330 "avg_render_without_flush_ms": avgWithoutFlushMS,
331 "median_render_without_flush_ms": medianWithoutFlushMS,
332 "stddev_render_without_flush_ms": stddevWithoutFlushMS,
333
334 "avg_render_with_flush_ms": avgWithFlushMS,
335 "median_render_with_flush_ms": medianWithFlushMS,
336 "stddev_render_with_flush_ms": stddevWithFlushMS,
337
338 "avg_render_frame_ms": avgTotalFrameMS,
339 "median_render_frame_ms": medianTotalFrameMS,
340 "stddev_render_frame_ms": stddevTotalFrameMS,
341
342 "skp_load_ms": data.SKPLoadMS,
343 }, nil
344 }
345
346 func summarize(input []float32) (float32, float32, float32) {
347 // Make a copy of the data so we don't mutate the order of the original
348 sorted := make([]float32, len(input))
349 copy(sorted, input)
350 sort.Slice(sorted, func(i, j int) bool {
351 return sorted[i] < sorted[j]
352 })
353
354 avg := computeAverage(sorted)
355 variance := float32(0)
356 for i := 0; i < len(sorted); i++ {
357 variance += (sorted[i] - avg) * (sorted[i] - avg)
358 }
359 stddev := float32(math.Sqrt(float64(variance / float32(len(sorted)))))
360
361 medIdx := (len(sorted) * 50) / 100
362
363 return avg, sorted[medIdx], stddev
364 }
365
366 func computeAverage(d []float32) float32 {
367 avg := float32(0)
368 for i := 0; i < len(d); i++ {
369 avg += d[i]
370 }
371 avg /= float32(len(d))
372 return avg
373 }