SlideShare uma empresa Scribd logo
1 de 50
Baixar para ler offline
Using Language Oriented
 Programming to Execute
Computations on the GPU
   Robert Pickering, ALTI
About the Presenter
          • Using F# for about 6 years
          • Oldest F# user outside of Microsoft
          • Written a book about F#
              (now in its second edition)
          • Spend at least 2 years as a professional
            functional programmer
          • I have 3 cats


    Contact me:
    robert@strangelights.com
    http://strangelights.com/blog

2
ALTI
• Large French services company
• Consulting, engineering and
  training
• Believe in helping clients
  discover upcoming niches

• Already offer F# training and
  consulting
What is Language Oriented
            Programming ?
• Creating programs that are an abstract
  description of the a problem

• This description can then either be
  interpreted, compiled, or analyzed in another
  way
LOP & Combinators
• F# has two main approaches to Language
  Oriented Programming:
  – Reinterpreting the F# syntax though the
    quotations system
  – Using combinators create a new syntax

  … both approaches are very similar
What is a Combinator?


  A combinator is a higher-order function that
   uses only function application and earlier
 defined combinators to define a result from its
                  arguments.



Source: Wikipedia, http://en.wikipedia.org/wiki/Combinatory_Logic
Combinatory Logic in Computing

 In computer science, combinatory logic is used
  as a simplified model of computation, used in
 computability theory and proof theory. Despite
 its simplicity, combinatory logic captures many
         essential features of computation.


Source: Wikipedia, http://en.wikipedia.org/wiki/Combinatory_Logic
Combinator Library
       "A combinator library offers functions (the
combinators) that combine functions together to make
    bigger functions"[1]. These kinds of libraries are
    particularly useful for allowing domain-specific
 programming languages to be easily embedded into a
 general purpose language by defining a few primitive
             functions for the given domain.

Souce: Wikipedia http://en.wikipedia.org/wiki/Combinator_library


[1] “A History of Haskell” Hudak, Hughes, Peyton Jones, Wadler
History of Haskell: Combinator Libraries

  What is a combinator library? The reader will
   search in vain for a definition of this heavily
used term, but the key idea is this: a combinator
 library offers functions (the combinators) that
   combine functions together to make bigger
                     functions.
History of Haskell: Combinator Libraries

 What is a combinator library? The reader will
  search in vain for a definition of this heavily
used term, but the key idea is this: a combinator
 library offers functions (the combinators) that
   combine functions together to make bigger
                    functions.
History of Haskell: Combinator Libraries

    Another productive way to think of a
 combinator library is as a domain-specific
  language (DSL) for describing values of a
              particular type.
What is a Domain Specific Language?

A programming language tailored for a particular application
domain, which captures precisely the semantics of the
application domain -- no more, no less.
   A DSL allows one to develop software for a particular
   application domain quickly, and effectively, yielding
   programs that are easy to understand, reason about, and
   maintain.
                                                       Hudak
Combinators vs DSLs
• Combinartor libraries are a special case of DSLs
   – Sometimes called DSELs (Domain Specific Embed languages)


• DSELs have several advantages:
   ― Inherit non-domain-specific parts of the design.
   ― Inherit compilers and tools.
   ― Uniform “look and feel” across many DSLs
   ― DSLs integrated with full programming language, and with each other.


• DSELs one disadvantage:
   ― Constrained by host language syntax and type system
What Makes F# a Suitable for DSLs ?
• Union Types / Active Patterns
   – type Option<'a> = Some x | None


• Lambda functions
   – fun x -> x + 1


• Define and redefine operators
   – let (++) x = x + 1


• Define custom numeric literals
   – let x : Expression = 1.0N
Union Types – The Option Type
// The pre-defined option type
type Option<'a> =
    | Some of 'a
    | None

// constructing options
let someValue = Some 1
let noValue = None

// pattern matching over options
let convert value =
    match value with
    | Some x -> Printf.sprintf "Value: %i" x
    | None -> "No value"
Union Types - Trees
// a binary tree definition
type BinaryTree<'a> =
    | Node of BinaryTree<'a> * BinaryTree<'a>
    | Leaf of 'a


// walk the tree collection values
let rec collectValues acc tree =
    match tree with
    | Node(ltree, rtree) ->
        // recursively walk the left tree
        let acc = collectValues acc ltree
        // recursively walk the right tree
        collectValues acc rtree
    | Leaf value -> value :: acc
                    // add value to accumulator
Using the Tree
// define a tree
let tree =
    Node(
          Node(Leaf 1, Leaf 2),
          Node(Leaf 3, Leaf 4))


// recover all values from the leaves
let values = collectValues [] tree
Union Types
Union types play a key role in language oriented
 programming, as they allow the user to easily
 define a tree that will form the abstract syntax
               tree of the language
Active Patterns
// definition of the active pattern
let (|Bool|Int|Float|String|) input =
    // attempt to parse a bool
    let sucess, res = Boolean.TryParse input
    if sucess then Bool(res)
    else
        // attempt to parse an int
        let sucess, res = Int32.TryParse input
        if sucess then Int(res)
        else
            // attempt to parse a float (Double)
            let sucess, res = Double.TryParse input
            if sucess then Float(res)
            else String(input)
Active Patterns
// function to print the results by pattern
// matching over the active pattern
let printInputWithType input =
    match input with
    | Bool b -> printfn "Boolean: %b" b
    | Int i -> printfn "Integer: %i" i
    | Float f -> printfn "Floating point: %f" f
    | String s -> printfn "String: %s" s

// print the results
printInputWithType "true"
printInputWithType "12"
Active Patterns
    Active patterns play a supporting role in
  language oriented programming in F#. They
allow the programmer to create abstractions of
complex operations on the abstract syntax tree
Lambda Functions


fun () ->
       lovin'()
Lambda Functions
 Lambda functions are important for language
oriented programming. They allow the users of
  the language to embed actions within other
              language elements
Custom Operators

let (++) x = x + 1
Custom Operators
   Custom operators play a supporting role in
language oriented programming. They allow the
   language designer to have a more flexible
                    syntax.
Custom Numeric Literals
type Expression =
    | Constant of int

module NumericLiteralN =
    let FromZero() = Constant 0
    let FromOne() = Constant 1
    let FromInt32 = Constant

let expr = 1N
Custom Numeric Literals
  Numeric literals play a supporting role in
language oriented programming. They allow
numeric literals be treated in a more natural
      within an embedded language
The Anatomy of a DSL
type Expression =                                    Syntax Tree
    | Add of Expression * Expression
    | Subtract of Expression * Expression
    | Multiply of Expression * Expression
    | Constant of int                                Combinators
    | Parameter of string
    with
         static member (+) (x, y) = Add(x, y)
         static member (-) (x, y) = Subtract(x, y)
         static member (*) (x, y) = Multiply(x, y)

module NumericLiteralN =
    let FromZero() = Constant 0
    let FromOne() = Constant 1
    let FromInt32 = Constant

let param = Parameter
The Anatomy of a DSL

let expr = (1N + 2N) * (5N - 2N)




val expr : Expression =
  Multiply (Add (Constant 1,Constant 2),
            Subtract (Constant 5,Constant 2))
The Anatomy of a DSL
• Expressions now have an abstract tree like
  representation:
   ― Multiply
      ― Add
           ― Constant 1
           ― Constant 2
      ― Subtract
           ― Constant 5
           ― Constant 2



• This can then be evaluated
• Or we can preform more advanced analysis
The Anatomy of a DSL
let evaluateExpression parameters =
    let rec innerEval tree =
        match tree with
        | Multiply (x, y) -> innerEval x * innerEval y
        | Add (x, y) -> innerEval x + innerEval y
        | Subtract (x, y) -> innerEval x - innerEval y
        | Constant value -> value
        | Parameter key -> Map.find key parameters
    innerEval


let expr = (1N + 2N) * (5N - 2N)

evaluateExpression Map.empty expr
The Anatomy of a DSL
The Anatomy of a DSL
let rec simplifyExpression exp =
    let simpIfPoss op exp1 exp2 =
        let exp' = op (simplifyExpression exp1,
                       simplifyExpression exp2)
        if exp' = exp then exp' else simplifyExpression exp'
    match exp with
    | Multiply(Constant 0, Constant _) -> Constant 0
    | Multiply(Constant _, Constant 0) -> Constant 0
    | Multiply(Constant n1, Constant n2) -> Constant (n1 * n2)
    | Add(Constant n1, Constant n2) -> Constant (n1 + n2)
    | Subtract(Constant n1, Constant n2) -> Constant (n1 - n2)
    | Multiply(exp1, exp2) -> simpIfPoss Multiply exp1 exp2
    | Add(exp1, exp2) -> simpIfPoss Add exp1 exp2
    | Subtract(exp1, exp2) -> simpIfPoss Add exp1 exp2
    | Constant _ | Parameter _ -> exp
The Anatomy of a DSL
Quotations

let quotation   = <@ (1 + 2) * (5 - 2) @>



val quotation : Quotations.Expr<int> =
  Call (None, Int32 op_Multiply[Int32,Int32,Int32](Int32, Int32),
      [Call (None, Int32 op_Addition[Int32,Int32,Int32](Int32, Int32),
             [Value (1), Value (2)]),
       Call (None, Int32 op_Subtraction[Int32,Int32,Int32](Int32, Int32),
             [Value (5), Value (2)])])
Quotations
• Allow you to grab a tree structure that
  represents a piece of F# code

• This tree structure can then be:
  – Interpreted
  – Compiled
  – Converted to instructions understood by another
    system or runtime
Microsoft Accelerator
• A project from MRS, now available on
  Microsoft Connect [1]

• Automatically parallelize code for execution
  on the GPU or x64 multicore

• Implemented as an unmanaged library with
  .NET wrapper
[1] http://connect.microsoft.com/acceleratorv2
Microsoft Accelerator
• Based on “Parallel Array”

• You define a set of operations to process the
  content of the array

• The Accelerator runtime will then process the
  operations in parallel
Microsoft Accelerator

                         User Program – Define Operations




                                   Accelerator




Input data                     Accelerated Program                  Input data




             DX9Target                                      X64Target
Microsoft Accelerator – Code!

let nums = [| 6; 1; 5; 5; 3 |]
let input = new FloatParallelArray(nums);
let sum = ParallelArrays.Shift(input, 1) + input +
                    ParallelArrays.Shift(input, -1);
let output = sum / 3.0f;



let target = new DX9Target();
let res = target.ToArray1D(output);
Game of Life
Game of Life

• Green - When an existing cell (green in the middle) has three
  or two neighbours it survives to the next round

• Red - When an existing cell has less than two neighbours it
  dies, because it is lonely (first red case), when it has more
  than three neighbours it dies of overcrowding (second red
  case)

• Blue - Finally, a new cell is born in an empty grid location if
  there are exactly three neighbours .
The implementation
              1        1



1                                       1


    initial                rotation 1



                        Sum of all
etc. ...                neighbours
Game of Life




CPU           GPU
Game of Life
/// Evaluate next generation of the life game state

let nextGeneration (grid: Matrix<float32>) =

 // Shift in each direction, to count the neighbours
 let sum = shiftAndSum grid offsets

 // Check to see if we're born or remain alive
 (sum =. threeAlive) ||. ((sum =. twoAlive) &&. grid)




 CPU                               GPU
Game of Life
/// Evaluate next generation of the life game state
[<ReflectedDefinition>]
let nextGeneration (grid: Matrix<float32>) =

 // Shift in each direction, to count the neighbours
 let sum = shiftAndSum grid offsets

 // Check to see if we're born or remain alive
 (sum =. threeAlive) ||. ((sum =. twoAlive) &&. grid)




 CPU                               GPU
Game of life in F# with Microsoft Accelerator

DEMO
Thanks!
• A big thanks to Tomáš Petříček!



• More info on his blog:
  – http://tomasp.net/articles/accelerator-intro.aspx
Books
Shameless Plug!
• Robert Pickering’s Beginning F# Workshop:
  – Thursday 9th Sept – 10th September 2010


http://skillsmatter.com/course/open-source-
dot-net/robert-pickerings-beginning-f-workshop

Mais conteúdo relacionado

Mais procurados

Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular ExpressionsPython Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular Expressions
Ranel Padon
 
02. chapter 3 lexical analysis
02. chapter 3   lexical analysis02. chapter 3   lexical analysis
02. chapter 3 lexical analysis
raosir123
 
Chapter Two(1)
Chapter Two(1)Chapter Two(1)
Chapter Two(1)
bolovv
 
Babar: Knowledge Recognition, Extraction and Representation
Babar: Knowledge Recognition, Extraction and RepresentationBabar: Knowledge Recognition, Extraction and Representation
Babar: Knowledge Recognition, Extraction and Representation
Pierre de Lacaze
 
Dsm as theory building
Dsm as theory buildingDsm as theory building
Dsm as theory building
ClarkTony
 

Mais procurados (20)

Minimizing DFA
Minimizing DFAMinimizing DFA
Minimizing DFA
 
Logic Programming and Prolog
Logic Programming and PrologLogic Programming and Prolog
Logic Programming and Prolog
 
Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular ExpressionsPython Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular Expressions
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Datatype
DatatypeDatatype
Datatype
 
Python data handling
Python data handlingPython data handling
Python data handling
 
02. chapter 3 lexical analysis
02. chapter 3   lexical analysis02. chapter 3   lexical analysis
02. chapter 3 lexical analysis
 
Chapter Two(1)
Chapter Two(1)Chapter Two(1)
Chapter Two(1)
 
LISP: Introduction to lisp
LISP: Introduction to lispLISP: Introduction to lisp
LISP: Introduction to lisp
 
Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
 
Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic Services
 
Lisp and scheme i
Lisp and scheme iLisp and scheme i
Lisp and scheme i
 
Babar: Knowledge Recognition, Extraction and Representation
Babar: Knowledge Recognition, Extraction and RepresentationBabar: Knowledge Recognition, Extraction and Representation
Babar: Knowledge Recognition, Extraction and Representation
 
2_2Specification of Tokens.ppt
2_2Specification of Tokens.ppt2_2Specification of Tokens.ppt
2_2Specification of Tokens.ppt
 
Chapter 10 data handling
Chapter 10 data handlingChapter 10 data handling
Chapter 10 data handling
 
INTRODUCTION TO LISP
INTRODUCTION TO LISPINTRODUCTION TO LISP
INTRODUCTION TO LISP
 
Dsm as theory building
Dsm as theory buildingDsm as theory building
Dsm as theory building
 

Destaque (8)

Five Steps to Kanban
Five Steps to KanbanFive Steps to Kanban
Five Steps to Kanban
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: Gradle
 
UK G-Cloud: The First Instantiation of True Cloud?
UK G-Cloud: The First Instantiation of True Cloud?UK G-Cloud: The First Instantiation of True Cloud?
UK G-Cloud: The First Instantiation of True Cloud?
 
Sug Jan 19
Sug Jan 19Sug Jan 19
Sug Jan 19
 
Oc Cloud Obscurity
Oc Cloud ObscurityOc Cloud Obscurity
Oc Cloud Obscurity
 
Narrative Acceptance Tests River Glide Antony Marcano
Narrative Acceptance Tests River Glide Antony MarcanoNarrative Acceptance Tests River Glide Antony Marcano
Narrative Acceptance Tests River Glide Antony Marcano
 
Cqrs Ldnug 200100304
Cqrs   Ldnug 200100304Cqrs   Ldnug 200100304
Cqrs Ldnug 200100304
 
5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence
 

Semelhante a Using Language Oriented Programming to Execute Computations on the GPU

Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#
Robert Pickering
 
Programming Languages - Functional Programming Paper
Programming Languages - Functional Programming PaperProgramming Languages - Functional Programming Paper
Programming Languages - Functional Programming Paper
Shreya Chakrabarti
 
15 functional programming
15 functional programming15 functional programming
15 functional programming
jigeno
 
15 functional programming
15 functional programming15 functional programming
15 functional programming
jigeno
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Declare Your Language (at DLS)
Declare Your Language (at DLS)Declare Your Language (at DLS)
Declare Your Language (at DLS)
Eelco Visser
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
Sergio Gil
 

Semelhante a Using Language Oriented Programming to Execute Computations on the GPU (20)

Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#
 
Programming Languages - Functional Programming Paper
Programming Languages - Functional Programming PaperProgramming Languages - Functional Programming Paper
Programming Languages - Functional Programming Paper
 
15 functional programming
15 functional programming15 functional programming
15 functional programming
 
15 functional programming
15 functional programming15 functional programming
15 functional programming
 
CPPDS Slide.pdf
CPPDS Slide.pdfCPPDS Slide.pdf
CPPDS Slide.pdf
 
Introduction to Functional Languages
Introduction to Functional LanguagesIntroduction to Functional Languages
Introduction to Functional Languages
 
Declare Your Language: Syntax Definition
Declare Your Language: Syntax DefinitionDeclare Your Language: Syntax Definition
Declare Your Language: Syntax Definition
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Unit1.ppt
Unit1.pptUnit1.ppt
Unit1.ppt
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
Declare Your Language (at DLS)
Declare Your Language (at DLS)Declare Your Language (at DLS)
Declare Your Language (at DLS)
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
 
Tools for reading papers
Tools for reading papersTools for reading papers
Tools for reading papers
 
Intro f# functional_programming
Intro f# functional_programmingIntro f# functional_programming
Intro f# functional_programming
 
Syntax
SyntaxSyntax
Syntax
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
 

Mais de Skills Matter

Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheim
Skills Matter
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-dive
Skills Matter
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_t
Skills Matter
 

Mais de Skills Matter (20)

Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
 
Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheim
 
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
 
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlCukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberl
 
Cukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsCukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.js
 
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
 
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
 
Progressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldProgressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source world
 
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
 
Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#
 
A poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingA poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testing
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-dive
 
Serendipity-neo4j
Serendipity-neo4jSerendipity-neo4j
Serendipity-neo4j
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelism
 
Plug 20110217
Plug   20110217Plug   20110217
Plug 20110217
 
Lug presentation
Lug presentationLug presentation
Lug presentation
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_t
 
Plug saiku
Plug   saikuPlug   saiku
Plug saiku
 
Huguk lily
Huguk lilyHuguk lily
Huguk lily
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

Using Language Oriented Programming to Execute Computations on the GPU

  • 1. Using Language Oriented Programming to Execute Computations on the GPU Robert Pickering, ALTI
  • 2. About the Presenter • Using F# for about 6 years • Oldest F# user outside of Microsoft • Written a book about F# (now in its second edition) • Spend at least 2 years as a professional functional programmer • I have 3 cats Contact me: robert@strangelights.com http://strangelights.com/blog 2
  • 3. ALTI • Large French services company • Consulting, engineering and training • Believe in helping clients discover upcoming niches • Already offer F# training and consulting
  • 4. What is Language Oriented Programming ? • Creating programs that are an abstract description of the a problem • This description can then either be interpreted, compiled, or analyzed in another way
  • 5. LOP & Combinators • F# has two main approaches to Language Oriented Programming: – Reinterpreting the F# syntax though the quotations system – Using combinators create a new syntax … both approaches are very similar
  • 6. What is a Combinator? A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments. Source: Wikipedia, http://en.wikipedia.org/wiki/Combinatory_Logic
  • 7. Combinatory Logic in Computing In computer science, combinatory logic is used as a simplified model of computation, used in computability theory and proof theory. Despite its simplicity, combinatory logic captures many essential features of computation. Source: Wikipedia, http://en.wikipedia.org/wiki/Combinatory_Logic
  • 8. Combinator Library "A combinator library offers functions (the combinators) that combine functions together to make bigger functions"[1]. These kinds of libraries are particularly useful for allowing domain-specific programming languages to be easily embedded into a general purpose language by defining a few primitive functions for the given domain. Souce: Wikipedia http://en.wikipedia.org/wiki/Combinator_library [1] “A History of Haskell” Hudak, Hughes, Peyton Jones, Wadler
  • 9. History of Haskell: Combinator Libraries What is a combinator library? The reader will search in vain for a definition of this heavily used term, but the key idea is this: a combinator library offers functions (the combinators) that combine functions together to make bigger functions.
  • 10. History of Haskell: Combinator Libraries What is a combinator library? The reader will search in vain for a definition of this heavily used term, but the key idea is this: a combinator library offers functions (the combinators) that combine functions together to make bigger functions.
  • 11. History of Haskell: Combinator Libraries Another productive way to think of a combinator library is as a domain-specific language (DSL) for describing values of a particular type.
  • 12. What is a Domain Specific Language? A programming language tailored for a particular application domain, which captures precisely the semantics of the application domain -- no more, no less. A DSL allows one to develop software for a particular application domain quickly, and effectively, yielding programs that are easy to understand, reason about, and maintain. Hudak
  • 13. Combinators vs DSLs • Combinartor libraries are a special case of DSLs – Sometimes called DSELs (Domain Specific Embed languages) • DSELs have several advantages: ― Inherit non-domain-specific parts of the design. ― Inherit compilers and tools. ― Uniform “look and feel” across many DSLs ― DSLs integrated with full programming language, and with each other. • DSELs one disadvantage: ― Constrained by host language syntax and type system
  • 14. What Makes F# a Suitable for DSLs ? • Union Types / Active Patterns – type Option<'a> = Some x | None • Lambda functions – fun x -> x + 1 • Define and redefine operators – let (++) x = x + 1 • Define custom numeric literals – let x : Expression = 1.0N
  • 15. Union Types – The Option Type // The pre-defined option type type Option<'a> = | Some of 'a | None // constructing options let someValue = Some 1 let noValue = None // pattern matching over options let convert value = match value with | Some x -> Printf.sprintf "Value: %i" x | None -> "No value"
  • 16. Union Types - Trees // a binary tree definition type BinaryTree<'a> = | Node of BinaryTree<'a> * BinaryTree<'a> | Leaf of 'a // walk the tree collection values let rec collectValues acc tree = match tree with | Node(ltree, rtree) -> // recursively walk the left tree let acc = collectValues acc ltree // recursively walk the right tree collectValues acc rtree | Leaf value -> value :: acc // add value to accumulator
  • 17. Using the Tree // define a tree let tree = Node( Node(Leaf 1, Leaf 2), Node(Leaf 3, Leaf 4)) // recover all values from the leaves let values = collectValues [] tree
  • 18. Union Types Union types play a key role in language oriented programming, as they allow the user to easily define a tree that will form the abstract syntax tree of the language
  • 19. Active Patterns // definition of the active pattern let (|Bool|Int|Float|String|) input = // attempt to parse a bool let sucess, res = Boolean.TryParse input if sucess then Bool(res) else // attempt to parse an int let sucess, res = Int32.TryParse input if sucess then Int(res) else // attempt to parse a float (Double) let sucess, res = Double.TryParse input if sucess then Float(res) else String(input)
  • 20. Active Patterns // function to print the results by pattern // matching over the active pattern let printInputWithType input = match input with | Bool b -> printfn "Boolean: %b" b | Int i -> printfn "Integer: %i" i | Float f -> printfn "Floating point: %f" f | String s -> printfn "String: %s" s // print the results printInputWithType "true" printInputWithType "12"
  • 21. Active Patterns Active patterns play a supporting role in language oriented programming in F#. They allow the programmer to create abstractions of complex operations on the abstract syntax tree
  • 22. Lambda Functions fun () -> lovin'()
  • 23. Lambda Functions Lambda functions are important for language oriented programming. They allow the users of the language to embed actions within other language elements
  • 25. Custom Operators Custom operators play a supporting role in language oriented programming. They allow the language designer to have a more flexible syntax.
  • 26. Custom Numeric Literals type Expression = | Constant of int module NumericLiteralN = let FromZero() = Constant 0 let FromOne() = Constant 1 let FromInt32 = Constant let expr = 1N
  • 27. Custom Numeric Literals Numeric literals play a supporting role in language oriented programming. They allow numeric literals be treated in a more natural within an embedded language
  • 28. The Anatomy of a DSL type Expression = Syntax Tree | Add of Expression * Expression | Subtract of Expression * Expression | Multiply of Expression * Expression | Constant of int Combinators | Parameter of string with static member (+) (x, y) = Add(x, y) static member (-) (x, y) = Subtract(x, y) static member (*) (x, y) = Multiply(x, y) module NumericLiteralN = let FromZero() = Constant 0 let FromOne() = Constant 1 let FromInt32 = Constant let param = Parameter
  • 29. The Anatomy of a DSL let expr = (1N + 2N) * (5N - 2N) val expr : Expression = Multiply (Add (Constant 1,Constant 2), Subtract (Constant 5,Constant 2))
  • 30. The Anatomy of a DSL • Expressions now have an abstract tree like representation: ― Multiply ― Add ― Constant 1 ― Constant 2 ― Subtract ― Constant 5 ― Constant 2 • This can then be evaluated • Or we can preform more advanced analysis
  • 31. The Anatomy of a DSL let evaluateExpression parameters = let rec innerEval tree = match tree with | Multiply (x, y) -> innerEval x * innerEval y | Add (x, y) -> innerEval x + innerEval y | Subtract (x, y) -> innerEval x - innerEval y | Constant value -> value | Parameter key -> Map.find key parameters innerEval let expr = (1N + 2N) * (5N - 2N) evaluateExpression Map.empty expr
  • 32. The Anatomy of a DSL
  • 33. The Anatomy of a DSL let rec simplifyExpression exp = let simpIfPoss op exp1 exp2 = let exp' = op (simplifyExpression exp1, simplifyExpression exp2) if exp' = exp then exp' else simplifyExpression exp' match exp with | Multiply(Constant 0, Constant _) -> Constant 0 | Multiply(Constant _, Constant 0) -> Constant 0 | Multiply(Constant n1, Constant n2) -> Constant (n1 * n2) | Add(Constant n1, Constant n2) -> Constant (n1 + n2) | Subtract(Constant n1, Constant n2) -> Constant (n1 - n2) | Multiply(exp1, exp2) -> simpIfPoss Multiply exp1 exp2 | Add(exp1, exp2) -> simpIfPoss Add exp1 exp2 | Subtract(exp1, exp2) -> simpIfPoss Add exp1 exp2 | Constant _ | Parameter _ -> exp
  • 34. The Anatomy of a DSL
  • 35. Quotations let quotation = <@ (1 + 2) * (5 - 2) @> val quotation : Quotations.Expr<int> = Call (None, Int32 op_Multiply[Int32,Int32,Int32](Int32, Int32), [Call (None, Int32 op_Addition[Int32,Int32,Int32](Int32, Int32), [Value (1), Value (2)]), Call (None, Int32 op_Subtraction[Int32,Int32,Int32](Int32, Int32), [Value (5), Value (2)])])
  • 36. Quotations • Allow you to grab a tree structure that represents a piece of F# code • This tree structure can then be: – Interpreted – Compiled – Converted to instructions understood by another system or runtime
  • 37. Microsoft Accelerator • A project from MRS, now available on Microsoft Connect [1] • Automatically parallelize code for execution on the GPU or x64 multicore • Implemented as an unmanaged library with .NET wrapper [1] http://connect.microsoft.com/acceleratorv2
  • 38. Microsoft Accelerator • Based on “Parallel Array” • You define a set of operations to process the content of the array • The Accelerator runtime will then process the operations in parallel
  • 39. Microsoft Accelerator User Program – Define Operations Accelerator Input data Accelerated Program Input data DX9Target X64Target
  • 40. Microsoft Accelerator – Code! let nums = [| 6; 1; 5; 5; 3 |] let input = new FloatParallelArray(nums); let sum = ParallelArrays.Shift(input, 1) + input + ParallelArrays.Shift(input, -1); let output = sum / 3.0f; let target = new DX9Target(); let res = target.ToArray1D(output);
  • 42. Game of Life • Green - When an existing cell (green in the middle) has three or two neighbours it survives to the next round • Red - When an existing cell has less than two neighbours it dies, because it is lonely (first red case), when it has more than three neighbours it dies of overcrowding (second red case) • Blue - Finally, a new cell is born in an empty grid location if there are exactly three neighbours .
  • 43. The implementation 1 1 1 1 initial rotation 1 Sum of all etc. ... neighbours
  • 45. Game of Life /// Evaluate next generation of the life game state let nextGeneration (grid: Matrix<float32>) = // Shift in each direction, to count the neighbours let sum = shiftAndSum grid offsets // Check to see if we're born or remain alive (sum =. threeAlive) ||. ((sum =. twoAlive) &&. grid) CPU GPU
  • 46. Game of Life /// Evaluate next generation of the life game state [<ReflectedDefinition>] let nextGeneration (grid: Matrix<float32>) = // Shift in each direction, to count the neighbours let sum = shiftAndSum grid offsets // Check to see if we're born or remain alive (sum =. threeAlive) ||. ((sum =. twoAlive) &&. grid) CPU GPU
  • 47. Game of life in F# with Microsoft Accelerator DEMO
  • 48. Thanks! • A big thanks to Tomáš Petříček! • More info on his blog: – http://tomasp.net/articles/accelerator-intro.aspx
  • 49. Books
  • 50. Shameless Plug! • Robert Pickering’s Beginning F# Workshop: – Thursday 9th Sept – 10th September 2010 http://skillsmatter.com/course/open-source- dot-net/robert-pickerings-beginning-f-workshop