Open main menu

CDOT Wiki β

Fall 2021 SPO600 Weekly Schedule

Revision as of 09:22, 29 November 2021 by Chris Tyler (talk | contribs) (Schedule Summary Table)

This is the schedule and main index page for the SPO600 Software Portability and Optimization course for Fall 2021.

Important.png
It's Alive!
This SPO600 weekly schedule will be updated as the course proceeds - dates and content are subject to change. The cells in the summary table will be linked to relevant resources and labs as the course progresses.

Schedule Summary Table

Week 1

Week 1 - Class II

Introduction to the Problems

Porting and Portability
  • Most software is written in a high-level language which can be compiled into machine code for a specific computer architecture. In many cases, this code can be compiled for multiple architectures. However, there is a lot of existing code that contains some architecture-specific code fragments written in architecture-specific high-level code or in Assembly Language.
  • Reasons that code is architecture-specific:
    • System assumptions that don't hold true on other platforms
    • Code that takes advantage of platform-specific features
  • Reasons for writing code in Assembly Langauge include:
    • Performance
    • Atomic Operations
    • Direct access to hardware features, e.g., CPUID registers
  • Most of the historical reasons for including assembler are no longer valid. Modern compilers can out-perform most hand-optimized assembly code, atomic operations can be handled by libraries or compiler intrinsics, and most hardware access should be performed through the operating system or appropriate libraries.
  • A new architecture has appeared: AArch64, which is part of ARMv8. This is the first new computer architecture to appear in several years (at least, the first mainstream computer architecture).
  • At this point, most key open source software (the software typically present in a Linux distribution such as Ubuntu or Fedora, for example) now runs on AArch64. However, it may not run as well as on older architectures (such as x86_64).
Benchmarking and Profiling

Benchmarking involves testing software performance under controlled conditions so that the performance can be compared to other software, the same software operating on other types of computers, or so that the impact of a change to the software can be gauged.

Profiling is the process of analyzing software performance on finer scale, determining resource usage per program part (typically per function/method). This can identify software bottlenecks and potential targets for optimization.

Optimization

Optimization is the process of evaluating different ways that software can be written or built and selecting the option that has the best performance tradeoffs.

Optimization may involve substituting software algorithms, altering the sequence of operations, using architecture-specific code, or altering the build process. It is important to ensure that the optimized software produces correct results and does not cause an unacceptable performance regression for other use-cases, system configurations, operating systems, or architectures.

The definition of "performance" varies according to the target system and the operating goals. For example, in some contexts, low memory or storage usage is important; in other cases, fast operation; and in other cases, low CPU utilization or long battery life may be the most important factor. It is often possible to trade off performance in one area for another; using a lookup table, for example, can reduce CPU utilization and improve battery life in some algorithms, in return for increased memory consumption.

Most advanced compilers perform some level of optimization, and the options selected for compilation can have a significant effect on the trade-offs made by the compiler, affecting memory usage, execution speed, executable size, power consumption, and debuggability.

Build Process

Building software is a complex task that many developers gloss over. The simple act of compiling a program invokes a process with five or more stages, including pre-proccessing, compiling, optimizing, assembling, and linking. However, a complex software system will have hundreds or even thousands of source files, as well as dozens or hundreds of build configuration options, auto configuration scripts (cmake, autotools), build scripts (such as Makefiles) to coordinate the process, test suites, and more.

The build process varies significantly between software packages. Most software distribution projects (including Linux distributions such as Ubuntu and Fedora) use a packaging system that further wraps the build process in a standardized script format, so that different software packages can be built using a consistent process.

In order to get consistent and comparable benchmark results, you need to ensure that the software is being built in a consistent way. Altering the build process is one way of optimizing software.

Note that the build time for a complex package can range up to hours or even days!

General Course Information

  • Course resources are linked from the CDOT wiki, starting at https://wiki.cdot.senecacollege.ca/wiki/SPO600 (Quick find: This page will usually be Google's top result for a search on "SPO600").
  • Coursework is submitted by blogging.
  • Quizzes will be short (1 page) and will be held without announcement at the start of any synchronous class. There is no opportunity to re-take a missed quiz, but your lowest three quiz scores will not be counted, so do not worry if you miss one or two.
    • Students with test accommodations: an alternate monthly quiz can be made available via the Test Centre. See your professor for details.
  • Course marks (see Weekly Schedule for dates):
    • 60% - Project Deliverables
    • 20% - Communication (Blog and Wiki writing)
    • 20% - Labs and Quizzes (10% labs - completed/not completed; 10% for quizzes - lowest 3 scores not counted)

Classes

  • Monday: asynchronous (pre-recorded) resources will be made available - see this page for details each week
  • Thursay: synchronous (live) classes will be held 8:00-9:50 am Eastern Time. See the announcement on Blackboard for details.

Course and Setup: Accounts, agreements, servers, and more

How open source communities work

Week 1 Deliverables

  1. Course setup:
    1. Set up your SPO600 Communication Tools - in particular, set up a blog.
    2. Add yourself to the Current SPO600 Participants page (leave the projects columns blank).
    3. Generate a pair of keys for SSH and email the public key to your professor, so that he can set up your access to the class servers.
    4. Optional (strongly recommended): Set up a personal Linux system.
    5. Optional: Purchase an AArch64 development board (such as a 96Boards HiKey or Raspberry Pi 3 or 4. (If you use a Pi, install a 64-bit Linux operating system on it, not a 32-bit version).
  2. Start work on Lab 1.


Week 2

Week 2 - Class I

Videos

Binary Representation of Data

  • Binary
    • Binary is a system which uses "bits" (binary digits) to represent values.
    • Each bit has one of two values, signified by the symbols 0 and 1. These correspond to:
      • Electrically: typically off/on, or low/high voltage, or low/high current. Many other electrical representations are possible.
      • Logically: false or true.
    • Binary numbers are resistant to errors, especially when compared to other systems such as analog voltages.
      • To represent the numbers 0-5 as an analog electical value, we could use a voltage from 0 - 5 volts. However, if we use a long cable, there will be signal loss the voltage will drop: we could apply 5 volts on one end of the cable, but only observe (say) 4.1 volts on the other end of the cable. Alternately, electromagnetic interference from nearby devices could slight increase the signal.
      • If we use instead use the same voltages and cable length to carry a binary signal, where 0 volts = off and 5 volts = on, a signal that had degraded from 5 volts to 4.1 volts would still be counted as a "1" and a 0 volt signal with some stray electromagnetic interference presenting as (say) 0.4 volts would still be counted as "0". However, we will need to use multiple bits to carry larger numbers -- either in parallel (multiple wires side-by-side), or sequentially (multiple bits presented over the same wire in sequence).
  • Integers
    • Integers are the basic building block of binary numbering schemes.
    • In an unsigned integer, the bits are numbered from right to left starting at 0, and the value of each bit is 2bit. The value represented is the sum of each bit multiplied by its corresponding bit value. The range of an unsigned integer is 0:2bits-1 where bits is the number of bits in the unsigned integer.
    • Signed integers are generally stored in twos-complement format, where the highest bit is used as a sign bit. If that bit is set, the value represented is -(!value)-1 where ! is the NOT operation (each bit gets flipped from 0→1 and 1→0)
  • Fixed-point
    • A fixed-point value is encoded the same as an integer, except that some of the bits are fractional -- they're considered to be to the right of the "binary point" (binary version of "decimal point" - or more generically, the radix point). For example, binary 000001.00 is decimal 1.0, and 000001.11 is decimal 1.75.
    • An alternative to fixed-point values is integer values in a smaller unit of measurement. For example, some accounting software may use integer values representing cents. For input and display purposes, dollar and cent values are converted to/from cent values.
  • Floating-point
    • Floating point numbers have three parts: a sign bit (0 for positive, 1 for negative), a mantissa or significand, and an exponent. The value is interpreted as sign mantissa * 2exponent.
    • The most commonly-used floating point formats are defined in the IEEE 754 standard.
  • Sound
    • Sound waves are air pressure vibrations
    • Digital sound is most often represented in raw form as a series of time-based measurements of air pressure, called Pulse Coded Modulation (PCM)
    • PCM takes a lot of storage, so sound is often compressed in either a lossless (perfectly recoverable) or lossy format (higher compression, but the decompressed data doesn't perfectly match the original data). To permit high compression ratios with minimal impact on quality, psychoacoustic compression is used - sound variations that most people can't perceive are removed.
  • Graphics
    • The human eye perceives luminance (brightness) as well as hue (colour). Our hue receptors are generally sensitive to three wavelengths: red, green, and blue (RGB). We can stimulate the eye to perceive most colours by presenting a combination of light at these three wavelengths.
    • Digital displays emit RGB colours, which are mixed together and perceived by the viewer. For printing, cyan/yellow/magenta inks are used, plus black to reduce the amount of colour ink required to represent dark tones; this is known as CYMK colour.
    • Images are broken into picture elements (pixels) and each pixel is usually represented by a group of values for RGB or CYMK channels, where each channel is represented by an integer or floating-point value. For example, using an 8-bit-per-pixel integer scheme (also known as 24-bit colour), the brightest blue could be represented as R=0,G=0,B=255; the brightest yellow would be R=255,G=255,B=0; black would be R=0,G=0,B=0; and white would be R=255,G=255,B=255. With this scheme, the number of unique colours available is 256^3 ~= 16 million.
    • As with sound, the raw storage of sampled data requires a lot of storage space, so various lossy and lossless compression schemes are used. Highest compression is achieved with psychovisual compression (e.g., JPEG).
    • Moving pictures (video, animations) are stored as sequential images, often compressed by encoding only the differences between frames to save storage space.
  • Compression techniques
    • Huffman encoding / Adaptive arithmetic encoding
      • Instead of fixed-length numbers, variable-length numbers are used, with the most common values encoded in the smallest number of bits. This is an effective strategy if the distribution of values in the data set is uneven.
    • Repeated sequence encoding (1D, 2D, 3D)
      • Run length encoding is an encoding scheme that records the number of repeated values. For example, fax messages are encoded as a series of numbers representing the number of white pixels, then the number of black pixels, the white pixels, then black pixels, alternating to the end of each line. These numbers are then represented with adaptive artithmetic encoding.
      • Text data can be compressed by building a dictionary of common sequences, which may represent words or complete phrases, where each entry in the dictionary is numbered. The compressed data contains the dictionary plus a sequence of numbers which represent the occurrence of the sequences in the original text. On standard text, this typically enables 10:1 compression.
    • Decomposition
      • Compound audio wavforms can be decomposed into individual signals, which can then be modelled as repeated sequences. For example, a waveform consisting of two notes being played at different frequencies can be decomposed into those separate notes; since each note consists of a number of repetitions of a particular wave pattern, they can individually be represented in a more compact format by describing the frequence, waveform shape, and amplitude characteristics.
    • Pallettization
      • Images often contain repeated colours, and rarely use all of the available colours in the original encoding scheme. For example, a 1920x1080 image contains about 2 million pixels, so if every pixel was a different colour, there would be a maximum of 2 million colours. But it's likely that many of the pixels in the image are the same colour, so there might only be (perhaps) 4000 colours in the image. If each pixel is encoded as a 24-bit value, there are potentially 16 million colours available, and there is no possibility that they are all used. Instead, a palette can be provided which specifies each of the 4000 colours used in the picture, and then each pixel can be encoded as a 12-bit number which selects one of the colours from the palette. The total storage requirement for the original 24-bit scheme is 1920*1080*3 bytes per pixel = 5.9 MB. Using a 12-bit pallette, the storage requirement is 3 * 4096 bytes for the palette plus 1920*1080*1.5 bytes for the image, for a total of 3 MB -- a reduction of almost 50%
    • Psychoacoustic and psychovisual compression
      • Much of the data in sound and images cannot be perceived by humans. Psychoacoustic and psychovisual compression remove artifacts which are least likely to be perceived. As a simple example, if two pixels on opposite sides of a large image are almost but not exactly the same, most people won't be able to tell the difference, so these can be encoded as the same colour if that saves space (for example, by reducing the size of the colour palette).

Week 2 - Class II

Computer Architecture Overview

Introduction to Assembly Language on the 6502 Processor

https://web.microsoftstream.com/video/6a645edd-3537-4910-843c-6d32f6678e79

To understand basic assembly/machine language concepts, we're going to start with a very simple processor: the 6502.

6502 Assembly Language Lab

Week 2 Deliverables


Week 3

Week 3 - Class I

Videos

6502 Assembly Language - Continued

Week 3 - Class II

Week 3 Deliverables

  • Complete and blog about Lab 2

Week 4

Week 4 - Class I

Videos

Characters, Strings, and System Routines

  • Characters are encoded in binary by numeric reference to a character in a character set. For example, characters in ASCII are encoded as 7-bit values in the range 0-127, which refer to characters in the American Standard Code for Information Interchange character set: code 32 represents a space (" "), 48 represents a zero ("0"), code 49 represents a one ("1"), and code 65 represents a capital letter A.
  • Strings in assembler are stored as sequences of bytes. As is usually the case in assembler, memory management is left to the programmer. You can terminate strings with null bytes (C-style), which are easy to detect one some CPUs (e.g., lda followed by bne / beq on a 6502), or you can use character counts to track string lengths.
  • The 6502 emulator has a 80x25 character display mapped starting at location $f000. Writing to a byte to screen memory will cause that character to be displayed at the corresponding location on the screen, if the character is printable. If the high bit is set, the character will be displayed in  reverse video . For example, storing the ASCII code for "A" (which is 65 or $41) into memory location $f000 will display the letter "A" as the first character on the screen; ORing the value with 128 ($80) yields a value of 193 or $d1, and storing that value into $f000 will display A as the first character on the screen.
  • A "ROM chip" with screen control routines is mapped into the emulator at the end of the memory space (at the time of writing, the current version of the ROM exists in pages $fe and $ff). Details of the available ROM routines can be viewed using the "Notes" button in the emulator or on the emulator page on this wiki.
    • To write to the screen, you can use the SCINIT (SCreen INITialize) routine followed by calls to the CHROUT (CHaRacter OUTput) routine. CHROUT handles things like cursor movement, newline ($0d) characters, and screen scrolling.

Week 4 - Class II

Week 4 Deliverables

Week 5

Week 5 - Class I

Videos

Building Code

  • C code is built with the C compiler, typically called cc (which is usually an alias for a specific C compiler, such as gcc, clang, or bcc).
  • The C compiler runs through five steps, often by calling separate executables:
    1. Preprocessing - performed by the C Preprocessor (cpp), this step handles directives such as #include, #define, and #ifdef to build produce a single source code text file, with cross-references to the original input files so that error messages can be displayed correctly (e.g., an error in an included file can be correctly reported by filename and line number).
    2. Compilation - the C source code is converted to assembler, going through one or more intermedie representations (IR) such as GENERIC or GIMPLE, or LLVM IR. The program used for this step is often called cc1.
    3. Optimization - various optimization passes are performed at different stages of processing through multiple passes, but centered on IR at the compilation step. Sometimes, the work of a previous pass is undone by a later pass: for example, a complex loop may be converted into a series of simpler loops by an early pass, in the hope that optimizations can be applied to one or more of the simpler loops; the loops may later be recombined to single loop if no optimizations are found that are applicable to the simplified loops.
    4. Assembly - converts the assembly language code emitted by the compilation stage into binary object code.
    5. Linking - connects code to functions (aka methods or procedures) which were compiled in other compilation units (they may be pre-compiled libraries available on the system, or they may be other pieces of the same code base which are compiled in separate steps). Linking may be static, where libraries are imported into the binary executable file of the output program, or linking may be dynamic, where additional information is added to the binary executable file so that a run-time linker can load and connect libraries at runtime.
  • Other languages which are compiled to binary form, such as C++, Ocaml, Haskell, Fortran, and COBOL go through similar processing. Languages which do not compile to binary form are either compiled to a bytecode format (binary code that doesn't correspond to actual hardware), or left in original source format, and an interpreter reads and executes the bytecode or source code at runtime. Java and Python use bytecode; Bash and JavaScript interpret source code. Some interpreters build and cache blocks of machine code on-the-fly; this is called Just-in-Time (JIT) compilation.
  • Compiler feature flags control the operation of the compiler on the source code, including optimiation passes. When using gcc, these "feature flags" take the form -f[no-]featureName -- for example:
    • -fbuiltin -- enables the "builtin" feature
    • -fno-builtin -- disables the "builtin" feature
  • Feature flags can be selected in groups using the optimization (-O) level:
    • -O0 -- disables most (but not all) optimizations
    • -O1 -- enables basic optimizations that can be performed quickly
    • -O2 -- enables almost all safe operatimizations
    • -O3 -- enables agressive optimization, including optimizations which may not always be safe for all code (e.g., assuming +0 == -0)
    • -Os -- optimzies for small binary and runtime size, possibly at the expense of speed
    • -Ofast -- optimizes for fast execution, possibly at the expense of size
    • -Og -- optimizes for debugging: applies optimizations that can be performed quickly, and avoids optimizations which convolute the code
  • To see the optimizations which are applied at each level in gcc, use: gcc -Q --help=optimizers -Olevel -- it's interesting to compare the output of different levels, such as -O0 and -O3
  • Different CPUs in one family can have different capabilities and performance characteristics. The compiler options -march sets the overall architecture family and CPU features to be targetted, and the -mtune option sets the specific target for tuning. Thus, you can produce an executable that will work across a range of CPUs, but is specifically tuned to perform best on a certain model. For example, -march=ivybridge -mtune=knl will cause the processor to use features which are present on all Intel Ivy Bridge (and later) processors, but tuned for optimal performance on Knight's Landing processors. Similarly, -march=armv8-a -mtune=cortex-a72 will cause the compiler to emit code which will safely run on any ARMv8-a processor, but be tuned specifically for the Cortex-A72 core.
  • When building code on different platforms, there are a lot of variables which may need to be fed into the preprocessor, compiler, and linker. These can be manually specified, or they can be automatically determined by a tool such as GNU Autotools (typically visible as the configure script in the source code archive).
  • The source code for large projects is divided into many source files for manageability. The dependencies between these files can become complex. When developing or debugging the software, it is often necessary to make changes in one or a small number of files, and it may not be necessary to rebuild the entire project from scratch. The make utility is used to script a build and to enable rapid partial rebuilds after a change to source code files (see Make and Makefiles).
  • Many open source projects distribute code as a source archive ("tarball") which usually decompresses to a subdirectory packageName-version (e.g. foolib-1.5.29). This will typically contain a script which configures the Makefile (configure if using GNU Autotools). After running this script, a Makefile will be available, which can be used to build the software. However, some projects use an alternative configuration tool instead of GNU Autotools, and some may use an alternate build system instead of make.
  • To eliminate this variation, most Linux distributions use a package system, which standardizes the build process and which produces installable package files which can be used to reliably install software into standard locations with automatic dependency resolution, package tracking via a database, and simple updating capability. For example, Fedora, Red Hat Enterprise Linux, CentOS, SuSE, and OpenSuSE all use the RPM package system, in which source code is bundled with a build recipe in a "Source RPM" (SRPM), which can be built with a single command into a binary package (RPM). The RPMs can then be downloaded, have dependencies and conflicts resolved, and installed with a single command such as dnf. The fact that the SRPM can be built into an installable RPM through an automated process enables and simplifies automated build systems, mass rebuilds, and architecture-specific builds.


Executable Files

  • Executable code is usually stored in a multi-segment file format containing code, data, linking information (for shared object files/dynamically linked libraries), information on how the segments should be placed in memory, and so forth.
  • On a modern Linux system, this is usually the Executable and Linkable Format (ELF). Other executable format include COFF (UEFI, Unix/Older Linux/Windows) and its derivative PE (Windows). See the Executable and Linkable Format page for a list of tools that can be used to analyze ELF files.

Week 5 - Class III

Week 5 Deliverables

Week 6

Monday of Week 6 was the Thanksgiving Holiday (no Class I this week).

Week 6 - Class II

Week 7

Week 7 - Class I

Videos

Delayed due to technical issues:

  • Introduction to x86_64 and AArch64

Week 7 - Class II

Week 7 Deliverables

Week 8

Week 8 - Class I

Video

Reminder

Week 8 - Class II

  • Discussion and demo of x86_64 and AArch64 differences

Week 8 Deliverables

Week 9

Week 9 - Class I

Video

Week 9 - Class II

Week 10

Week 10 - Class I

  • No new videos - continue work on Lab 5

Week 10 - Class II

  • Quiz 2
  • Discussion

Week 11

Week 11 - Class I

  • Lab 6 / Project Stage 1

Videos


Week 11 - Class II

Week 11 Deliverables