{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lecture Notes: Introduction to Lua and Torch\n", "\n", "Understanding Lua/Torch code will be useful to follow the material presented in the course but you are free to experiment with any other tool that you prefer, especially if you already have experience with a different one.\n", "\n", "Why Lua?\n", "- Mainly because of Torch, a powerful library with lots of vector, matrix, and tensor operations.\n", "- Torch is heavily developed and maintained by Facebook AI Research, among many people from several universities and research groups.\n", "- Torch is being used by many research groups and companies around the world, and has a good community built around.\n", "- It usually supports all the basic primitives needed to implement state-of-the-art research.\n", "- The Lua Programming language syntax is simple, and the philosphy is very Javascript which you probably are already familiar with.\n", "- Lua was developed by a Computer Graphics Group in Brazil's PUC Rio University. It means moon in Portuguese.\n", "- Lua has a niche following as a scripting language for games.\n", "\n", "## Numbers and strings.\n", "In Lua you have available the 'string' and 'math' libraries providing basic functionalities. (Here is a link to the official Lua manual https://www.lua.org/manual/5.1/)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "-- Declare a string and and some numbers.\n", "str = 'visual recognition'\n", "x = 10\n", "y = 30\n", "\n", "-- Manipulating strings using the 'string' library.\n", "print(str) -- print str\n", "print(string.sub(str, 1, 6)) -- print a substring\n", "\n", "-- Manipulating numbers using the 'math' library.\n", "print(x) -- print the sum.\n", "print(math.log(x))\n", "print(math.sqrt(x))\n", "\n", "-- You can also print formatted output as in C.\n", "print(string.format('This is a string: %s, and this is a number: %.3f', str, math.sqrt(x + y)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Control structures (loops and conditional statements)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "-- For loop syntax.\n", "for i = 1, 10 do\n", " -- This is the same as string.format('iteration %d', i)\n", " print(('iteration %d'):format(i))\n", "end\n", "\n", "for i = 1, 10 do\n", " -- If statement syntax.\n", " if i % 2 == 0 then\n", " print(('Even number %d'):format(i))\n", " else\n", " print(('Odd number %d'):format(i))\n", " end\n", "end" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Variable scope\n", "By default in Lua, all variables are global, meaning you can access a variable value even if you declared such variable inside a loop or in a completely different file. This means that it is probably a good idea to declare most of your variables local unless you really want them to be global." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a = 'Hi, my name is A'\n", "local b = 'Hi, my name is B'\n", "\n", "if string.len(b) > 0 then\n", " c = 'Hi, my name is C'\n", " local d = 'Hi, my name is D'\n", "end\n", "\n", "print(a)\n", "print(b)\n", "print(c)\n", "print(d) -- This one will print nil." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In jupyter/ipython, cells are in different scopes so in the next cell we still have access to global variables a, and c but will not have access to b anymore." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(a) \n", "print(b) -- This one will print nil.\n", "print(c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conditional Assignments\n", "\n", "The following ways of initializing variables are also popular in Lua/Torch." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "-- (counter or 0) evaluates to 0 when counter is nil.\n", "for i = 1, 10 do\n", " counter = 1 + (counter or 0)\n", "end\n", "print(counter)\n", "\n", "-- The form \n", "-- var = (condition) and [value1] or [value2] \n", "-- is similar to the ternary conditional operator in C: \n", "-- var = (condition) ? [value1]: [value2];\n", "local passedNine = (counter > 9) and 'Bigger than 9' or 'Smaller than 9'\n", "print(passedNine)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tables\n", "Tables are the only data structure you will need in Lua, they can behave like arrays, lists, hashmaps, C-like structures.\n", "\n", "Tables as structures:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "-- We can initialize a table in this way.\n", "course = {}\n", "course.name = 'Computational Visual Recognition'\n", "course.school = 'University of Virginia'\n", "course.nStudents = 39\n", "course.year = 2016\n", "\n", "print(course) -- Print the table\n", "print(course.school) -- Print a table field\n", "print(course['school']) -- Another way to print a field." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "-- We can also simply do.\n", "course = {name = 'Computational Visual Recognition',\n", " school = 'University of Virginia',\n", " nStudents = 39, year = 2016}\n", "print(course)\n", "print(course.school)\n", "print(course['school']) -- Another way to print a field." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tables as arrays:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "-- We can also use tables as arrays.\n", "local myarray = {}\n", "for i = 1, 10 do\n", " myarray[i] = math.exp(i) -- Store the exp of each i.\n", "end\n", "print(myarray) -- Print the array-table\n", "print(myarray[1]) -- Print the first element (indices start at 1 in Lua).\n", "\n", "-- Caution: The # operator only works when using the table as an array or list\n", "-- This means when the table keys are contiguous integer values.\n", "print(#myarray) -- Prints the number of elements\n", "\n", "-- Traversing the array.\n", "for k,v in pairs(myarray) do\n", " print(string.format('index: %d, value %d', k, v))\n", "end" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tables as lists:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "local mylist1 = {'cat', 'dog', 'rabbit', 'monkey'}\n", "local mylist2 = {'frog', 'shark', 'donkey'}\n", "\n", "-- insert all elements of the second list in the first list.\n", "for k,v in pairs(mylist2) do\n", " table.insert(mylist1, v)\n", "end\n", "\n", "print(mylist1)\n", "print(#mylist1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tables as hashmaps:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "-- Count the number of repeats of each element\n", "local alist = {'do', 're', 'mi', 'la', 'fa', 'do', 're', 'mi', 'si', 're'}\n", "local counts = {}\n", "\n", "-- note that (counts[v] or 0) evalutes to 0 when counts[v] is nil.\n", "for k, v in pairs(alist) do\n", " counts[v] = 1 + (counts[v] or 0)\n", "end\n", "\n", "print(counts)\n", "-- The following line returns 0 because # is only defined for contiguous integer indices.\n", "-- print(#counts) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "-- This is how you define functions in lua.\n", "function sum(x, y)\n", " return x + y\n", "end\n", "print(sum(2,3))\n", "\n", "-- Functions can also be defined nameless or assigned as variables.\n", "local mul = function(x, y) return x * y end\n", "print(mul(2, 3))\n", "\n", "-- Function to add some fixed number to input.\n", "local some = 5\n", "function sumSome(x)\n", " -- notice how \"some\" was defined outside the function.\n", " -- you can only use local variables defined right outside the function.\n", " return some + x\n", "end\n", "print(sumSome(2))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(some) -- some was a local variable in a different cell so this will print nil.\n", "print(sumSome(2)) -- but sumSome is still available and still has access to variable some." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "-- Functions can also be attached to tables to simulate \"classes\".\n", "-- e.g. \n", "\n", "dog = {}\n", "dog.name = 'Rocky'\n", "function dog:bark()\n", " print('whoof, I am ' .. self.name .. '!')\n", "end\n", "\n", "dog:bark() -- same as dog.bark(dog)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## Torch Tensors\n", "Tensors are not natively part of Lua but part of the Torch Library. Tensors are for our purposes just generalizations of matrices where one can have more than two dimensions. There are no memory limits on Torch tensors, Lua tables have an upper limit on how much memory they can take.\n", "\n", "You can find a more detailed treatment of tensors in the Torch documentation:\n", "https://github.com/torch/torch7/blob/master/doc/tensor.md\n", "\n", "Here I include a matrix multiplication operation but you can consult other operations here: https://github.com/torch/torch7/blob/master/doc/maths.md " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "require 'torch' -- Usually you do not need to declare this explicitly.\n", "\n", "-- This creates a 5x5 matrix of float values.\n", "local a = torch.FloatTensor(5, 3)\n", "a:fill(3) -- fill all elements of the matrix with 3's.\n", "print(a) -- print the matrix on the console.\n", "\n", "-- This creates a 3x2 matrix of float avalues.\n", "local b = torch.FloatTensor(3, 2) \n", "b:fill(2)\n", "print(b)\n", "\n", "-- Multiply the two matrices and output the result.\n", "print(a * b) --- alternatively you can use torch.mm(a, b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Basic tensor indexing" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "-- create a matrix of size 5x5 filled with 8's.\n", "local a = torch.FloatTensor(5, 5):fill(8)\n", "\n", "-- change the element in position (3, 3) to 0.\n", "a[{3, 3}] = 0\n", "\n", "-- change the first row of the matrix to 2's.\n", "a[{{1}, {}}]:fill(2)\n", "\n", "-- change the last column of the matrix to 5's.\n", "a[{{}, {-1}}]:fill(5)\n", "\n", "-- change the first two columns to 1's.\n", "a[{{}, {1,2}}]:fill(1)\n", "\n", "print(a) -- print the resulting matrix." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tensor references\n", "Torch tensors are always references unless you use use the clone method. Sometimes you want to have two variables pointing to the same tensor, this is something used extensively in torch. But you have to use this carefully because you might inadvertently modify a tensor somewhere else in your code, or if you are running many threads on the same tensor." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "local a = torch.FloatTensor(1, 3):fill(3) -- create a 1x3 vector filled with 3's.\n", "local b = a -- a and b are the same.\n", "local c = a:clone() -- c is a copy of a.\n", "\n", "b[1][3] = 4 -- this will affect tensor a.\n", "\n", "print(a) -- a[{1, 3}] is changed.\n", "print(c) -- c is the original tensor a." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Finally here is a couple of urls that you might also find useful at this point:\n", "- Lua manual https://www.lua.org/manual/5.1/\n", "- Torch Wiki https://github.com/torch/torch7/wiki/Cheatsheet" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
If you find any errors or omissions in this material please contact me at vicente@cs.virginia.edu" ] } ], "metadata": { "kernelspec": { "display_name": "iTorch", "language": "lua", "name": "itorch" }, "language_info": { "name": "lua", "version": "20100" } }, "nbformat": 4, "nbformat_minor": 0 }