ProgramOptimize.swift 7.8 KB
Newer Older
L
liuruilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License. */
L
liuruilong 已提交
14 15 16 17

import Foundation

precedencegroup ChainNode {
L
liuruilong 已提交
18 19
  associativity: left
  higherThan: MultiplicationPrecedence
L
liuruilong 已提交
20 21 22 23 24
}

infix operator --> : ChainNode

class Node {
L
liuruilong 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
  var inputs: [Node] = []
  var outputs: [Node] = []
  var type: String
  var opDesc: OpDesc?
  init(inOpDesc: OpDesc) {
    type = inOpDesc.type
    opDesc = inOpDesc
  }
  
  init(inType: String) {
    type = inType
  }
  
  subscript(index: Int) -> [Node] {
    var nodes: [Node] = []
    getNodesWithLocation(index: index, nowIndex: 0, nodes: &nodes)
    return nodes
  }
  
  func getNodesWithLocation(index: Int, nowIndex: Int, nodes: inout [Node]) {
    if index == nowIndex {
      nodes.append(self)
L
liuruilong 已提交
47 48
    }
    
L
liuruilong 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    for output in outputs {
      output.getNodesWithLocation(index: index, nowIndex: nowIndex + 1, nodes: &nodes)
    }
  }
  
  static func -->(lNode: Node, rNode: Node) -> Node {
    lNode.outputs.append(rNode)
    rNode.inputs.append(lNode)
    return rNode
  }
  
  func depth(begin: UInt = 1) -> UInt {
    var beginMax: UInt = 1
    for output in outputs {
      let subDepth = output.depth(begin: begin + 1)
      beginMax = max(begin, subDepth)
    }
    beginMax = max(begin, beginMax)
    return beginMax
  }
  
  func to(depth: UInt) -> Node {
    let beginNode = Node.init(inType: type)
    to(depth: depth - 1, withNode: beginNode)
    return beginNode
  }
  
  func folderWith(fusion: Fusion.Type, removedNodes: inout [Node]) {
    let fusionNode = fusion.fusionNode()
    let change = fusion.change()
    let inOutputs = outputs
    outputs.removeAll()
    opDesc?.outputs.removeAll()
    for i in 0..<inOutputs.count {
      inOutputs[i].folderWith(beginNode: self, matchNode: fusionNode.outputs[i], change: change, removedNodes: &removedNodes)
    }
    opDesc?.type = fusion.fusionType()
    type = fusion.fusionType()
  }
  
  private func folderWith(beginNode: Node, matchNode: Node, change: [String : [(from: String, to: String)]], removedNodes: inout [Node]) {
    guard let inOpdesc = opDesc else {
      fatalError()
L
liuruilong 已提交
92 93
    }
    
L
liuruilong 已提交
94 95 96
    for attr in inOpdesc.attrs {
      beginNode.opDesc?.attrs[attr.key] = attr.value
      //            print(beginNode.opDesc?.attrs)
L
liuruilong 已提交
97 98
    }
    
L
liuruilong 已提交
99 100 101 102 103 104 105 106
    for paraInput in inOpdesc.paraInputs {
      if let inChanges = change[type] {
        for keyChange in inChanges {
          if keyChange.from == paraInput.key {
            beginNode.opDesc?.paraInputs[keyChange.to] = paraInput.value
          } else {
            beginNode.opDesc?.paraInputs[paraInput.key] = paraInput.value
          }
L
liuruilong 已提交
107
        }
L
liuruilong 已提交
108 109 110
      } else {
        beginNode.opDesc?.paraInputs[paraInput.key] = paraInput.value
      }
L
liuruilong 已提交
111 112
    }
    
L
liuruilong 已提交
113 114 115 116
    if matchNode.outputs.count == 0 {
      beginNode.outputs.append(contentsOf: outputs)
      beginNode.opDesc?.outputs = inOpdesc.outputs
      
L
liuruilong 已提交
117
    }
L
liuruilong 已提交
118
    removedNodes.append(self)
L
liuruilong 已提交
119
    
L
liuruilong 已提交
120 121
    for i in 0..<matchNode.outputs.count {
      outputs[i].folderWith(beginNode: beginNode, matchNode: matchNode.outputs[i], change: change, removedNodes: &removedNodes)
L
liuruilong 已提交
122 123
    }
    
L
liuruilong 已提交
124 125 126 127 128
  }
  
  private func to(depth: UInt, withNode: Node) {
    if depth < 1 {
      return
L
liuruilong 已提交
129 130
    }
    
L
liuruilong 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    for output in outputs {
      let node = Node.init(inType: output.type)
      withNode.outputs.append(node)
      output.to(depth: depth - 1, withNode: node)
    }
  }
  
  func relationship() -> [String : Node]{
    var map: [String : Node] = [:]
    relationship(map: &map)
    return map
  }
  
  private func relationship(map: inout [String : Node]) {
    guard let inOpDesc = opDesc else {
      return
L
liuruilong 已提交
147 148
    }
    
L
liuruilong 已提交
149 150 151 152 153
    for output in inOpDesc.outputs {
      for outputKey in output.value {
        map[outputKey] = self
      }
    }
L
liuruilong 已提交
154
    
L
liuruilong 已提交
155 156 157 158 159
    for output in outputs {
      output.relationship(map: &map)
    }
  }
  
L
liuruilong 已提交
160 161 162
}

extension Node: Equatable {
L
liuruilong 已提交
163 164 165
  static func == (lhs: Node, rhs: Node) -> Bool {
    if lhs.outputs.count != rhs.outputs.count {
      return false
L
liuruilong 已提交
166 167
    }
    
L
liuruilong 已提交
168 169 170 171 172 173 174 175 176 177 178 179
    if lhs.type != rhs.type {
      return false
    }
    
    for i in 0..<lhs.outputs.count {
      if lhs.outputs[i] != rhs.outputs[i] {
        return false
      }
    }
    return true
  }
  
L
liuruilong 已提交
180 181 182
}

class ProgramOptimize<P: PrecisionType> {
L
liuruilong 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  // register fusion
  let fusionOps: [Fusion.Type] = [ConvAddBatchNormReluOp<P>.self,
                                  ConvAddPreluOp<P>.self,
                                  ConvAddOp<P>.self,
                                  ConvBNReluOp<P>.self,
                                  DwConvBNReluOp<P>.self
  ]
  
  func optimize(originProgramDesc: ProgramDesc) -> ProgramDesc {
    
    guard originProgramDesc.blocks.count == 1 else {
      fatalError(" not support yet")
    }
    
    var mapForNodeChain: [String : Node] = [:]
    var nodes: [Node] = []
    var typeMapNodes: [String : [(node: Node, output: [String : Node])]] = [:]
    let block = originProgramDesc.blocks[0]
    for opDesc in block.ops {
      guard let opInputKeys = opInfos[opDesc.type]?.inputs, let outputKeys = opInfos[opDesc.type]?.outputs else {
        fatalError()
      }
      
      let node = Node.init(inOpDesc: opDesc)
      for inputKey in opInputKeys {
        if let inputs = opDesc.inputs[inputKey] {
          for input in inputs {
            if let inputNode = mapForNodeChain[input] {
              _ = inputNode --> node
            }
          }
L
liuruilong 已提交
214
        }
L
liuruilong 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
      }
      
      for outputKey in outputKeys {
        if let outputs = opDesc.outputs[outputKey] {
          for output in outputs {
            mapForNodeChain[output] = node
          }
        }
      }
      
      nodes.append(node)
      
      if var inNodes = typeMapNodes[opDesc.type] {
        inNodes.append((node, mapForNodeChain))
        typeMapNodes[opDesc.type] = inNodes
      } else {
        typeMapNodes[opDesc.type] = [(node, mapForNodeChain)]
      }
    }
    
    for fusion in fusionOps {
      let fusionNode = fusion.fusionNode()
      let depth = fusionNode.depth()
      if let toMatchNodes = typeMapNodes[fusionNode.type] {
        for node in toMatchNodes {
          
          let toNode = node.node.to(depth: depth)
          if toNode == fusionNode {   // match
            var canFolder = true
            let relationshipMap = toNode.relationship()
            
            for toCheck in fusion.needCheck() {
              //              let nodes = toCheck
              let checkNodes = toNode[toCheck.0]
              
              for checkNode in checkNodes {
                let inputToChecks = checkNode.opDesc?.inputs[toCheck.1] ?? []
                for inputToCheck in inputToChecks {
                  if node.output[inputToCheck] == nil {
                    if relationshipMap[inputToCheck] == nil {
                      canFolder = false
L
liuruilong 已提交
256
                    }
L
liuruilong 已提交
257
                  }
L
liuruilong 已提交
258
                }
L
liuruilong 已提交
259
              }
L
liuruilong 已提交
260 261
            }
            
L
liuruilong 已提交
262 263
            if !canFolder {
              continue
L
liuruilong 已提交
264
            }
L
liuruilong 已提交
265 266 267 268 269 270 271
            
            var removeNodes: [Node] = []
            node.node.folderWith(fusion: fusion, removedNodes: &removeNodes)
            for removeNode in removeNodes {
              nodes.remove(element: removeNode)
            }
          }
L
liuruilong 已提交
272
        }
L
liuruilong 已提交
273
      }
L
liuruilong 已提交
274
    }
L
liuruilong 已提交
275 276 277 278 279 280 281 282 283 284 285
    
    var ops: [OpDesc] = []
    for node in nodes {
      ops.append(node.opDesc!)
    }
    
    var newProgramDesc = ProgramDesc.init()
    let newBlock = BlockDesc.init(inVars: block.vars, inOps: ops)
    newProgramDesc.blocks.append(newBlock)
    return newProgramDesc
  }
L
liuruilong 已提交
286
}