Skip to content

Introductory tutorial

dcoetzee edited this page Jan 26, 2012 · 4 revisions

Introductory tutorial

SEJITS is a toolkit for writing simple compilers for domain-specific languages embedded in Python. These compilers, called specializers, are typically written in Python and generate C++ just-in-time at runtime. SEJITS then compiles the C++ and executes it immediately.

Templates

SEJITS supplies two main mechanisms for implementing specializers. The first, templates, enable specializer writers to write C++ code containing "placeholders" or "holes" which are filled in at runtime:

for (int i=0; i < ${num_items}; i++) {
    arr[i] *= 2.0;
}

In this example, the loop bound is a constant determined by the Python application at runtime. By filling in the constant before the C++ is compiled, C++ compiler optimizations such as loop unrolling are enabled. In general, templates enable compiler optimizations, adapting to machine parameters, and allow choosing among implementations based on architecture.

Exercise

We're going to modify a template-based SEJITS specializer. Begin by connecting by SSH to:

  • Hostname: moonflare.com
  • Username: par-lab-all
  • Password: 2xyb3pex

Set up your user tutorial directory with "setup yourname". The specializer you're going to modify is in double.py and multiplies each entry of an input vector by 2. Go ahead and run it using "python double.py". The specializer will generate a C++ source file, compile it, and run it. Look under your "cache" subdirectory for the generated .cpp file, and examine it.

Now, we're going to modify the specializer. The double.py specializer uses a template stored in double_template.mako. Open double_template.mako in your favorite editor (if you're not sure, use "nano"). Try changing the template to multiply each entry of the vector by 3 instead of 2. Once you've made your change, run "python double.py" again to try it. Review the generated C++ code to see that it has changed.

Next, we're going to modify the template to allow the Python application to multiply by any scalar it wants. Replace the constant in double_template.mako by the placeholder "${scalar}". Next, edit double.py and follow these steps:

  • Add a parameter to double_using_template for specifying the scalar multiple to multiply by.
  • Pass the parameter correctly to mytemplate.render().
  • Update test_generated() to pass some constant value in to double_using_template() for the new argument.

Test your changes using "python double.py". This completes the template exercise.

Clone this wiki locally