text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as Motorcycle from '@motorcycle/run' import * as assert from 'assert' import * as most from 'most' import { div, h2, h3, h4, input, makeDomComponent } from '../../src' import { createRenderTarget } from '../helpers/createRenderTarget' describe('DOMSource.events()', function() { it('should catch a basic click interaction Observable', function(done) { function app() { return { view$: most.of(h3('.myelementclass', 'Foobar')), } } const { sources, dispose } = Motorcycle.run<any, any>(app, (sinks: any) => ({ dom: makeDomComponent(createRenderTarget())(sinks).dom, })) sources.dom.select('.myelementclass').events('click').observe((ev: Event) => { assert.strictEqual(ev.type, 'click') assert.strictEqual((ev.target as HTMLHeadElement).textContent, 'Foobar') dispose() done() }) // Make assertions sources.dom.select(':root').elements().skip(1).take(1).observe(function([root]: Array<HTMLElement>) { const myElement: any = root.querySelector('.myelementclass') assert.notStrictEqual(myElement, null) assert.notStrictEqual(typeof myElement, 'undefined') assert.strictEqual(myElement.tagName, 'H3') assert.doesNotThrow(function() { setTimeout(() => myElement.click()) }) }) }) it('should setup click detection with events() after run() occurs', function(done) { function app() { return { view$: most.of(h3('.test2.myelementclass', 'Foobar')), } } const { sources, dispose } = Motorcycle.run<any, any>(app, (sinks: any) => ({ dom: makeDomComponent(createRenderTarget())(sinks).dom, })) sources.dom.select('.myelementclass').events('click').observe((ev: Event) => { assert.strictEqual(ev.type, 'click') assert.strictEqual((ev.target as HTMLHeadElement).textContent, 'Foobar') dispose() done() }) // Make assertions setTimeout(() => { const myElement = document.querySelector('.test2.myelementclass') as HTMLElement assert.notStrictEqual(myElement, null) assert.notStrictEqual(typeof myElement, 'undefined') assert.strictEqual(myElement.tagName, 'H3') assert.doesNotThrow(function() { setTimeout(() => (myElement as any).click()) }) }, 200) }) it('should setup click detection on a ready dom element (e.g. from server)', function(done) { function app() { return { view$: most.never(), } } const containerElement = createRenderTarget() const headerElement = document.createElement('H3') headerElement.className = 'myelementclass' headerElement.textContent = 'Foobar' containerElement.appendChild(headerElement) const { sources, dispose } = Motorcycle.run<any, any>(app, (sinks: any) => ({ dom: makeDomComponent(containerElement)(sinks).dom, })) sources.dom.select('.myelementclass').events('click').observe((ev: Event) => { assert.strictEqual(ev.type, 'click') assert.strictEqual((ev.target as HTMLHeadElement).textContent, 'Foobar') dispose() done() }) // Make assertions setTimeout(() => { const myElement = containerElement.querySelector('.myelementclass') as HTMLElement assert.notStrictEqual(myElement, null) assert.notStrictEqual(typeof myElement, 'undefined') assert.strictEqual(myElement.tagName, 'H3') assert.doesNotThrow(function() { setTimeout(() => (myElement as any).click()) }) }, 200) }) it('should catch events using id of root element in dom.select', function(done) { function app() { return { view$: most.of(h3('.myelementclass', 'Foobar')), } } const { sources, dispose } = Motorcycle.run<any, any>(app, (sinks: any) => ({ dom: makeDomComponent(createRenderTarget('parent-001'))(sinks).dom, })) // Make assertions sources.dom.select('#parent-001').events('click').observe((ev: Event) => { assert.strictEqual(ev.type, 'click') assert.strictEqual((ev.target as HTMLHeadElement).textContent, 'Foobar') dispose() done() }) sources.dom.select(':root').elements().skip(1).take(1).observe(function([root]: Array<HTMLElement>) { const myElement: any = root.querySelector('.myelementclass') assert.notStrictEqual(myElement, null) assert.notStrictEqual(typeof myElement, 'undefined') assert.strictEqual(myElement.tagName, 'H3') assert.doesNotThrow(function() { setTimeout(() => myElement.click()) }) }) }) it('should catch events using id of top element in dom.select', function(done) { function app() { return { view$: most.of(h3('#myElementId', 'Foobar')), } } const { sources, dispose } = Motorcycle.run<any, any>(app, (sinks: any) => ({ dom: makeDomComponent(createRenderTarget('parent-002'))(sinks).dom, })) // Make assertions sources.dom.select('#myElementId').events('click').observe((ev: Event) => { assert.strictEqual(ev.type, 'click') assert.strictEqual((ev.target as HTMLHeadElement).textContent, 'Foobar') dispose() done() }) sources.dom.select(':root').elements().skip(1).take(1) .observe(function([root]: Array<HTMLElement>) { const myElement: any = root.querySelector('#myElementId') assert.notStrictEqual(myElement, null) assert.notStrictEqual(typeof myElement, 'undefined') assert.strictEqual(myElement.tagName, 'H3') assert.doesNotThrow(function() { setTimeout(() => myElement.click()) }) }) }) it('should catch interaction events without prior select()', function(done) { function app() { return { view$: most.of(div('.parent', [ h3('.myelementclass', 'Foobar'), ])), } } const { sources, dispose } = Motorcycle.run<any, any>(app, (sinks: any) => ({ dom: makeDomComponent(createRenderTarget())(sinks).dom, })) // Make assertions sources.dom.events('click').observe((ev: Event) => { assert.strictEqual(ev.type, 'click') assert.strictEqual((ev.target as HTMLHeadElement).textContent, 'Foobar') dispose() done() }) sources.dom.select(':root').elements().skip(1).take(1).observe(function([root]: Array<HTMLElement>) { const myElement: any = root.querySelector('.myelementclass') assert.notStrictEqual(myElement, null) assert.notStrictEqual(typeof myElement, 'undefined') assert.strictEqual(myElement.tagName, 'H3') assert.doesNotThrow(function() { setTimeout(() => myElement.click()) }) }) }) it('should catch user events using dom.select().select().events()', function(done) { function app() { return { view$: most.of( h3('.top-most', [ h2('.bar', 'Wrong'), div('.foo', [ h4('.bar', 'Correct'), ]), ]), ), } } const { sources, dispose } = Motorcycle.run<any, any>(app, (sinks: any) => ({ dom: makeDomComponent(createRenderTarget())(sinks).dom, })) // Make assertions sources.dom.select('.foo').select('.bar').events('click').observe((ev: Event) => { assert.strictEqual(ev.type, 'click') assert.strictEqual((ev.target as HTMLHeadElement).textContent, 'Correct') dispose() done() }) sources.dom.select(':root').elements().skip(1).take(1) .observe(function([root]: Array<HTMLElement>) { const wrongElement: any = root.querySelector('.bar') const correctElement: any = root.querySelector('.foo .bar') assert.notStrictEqual(wrongElement, null) assert.notStrictEqual(correctElement, null) assert.notStrictEqual(typeof wrongElement, 'undefined') assert.notStrictEqual(typeof correctElement, 'undefined') assert.strictEqual(wrongElement.tagName, 'H2') assert.strictEqual(correctElement.tagName, 'H4') assert.doesNotThrow(function() { setTimeout(() => wrongElement.click()) setTimeout(() => correctElement.click(), 15) }) }) }) it('should catch events from many elements using dom.select().events()', function(done) { function app() { return { view$: most.of(div('.parent', [ h4('.clickable.first', 'First'), h4('.clickable.second', 'Second'), ])), } } const { sources, dispose } = Motorcycle.run<any, any>(app, (sinks: any) => ({ dom: makeDomComponent(createRenderTarget())(sinks).dom, })) // Make assertions sources.dom.select('.clickable').events('click').take(1) .observe((ev: Event) => { assert.strictEqual(ev.type, 'click') assert.strictEqual((ev.target as HTMLHeadElement).textContent, 'First') }) sources.dom.select('.clickable').events('click').skip(1).take(1) .observe((ev: Event) => { assert.strictEqual(ev.type, 'click') assert.strictEqual((ev.target as HTMLHeadElement).textContent, 'Second') dispose() done() }) sources.dom.select(':root').elements().skip(1).take(1) .observe(function([root]: Array<HTMLElement>) { const firstElem: any = root.querySelector('.first') const secondElem: any = root.querySelector('.second') assert.notStrictEqual(firstElem, null) assert.notStrictEqual(typeof firstElem, 'undefined') assert.notStrictEqual(secondElem, null) assert.notStrictEqual(typeof secondElem, 'undefined') assert.doesNotThrow(function() { setTimeout(() => firstElem.click()) setTimeout(() => secondElem.click(), 5) }) }) }) it('should catch interaction events from future elements', function(done) { function app() { return { view$: most.concat( most.of(h2('.blesh', 'Blesh')), most.of(h3('.blish', 'Blish')).delay(100), ).concat(most.of(h4('.blosh', 'Blosh')).delay(100)), } } const { sources, dispose } = Motorcycle.run<any, any>(app, (sinks: any) => ({ dom: makeDomComponent(createRenderTarget('parent-002'))(sinks).dom, })) // Make assertions sources.dom.select('.blosh').events('click').observe((ev: Event) => { assert.strictEqual(ev.type, 'click') assert.strictEqual((ev.target as HTMLHeadElement).textContent, 'Blosh') dispose() done() }) .catch(done) sources.dom.select(':root').elements().skip(3).take(1) .observe(function([root]: Array<HTMLElement>) { const myElement: any = root.querySelector('.blosh') assert.notStrictEqual(myElement, null) assert.notStrictEqual(typeof myElement, 'undefined') assert.strictEqual(myElement.tagName, 'H4') assert.strictEqual(myElement.textContent, 'Blosh') assert.doesNotThrow(function() { setTimeout(() => myElement.click()) }) }) .catch(done) }) it('should catch a non-bubbling click event with useCapture', function(done) { function app() { return { view$: most.of(div('.parent', [ div('.clickable', 'Hello'), ])), } } function click(el: HTMLElement) { const ev: any = document.createEvent(`MouseEvent`) ev.initMouseEvent( `click`, false /* bubble */, true /* cancelable */, window, null, 0, 0, 0, 0, /* coordinates */ false, false, false, false, /* modifier keys */ 0 /*left*/, null, ) el.dispatchEvent(ev) } const { sources } = Motorcycle.run<any, any>(app, (sinks: any) => ({ dom: makeDomComponent(createRenderTarget())(sinks).dom, })) sources.dom.select('.clickable').events('click', {useCapture: true}) .observe((ev: Event) => { assert.strictEqual(ev.type, 'click') assert.strictEqual((ev.target as HTMLElement).tagName, 'DIV') assert.strictEqual((ev.target as HTMLElement).className, 'clickable') assert.strictEqual((ev.target as HTMLHeadElement).textContent, 'Hello') done() }) sources.dom.select('.clickable').events('click', {useCapture: false}) .observe(assert.fail) sources.dom.select(':root').elements().skip(1).take(1).observe(([root]: Array<HTMLElement>) => { const clickable: any = root.querySelector('.clickable') setTimeout(() => click(clickable)) }) }) it('should catch a blur event with useCapture', function(done) { if (!document.hasFocus()) return done() function app() { return { view$: most.of(div('.parent', [ input('.correct', { type: 'text' }, []), input('.wrong', { type: 'text' }, []), input('.dummy', { type: 'text' }), ])), } } const { sources } = Motorcycle.run<any, any>(app, (sinks: any) => ({ dom: makeDomComponent(createRenderTarget())(sinks).dom, })) sources.dom.select('.correct').events('blur', {useCapture: true}) .observe((ev: Event) => { assert.strictEqual(ev.type, 'blur') assert.strictEqual((ev.target as HTMLElement).className, 'correct') done() }) sources.dom.select(':root').elements().skip(1).take(1).observe(([root]: Array<HTMLElement>) => { const correct: any = root.querySelector('.correct') const wrong: any = root.querySelector('.wrong') const dummy: any = root.querySelector('.dummy') setTimeout(() => wrong.focus(), 50) setTimeout(() => dummy.focus(), 100) setTimeout(() => correct.focus(), 150) setTimeout(() => dummy.focus(), 200) }) }) it('should catch a blur event by default (no options)', function(done) { if (!document.hasFocus()) return done() function app() { return { view$: most.of(div('.parent', [ input('.correct', { type: 'text' }, []), input('.wrong', { type: 'text' }, []), input('.dummy', { type: 'text' }), ])), } } const { sources } = Motorcycle.run<any, any>(app, (sinks: any) => ({ dom: makeDomComponent(createRenderTarget())(sinks).dom, })) sources.dom.select('.correct').events('blur') .observe((ev: Event) => { assert.strictEqual(ev.type, 'blur') assert.strictEqual((ev.target as HTMLElement).className, 'correct') done() }) sources.dom.select(':root').elements().skip(1).take(1).observe(([root]: Array<HTMLElement>) => { const correct: any = root.querySelector('.correct') const wrong: any = root.querySelector('.wrong') const dummy: any = root.querySelector('.dummy') setTimeout(() => wrong.focus(), 50) setTimeout(() => dummy.focus(), 100) setTimeout(() => correct.focus(), 150) setTimeout(() => dummy.focus(), 200) }) }) })
the_stack
import * as _ from 'lodash'; import { Component, ElementRef, EventEmitter, Injector, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; import {AbstractComponent} from '@common/component/abstract.component'; import {PopupService} from '@common/service/popup.service'; import {SubscribeArg} from '@common/domain/subscribe-arg'; import {ImportType, PrDataset} from '@domain/data-preparation/pr-dataset'; import {DataflowService} from '../dataflow/service/dataflow.service'; import {PreparationAlert} from '../util/preparation-alert.util'; import {PreparationCommonUtil} from '../util/preparation-common.util'; import {RadioSelectDatasetComponent} from './radio-select-dataset.component'; @Component({ selector: 'long-update-popup', templateUrl: './long-update-popup.component.html' }) export class LongUpdatePopupComponent extends AbstractComponent implements OnInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @ViewChild('inputSearch') private _inputSearch: ElementRef; private firstLoadCompleted: boolean = false; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public - ViewChild |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @ViewChild(RadioSelectDatasetComponent) public radioSelectDatasetComponent: RadioSelectDatasetComponent; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public - Output Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @Output() public closeEvent = new EventEmitter(); @Output() public doneEvent = new EventEmitter(); @Output() public addEvent = new EventEmitter(); /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public - Input Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @Input() public dataflowId: string; // 현재 데이터플로우 아이디 @Input() public isRadio: boolean = false; @Input() public popType: string = ''; @Input() public originalDatasetList: PrDataset[] = []; // 현재 데이터플로우에 추가되어 있는 모든 데이터셋 정보 @Input() public selectedDatasetId: string; // 미리보기를 위해 화면에 선택된 데이터셋 /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ public originalDatasetId: string; // 이미 데이터플로우에 추가된 데이터셋 public datasets: PrDataset[] = []; // 화면에 보여지는 리스트 public swappingDatasetId: string; public title: string; public layoutType: string = 'ADD'; // 새로운 데이터셋 추가 ADD, 기존 데이터셋 치환 SWAP public selectedDatasets: PrDataset[]; // 선택된 데이터셋 리스트 // 정렬 public selectedContentSort: Order = new Order(); public searchText: string = ''; public searchType: string = 'IMPORTED'; public isShow: boolean = false; // popup status public step: string; public prepCommonUtil = PreparationCommonUtil; public ImportType = ImportType; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ constructor(protected elementRef: ElementRef, protected injector: Injector, private dataflowService: DataflowService, private popupService: PopupService) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // Init public ngOnInit() { super.ngOnInit(); this.subscriptions.push( this.popupService.view$.subscribe((data: SubscribeArg) => { this.step = data.name; if (this.step === 'complete-dataset-create') { if (data.hasOwnProperty('data') && data.data !== null) { this.selectedDatasetId = data.data; if (this.layoutType === 'SWAP') { this.swappingDatasetId = data.data; } } $('.ddp-ui-gridbody').scrollTop(0); this._initViewPage() } }) ); if (this.isRadio) { // 기존 데이터셋 치환 SWAP this.layoutType = 'SWAP'; this.originalDatasetId = this.selectedDatasetId; } else { // 새로운 데이터셋 추가 ADD this.layoutType = 'ADD'; } this.selectedDatasetId = ''; if (this.popType === 'add') { this.title = this.translateService.instant('msg.dp.btn.add.ds'); } else if (this.popType === 'imported') { this.title = this.translateService.instant('msg.dp.ui.swap.dataset'); } else if (this.popType === 'wrangled') { this.title = this.translateService.instant('msg.dp.ui.change.input.dataset'); } this._initViewPage(); } // Destroy public ngOnDestroy() { super.ngOnDestroy(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 화면 닫기 */ public close() { this.closeEvent.emit(); this.datasets = []; this.page.page = 0; } // function - close /** * 다음 단계로 이동 */ public done() { if (this.layoutType === 'ADD') { // 선택된 데이터셋이 없으면 X if (this.isNullOrUndefined(this.selectedDatasets) || this.selectedDatasets.length === 0) { return } const datasetLists: string[] = []; this.selectedDatasets.forEach((ds) => { datasetLists.push(ds.dsId); }); this.addEvent.emit(datasetLists); } else if (this.layoutType === 'SWAP') { const param = {oldDsId: this.originalDatasetId, newDsId: this.swappingDatasetId}; param['type'] = this.popType; this.doneEvent.emit(param); } } // function - next /** * 검색 조회 - 키보드 이벤트 * @param {KeyboardEvent} event */ public searchEventPressKey(event: KeyboardEvent) { (13 === event.keyCode) && (this.searchEvent()); } // function - searchEventPressKey /** * 검색 조회 */ public searchEvent() { // 검색어 설정 this.searchText = this._inputSearch.nativeElement.value; // 페이지 초기화 this.page.page = 0; // 상세정보 화면 초기화 this.selectedDatasetId = ''; // 데이터소스 리스트 조회 this.getDatasets(); } // function - searchEvent /** * Clear search text * @param isClear */ public resetSearchText(isClear: boolean) { if (isClear) { this._inputSearch.nativeElement.value = ''; } else { // 검색어 설정 this._inputSearch.nativeElement.value = this.searchText; } } // function - resetSearchText /** * 데이터셋 요약 페이지 닫았을 때 발생 이벤트 */ public onCloseSummary() { this.selectedDatasetId = ''; this.safelyDetectChanges(); } // function - onCloseSummary /** * 새로운 데이터셋 만들기 */ public createDataset() { // 데이터셋 생성 팝업 생성 this.step = 'select-datatype'; } // function - createDataset /** * Retrieve dataset list */ private getDatasets() { this.loadingShow(); this.dataflowService.getDatasets(this.searchText, this.page, 'listing', this.searchType, '') .then((data) => { this.loadingHide(); this.pageResult = data['page']; const sorting = this.page.sort.split(','); this.selectedContentSort.key = sorting[0]; this.selectedContentSort.sort = sorting[1]; if (this.page.page === 0) { // 첫번째 페이지이면 초기화 this.datasets = []; } this.datasets = this.datasets.concat(data['_embedded'].preparationdatasets); if (this.layoutType === 'ADD') { // 데이터플로우에 이미 추가된 데이터셋이라면 selected, origin 을 true 로 준다. this.datasets.forEach((item) => { item.origin = _.findIndex(this.originalDatasetList, {dsId: item.dsId}) > -1; const idx = _.findIndex(this.selectedDatasets, {dsId: item.dsId}); item.selected = idx > -1; }); } if (this.layoutType === 'SWAP') { // 데이터 플로우에 이미 추가된 데이터셋이라면 selected, origin 을 true 로 준다. this.datasets.forEach((item) => { item.selected = item.dsId === this.selectedDatasetId; item.origin = item.dsId === this.selectedDatasetId; }); // SWAP (radio button) mode : radio button 이 check 되지 않은 상태에서 부모화면에서 선택한 데이터셋이 load 된 경우, 이 항목의 radio button 을 check 한다 if (this.firstLoadCompleted === false && (this.swappingDatasetId === undefined || this.swappingDatasetId === '')) { for (let i: number = 0, nMax = this.datasets.length; i < nMax; i = i + 1) { if (this.originalDatasetId === this.datasets[i].dsId) { this.swappingDatasetId = this.datasets[i].dsId; this.firstLoadCompleted = true; break; } } } } // 총페이지 수 this.page.page += 1; }).catch((error) => { this.loadingHide(); const prepError = this.dataprepExceptionHandler(error); PreparationAlert.output(prepError, this.translateService.instant(prepError.message)); }); } // function - getDatasets /** * 전체 체크 인지 확인 */ public isAllChecked(): boolean { if (this.isCheckAllDisabled()) { return; } const listWithNoOrigin = this.datasets.filter((item) => { return !item.origin }); if (listWithNoOrigin.length !== 0) { for (let index = 0, nMax = listWithNoOrigin.length; index < nMax; index++) { if (_.findIndex(this.selectedDatasets, {dsId: listWithNoOrigin[index].dsId}) === -1) { return false; } } return true; } else { // 조회된 멤버 목록이 없다면 false return false; } } /** * 전체 체크 박스가 비활성화 인지 확인 */ public isCheckAllDisabled(): boolean { return this.datasets.length === 0; } /** * 더보기 버튼 클릭 */ public getMoreList() { // 더 보여줄 데이터가 있다면 if (this.page.page < this.pageResult.totalPages) { // 데이터셋 조회 this.getDatasets(); } } /** * 정렬 정보 변경 * @param {string} column */ public changeOrder(column: string) { // 상세화면 초기화(close) this.selectedDatasetId = ''; // page sort 초기화 this.selectedContentSort.sort = this.selectedContentSort.key !== column ? 'default' : this.selectedContentSort.sort; // 정렬 정보 저장 this.selectedContentSort.key = column; if (this.selectedContentSort.key === column) { // asc, desc, default switch (this.selectedContentSort.sort) { case 'asc': this.selectedContentSort.sort = 'desc'; break; case 'desc': this.selectedContentSort.sort = 'asc'; break; case 'default': this.selectedContentSort.sort = 'desc'; break; } } // 페이지 초기화 this.page.page = 0; this.page.sort = column + ',' + this.selectedContentSort.sort; this.getDatasets(); } // function - changeOrder /** * 데이터 셋 선택 * @param dataset */ public selectDataset(dataset: any) { // 지금 보고있는 데이터면 show 해제 if (dataset.dsId === this.selectedDatasetId) { this.selectedDatasetId = ''; } else { // 데이터 아이디 저장 this.selectedDatasetId = dataset.dsId; } } // function - selectDataset /** * 라디오 버튼 선택 */ public radioCheck(event, item) { event.stopPropagation(); this.swappingDatasetId = item.dsId; } // function - check /** * 체크박스 전체 선택 */ public checkAll() { this.isAllChecked() ? this._deleteAllItems() : this._addAllItems(); } /** * 체크박스 선택 */ public check(ds: PrDataset) { // 중복 체크 방지 event.stopImmediatePropagation(); // Original dataset cannot be checked if (ds.origin) { return; } ds.selected = !ds.selected; -1 === _.findIndex(this.selectedDatasets, {dsId: ds.dsId}) ? this._addSelectedItem(ds) : this._deleteSelectedItem(ds); } // function - check /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * Init * @private */ private _initViewPage() { // 검색어 초기화 this.searchText = ''; // 선택된 checkbox 항목 초기화 this.selectedDatasets = []; // 정렬 this.selectedContentSort = new Order(); this.selectedContentSort.key = 'modifiedTime'; this.selectedContentSort.sort = 'desc'; // page 설정 this.page.page = 0; this.page.size = 15; this.page.sort = this.selectedContentSort.key + ',' + this.selectedContentSort.sort; this.getDatasets(); } // function - initViewPage /** * Add selected item * @param ds * @private */ private _addSelectedItem(ds: PrDataset) { this.selectedDatasets.push(ds); } /** * Delete selected item * @param ds * @private */ private _deleteSelectedItem(ds: PrDataset) { const index = _.findIndex(this.selectedDatasets, {dsId: ds.dsId}); if (-1 !== index) { this.selectedDatasets.splice(index, 1); } } /** * 모든 아이템 선택 해제 * @private */ private _deleteAllItems() { this.datasets.forEach((item) => { if (!item.origin && item.selected) { item.selected = false; this._deleteSelectedItem(item); } }) } /** * 모든 아이템 선택 * @private */ private _addAllItems() { this.datasets.forEach((item) => { if (!item.origin) { item.selected = true; if (-1 === _.findIndex(this.selectedDatasets, {dsId: item.dsId})) { this._addSelectedItem(item); } } }) } } class Order { key: string = 'seq'; sort: string = 'default'; }
the_stack
import * as fc from "fast-check"; import { array } from "fp-ts/lib/Array"; import { left, right } from "fp-ts/lib/Either"; import { FunctionN, identity } from "fp-ts/lib/function"; import { pipe } from "fp-ts/lib/pipeable"; import {abort, done, interrupt, raise } from "../src/exit"; import { Wave } from "../src/wave"; import * as io from "../src/wave"; import { makeRef } from "../src/ref"; import { arbConstIO, arbEitherIO, arbErrorIO, arbErrorKleisliIO, arbIO, arbKleisliIO, eqvIO, expectExit } from "./tools.spec"; // Tests for the io module describe("io", () => { describe("#succeed", () => { it("should complete with a completed", () => expectExit(io.pure(42), done(42)) ); }); describe("#fail", () => { it("should complete with a failed", () => expectExit(io.raiseError("boom"), raise("boom")) ); }); describe("#abort", () => { it("should complete with an aborted", () => expectExit(io.raiseAbort("boom"), abort("boom")) ); }); describe("#interrupted", () => { it("should complete with an interrupted", () => expectExit(io.raiseInterrupt, interrupt) ); }); describe("#exitWith", () => { it("should complete with a completed when provided", () => expectExit(io.completed(done(42)), done(42)) ); it("should complete with a failed when provided", () => expectExit(io.completed(raise("boom")), raise("boom")) ); it("should complete with an aborted when provided", () => expectExit(io.completed(abort("boom")), abort("boom")) ); it("should complete with an interrupted when provided", () => expectExit(io.completed(interrupt), interrupt) ); }); describe("#effect", () => { it("should complete at some a success", () => expectExit(io.sync(() => 42), done(42)) ); }); describe("#suspend", () => { it("should complete with synchronous effects", () => expectExit(io.suspended(() => io.pure(42)), done(42)) ); it("should complete with asynchronous effects", () => expectExit(io.suspended(() => io.asyncTotal((callback) => { const handle = setTimeout(() => callback(42), 0); return () => { clearTimeout(handle); }; }) ), done(42)) ); }); describe("#delay", () => { it("should complete with a success eventually", () => expectExit(io.asyncTotal((callback) => { const handle = setTimeout(() => callback(42), 0); return () => { clearTimeout(handle); }; }), done(42)) ); }); describe("#async", () => { it("should complete with a success eventually", () => expectExit(io.async((callback) => { const handle = setTimeout(() => callback(right(42)), 0); return () => { clearTimeout(handle); }; }), done(42)) ); it("should complete with a failed eventually", () => expectExit(io.async((callback) => { const handle = setTimeout(() => callback(left("boom")), 0); return () => { clearTimeout(handle); }; }), raise("boom")) ); }); describe("#interrupted", () => { it("should complete with interrupted", () => expectExit(io.raiseInterrupt, interrupt) ); }); describe("#run", () => { it("should complete with an expected completion", () => expectExit(io.result(io.pure(42)), done(done(42))) ); it("should complete with an expected failure", () => expectExit(io.result(io.raiseError("boom")), done(raise("boom"))) ); it("should complete with an expected abort", () => expectExit(io.result(io.raiseAbort("boom")), done(abort("boom"))) ); /** * This may be counter-intruitive, but the interrupted io sets the interrupted flag. * Additionally, because of how the driver operates, there is always a at least 1 more action following leaving an * uninterruptible region * Therefore it is never possible to fully complete a fiber that has been interrupted and we don't get a 'value' as * above */ it("should complete with an expected interrupt", () => expectExit(io.uninterruptible(io.result(io.raiseInterrupt)), interrupt) ); }); describe("raceFirst", () => { it("should resolve with the first success", () => expectExit(io.raceFirst(io.delay(io.pure(42), 10), io.never), done(42)) ); it("should resolve with the first success (flipped)", () => expectExit(io.raceFirst(io.never, io.delay(io.pure(42), 10)), done(42)) ); it("should resolve with the first error", () => expectExit(io.raceFirst(io.delay(io.raiseError("boom"), 10), io.never), raise("boom")) ); it("should resolve with the first error (flipped)", () => expectExit(io.raceFirst(io.never, io.delay(io.raiseError("boom"), 10)), raise("boom")) ); }); describe("race", () => { it("should resolve wih a success", () => expectExit(io.zip( io.race(io.delay(io.pure(42), 10), io.never), io.race(io.never, io.delay(io.pure(42), 14)) ), done([42, 42] as const)) ); it("should resolve to a success on a failure", () => expectExit(io.race(io.raiseError("boom!"), io.delay(io.pure(42), 10)), done(42)) ); }); describe("interruptible state", () => { it("should set interrupt status", () => expectExit( io.interruptible(io.accessInterruptible), done(true) ) ); it("should set nested interrupt status", () => expectExit( io.uninterruptible(io.interruptible(io.accessInterruptible)), done(true) ) ); it("should compose", () => expectExit( io.uninterruptible(io.interruptible(io.uninterruptible(io.accessInterruptible))), done(false) ) ); it("should allow setting uninterruptible", () => expectExit( io.uninterruptible(io.accessInterruptible), done(false) ) ); }); // Property test utils // base on fp-ts-laws at https://github.com/gcanti/fp-ts-laws but adapter for the fact that we need to run IOs describe("laws", function() { this.timeout(60000); const strlen: FunctionN<[string], number> = (s: string) => s.length; const even: FunctionN<[number], boolean> = (n: number) => n % 2 === 0; const functor = { identity: <E, A>(ioa: Wave<E, A>) => eqvIO(io.map(ioa, identity), ioa), composition: <E, A, B, C>(ioa: Wave<E, A>, fab: FunctionN<[A], B>, fbc: FunctionN<[B], C>) => eqvIO(pipe(ioa, io.lift(fab), io.lift(fbc)), io.map(ioa, (a) => fbc(fab(a)))) }; const apply = { associativeComposition: <E, A, B, C>(ioa: Wave<E, A>, iofab: Wave<E, FunctionN<[A], B>>, iofbc: Wave<E, FunctionN<[B], C>>) => eqvIO( io.ap_( io.ap_( io.map(iofbc, (bc) => (ab: FunctionN<[A], B>) => (a: A) => bc(ab(a)) ), iofab ), ioa ), io.ap_(iofbc, io.ap_(iofab, ioa)) ) }; const applicative = { identity: <E, A>(ioa: Wave<E, A>) => eqvIO( io.ap(ioa, io.pure(identity)), ioa ), homomorphism: <A, B>(fab: FunctionN<[A], B>, a: A) => eqvIO( io.ap_(io.pure(fab), io.pure(a)), io.pure(fab(a)) ), interchange: <E, A, B>(a: A, iofab: Wave<E, FunctionN<[A], B>>) => eqvIO( io.ap_(iofab, io.pure(a)), io.ap_(io.pure((ab: FunctionN<[A], B>) => ab(a)), iofab) ), derivedMap: <E, A, B>(ab: FunctionN<[A], B>, ioa: Wave<E, A>) => eqvIO( io.map(ioa, ab), io.ap_(io.pure(ab), ioa) ) }; const chain = { associativivity: <E, A, B, C>(ioa: Wave<E, A>, kab: FunctionN<[A], Wave<E, B>>, kbc: FunctionN<[B], Wave<E, C>>) => eqvIO( pipe( ioa, io.chainWith(kab), io.chainWith(kbc) ), io.chain(ioa, (a) => io.chain(kab(a), kbc)) ), derivedAp: <E, A, B>(iofab: Wave<E, FunctionN<[A], B>>, ioa: Wave<E, A>) => eqvIO( io.ap(ioa, iofab), io.chain(iofab, (f) => io.map(ioa, f)) ) }; const monad = { leftIdentity: <E, A, B>(kab: FunctionN<[A], Wave<E, B>>, a: A) => eqvIO( io.chain(io.pure(a), kab), kab(a) ), rightIdentity: <E, A>(ioa: Wave<E, A>) => eqvIO( io.chain(ioa, io.pure), ioa ), derivedMap: <E, A, B>(ab: FunctionN<[A], B>, ioa: Wave<E, A>) => eqvIO( io.map(ioa, ab), io.chain(ioa, (a) => io.pure(ab(a))) ) }; describe("Functor", () => { it("- identity", () => fc.assert(fc.asyncProperty(arbIO(fc.integer()), functor.identity)) ); it("- composition", () => fc.assert( fc.asyncProperty( arbIO(fc.string()), fc.constant(strlen), fc.constant(even), functor.composition ) ) ); }); describe("Apply", () => { it("- associaive composition", () => fc.assert( fc.asyncProperty( arbIO(fc.string()), fc.constant(strlen).map(io.pure), fc.constant(even).map(io.pure), apply.associativeComposition ) ) ); }); describe("Applicative", () => { it("- identity", () => fc.assert( fc.asyncProperty( arbIO(fc.string()), applicative.identity ) ) ); it("- homomorphism", () => fc.assert( fc.asyncProperty( fc.constant(strlen), fc.string(), applicative.homomorphism ) ) ); it("- interchange", () => fc.assert( fc.asyncProperty( fc.string(), arbIO(fc.constant(strlen)), applicative.interchange ) ) ); it("- derived map", () => fc.assert( fc.asyncProperty( fc.constant(strlen), arbIO(fc.string()), applicative.derivedMap ) ) ); }); describe("Chain", () => { it(" - associativity", () => fc.assert( fc.asyncProperty( arbIO(fc.string()), arbKleisliIO(fc.constant(strlen)), arbKleisliIO(fc.constant(even)), chain.associativivity ) ) ); it(" - derived ap", () => fc.assert( fc.asyncProperty( fc.constant(strlen).map(io.pure), arbIO(fc.string()), chain.derivedAp ) ) ); }); describe("Monad", () => { it(" - left identity", () => fc.assert( fc.asyncProperty( arbKleisliIO(fc.constant(strlen)), fc.string(), monad.leftIdentity ) ) ); it(" - right identity", () => fc.assert( fc.asyncProperty( arbIO(fc.string()), monad.rightIdentity ) ) ); it(" - derived map", () => fc.assert( fc.asyncProperty( fc.constant(strlen), arbIO(fc.string()), monad.derivedMap ) ) ); }); describe("MonadError", () => { const monadError = { // The host exists to ensure we are testing in async boundaries recoveryEquivalence: <E, E2, A>(host: Wave<E2, A>, e: E, kea: FunctionN<[E], Wave<E2, A>>) => eqvIO( io.chain(host, () => io.chainError(io.raiseError(e), kea)), io.chain(host, () => kea(e)) ) }; it(" - recovery equivalence", () => fc.assert( fc.asyncProperty( arbConstIO(undefined), fc.string(), arbErrorKleisliIO(fc.constant(strlen)), monadError.recoveryEquivalence ) ) ); }); }); describe("properties", function() { this.timeout(10000); it("any number of successful IOs surrounding a failed IO produces the error of the failed IO", () => fc.assert( fc.asyncProperty( fc.array(arbIO<string, number>(fc.integer())), arbErrorIO<string, number>(fc.constant("failure")), fc.array(arbIO<string, number>(fc.integer())), (before, err, after) => { const arr = [...before, err, ...after] const result = array.sequence(io.instances)(arr) return eqvIO(result, io.as(err, [] as number[])); } ) ) ); }); describe("parZip", function () { this.timeout(10000); it("many async ios should be parZipWithAble", () => { const ios: Wave<never, number>[] = []; for (let i = 0; i < 10000; i++) { ios.push(io.delay(io.pure(1), Math.random() * 100)); } return eqvIO( array.reduce(ios, io.pure(42) as Wave<never, number>, (l, r) => io.parApplyFirst(l, r)), io.pure(42) ); }); it("many sync ios should be parZipWithAble", () => { const ios: Wave<never, number>[] = []; for (let i = 0; i < 10000; i++) { ios.push(io.pure(1)); } return eqvIO( array.reduce(ios, io.pure(42) as Wave<never, number>, (l, r) => io.parApplyFirst(l, r)), io.pure(42) ); }); }) describe("#bracketExit", function() { this.timeout(10000); // Verify that bracketExit has the cleanup semantics that we expect // We produce an acquisition and release that wait for a random time and then increment/decrement a ref // We also have a use that waits some time then succeeds or fails randomly // Finally, we interrupt this thread after some random delay // In all cases the value of the resuling ref should be 0 because of cleanup it("finalizer should execute in all cases", () => fc.assert( fc.asyncProperty( fc.nat(30), fc.nat(30), fc.nat(30), fc.nat(90), arbEitherIO(fc.string(), fc.nat()), (acqDelay, useDelay, relDelay, interruptDelay, useResult) => expectExit( io.chain(makeRef(0), (cell) => { const action = io.bracket( io.delay(cell.update((n) => n + 1), acqDelay), () => io.delay(cell.update((n) => n - 1), relDelay), () => io.delay(useResult, useDelay)); return io.chain( io.fork(action), (child) => io.applySecond(io.delay(child.interrupt, interruptDelay), cell.get) ); }), done(0) ) ) ) ); }); });
the_stack
import Base from '~/src/command/generate/base' import { TypeWeiboUserInfo, TypeMblog, TypeWeiboEpub, TypeWeiboListByDay } from '~/src/type/namespace/weibo' import TypeTaskConfig from '~/src/type/namespace/task_config' import PathConfig from '~/src/config/path' import MMblog from '~/src/model/mblog' import MMblogUser from '~/src/model/mblog_user' import DATE_FORMAT from '~/src/constant/date_format' import imageSize from 'image-size' import _ from 'lodash' import json5 from 'json5' import { TypeTransConfigItem, TypeTransConfigPackageList, TypeTransConfigPackage } from "./trans_config" import WeiboView from '~/src/view/weibo' import BaseView from '~/src/view/base' import fs from 'fs' import path from 'path' import StringUtil from '~/src/library/util/string' import moment from 'moment' import * as mozjpeg from "mozjpeg-js" import sharp from "sharp" // 将img输出为pdf import TaskConfig from '~/src/type/namespace/task_config' import jsPDF from '~/src/library/pdf/jspdf.node.js' import { BrowserWindow } from 'electron' import CommonUtil from '~/src/library/util/common' /** * 单张页面渲染时间不能超过60秒 */ const Const_Render_Html_Timeout_Second = 60 /** * 渲染webview最大高度(经实验, 当Electron窗口高度超过16380时, 会直接黑屏卡死, 所以需要专门限制下) */ const Const_Max_Webview_Render_Height_Px = 5000 /** * 单卷中最多只能有5000条微博 */ const Const_Max_Mblog_In_Single_Book = 5000 /** * 在宽度为760的前提下, sharp最多支持的jpg高度(正常值为60000, 安全起见取50000) * 超大图片在手机上也很难打开, 因此将分页高度改为25000, 这样每张图高30000px, 还算可以接受 */ const Const_Max_Jpge_Height_In_Sharp_Px = 25000 /** * 屏幕分辨率是否正常 * * 高分屏下,截图截出来的实际像素和指定像素值不一致. * 设定宽度为760,但实际截屏结果为1520,会大2倍 * 如果  Screen_Display_Rate 不一致, 需要提前对截图结果进行处理。 否则后续图片合并会失败 */ let Is_Normal_Display_Rate = true // 硬编码传入 let globalSubWindow: InstanceType<typeof BrowserWindow> = null const Const_Default_Webview_Width = 760; const Const_Default_Webview_Height = 10; class GenerateCustomer extends Base { static get signature() { return ` Generate:Customer ` } static get description() { return '输出微博记录' } /** * 配置项 */ /** * 分类依据 */ CONST_CONFIG_DATE_FORMAT = DATE_FORMAT.DATABASE_BY_DAY CUSTOMER_CONFIG_bookname: TaskConfig.Customer['bookTitle'] = '' CUSTOMER_CONFIG_comment: TaskConfig.Customer['comment'] = '' CUSTOMER_CONFIG_volumeSplitBy: TaskConfig.Customer['volumeSplitBy'] = 'single' CUSTOMER_CONFIG_volumeSplitCount: TaskConfig.Customer['volumeSplitCount'] = 10000 CUSTOMER_CONFIG_postAtOrderBy: TaskConfig.Customer['postAtOrderBy'] = 'asc' CUSTOMER_CONFIG_imageQuilty: TaskConfig.Customer['imageQuilty'] = 'default' CUSTOMER_CONFIG_pdfQuilty: TaskConfig.Customer['pdfQuilty'] = 70 CUSTOMER_CONFIG_outputStartAtMs: TaskConfig.Customer['outputStartAtMs'] = 0 CUSTOMER_CONFIG_outputEndAtMs: TaskConfig.Customer['outputEndAtMs'] = moment() .add(1, 'year') .unix() * 1000 CUSTOMER_CONFIG_isSkipGeneratePdf: TaskConfig.Customer['isSkipGeneratePdf'] = false CUSTOMER_CONFIG_isRegenerateHtml2PdfImage: TaskConfig.Customer['isRegenerateHtml2PdfImage'] = false CUSTOMER_CONFIG_isSkipFetch: TaskConfig.Customer['isSkipFetch'] = false CUSTOMER_CONFIG_isOnlyArticle: TaskConfig.Customer['isOnlyArticle'] = false CUSTOMER_CONFIG_isOnlyOriginal: TaskConfig.Customer['isOnlyOriginal'] = false async detectIsNormalScreenRate() { // 首先先计算屏幕缩放比 let webview = globalSubWindow.webContents; await globalSubWindow.setContentSize( Const_Default_Webview_Width, Const_Default_Webview_Height, ); // 利用百度首页. 测试分辨率是否正常 await webview.loadURL("https://m.baidu.com") let nativeImg = await webview.capturePage(); let content = await nativeImg.toJPEG(100) let realWidth = imageSize.imageSize(content).width || Const_Default_Webview_Width Is_Normal_Display_Rate = realWidth / Const_Default_Webview_Width === 1 } async execute(args: any, options: any): Promise<any> { let { subWindow } = args globalSubWindow = subWindow await this.detectIsNormalScreenRate() this.log(`从${PathConfig.customerTaskConfigUri}中读取配置文件`) let fetchConfigJSON = fs.readFileSync(PathConfig.customerTaskConfigUri).toString() this.log('content =>', fetchConfigJSON) let customerTaskConfig: TypeTaskConfig.Customer = json5.parse(fetchConfigJSON) this.CUSTOMER_CONFIG_bookname = customerTaskConfig.bookTitle this.CUSTOMER_CONFIG_comment = customerTaskConfig.comment this.CUSTOMER_CONFIG_outputStartAtMs = customerTaskConfig.outputStartAtMs this.CUSTOMER_CONFIG_outputEndAtMs = customerTaskConfig.outputEndAtMs this.CUSTOMER_CONFIG_volumeSplitBy = customerTaskConfig.volumeSplitBy this.CUSTOMER_CONFIG_volumeSplitCount = customerTaskConfig.volumeSplitCount this.CUSTOMER_CONFIG_postAtOrderBy = customerTaskConfig.postAtOrderBy this.CUSTOMER_CONFIG_imageQuilty = customerTaskConfig.imageQuilty this.CUSTOMER_CONFIG_pdfQuilty = customerTaskConfig.pdfQuilty || 60 // 加上默认值 this.CUSTOMER_CONFIG_isSkipFetch = customerTaskConfig.isSkipFetch this.CUSTOMER_CONFIG_isSkipGeneratePdf = customerTaskConfig.isSkipGeneratePdf this.CUSTOMER_CONFIG_isRegenerateHtml2PdfImage = customerTaskConfig.isRegenerateHtml2PdfImage this.CUSTOMER_CONFIG_isOnlyArticle = customerTaskConfig.isOnlyArticle this.CUSTOMER_CONFIG_isOnlyOriginal = customerTaskConfig.isOnlyOriginal let configList = customerTaskConfig.configList for (let config of configList) { let author_uid = config.uid // 配置当前生成的用户uid, 便于缓存 this.currentAuthorUid = author_uid let userInfo = await MMblogUser.asyncGetUserInfo(author_uid) if (_.isEmpty(userInfo)) { this.log(`未抓取到对应的用户数据, 自动跳过`) return } let screenName = userInfo.screen_name this.log(`开始输出用户${screenName}的微博备份数据`) // 将任务中的数据按照问题/文章/想法进行汇总 this.log(`获取数据记录`) let article_status_in = [0, 1] let retweet_status_in = [0, 1] if (this.CUSTOMER_CONFIG_isOnlyOriginal) { retweet_status_in = [0] } if (this.CUSTOMER_CONFIG_isOnlyArticle) { article_status_in = [1] } let mblogList = await MMblog.asyncGetMblogList( author_uid, this.CUSTOMER_CONFIG_outputStartAtMs / 1000, this.CUSTOMER_CONFIG_outputEndAtMs / 1000, retweet_status_in, article_status_in ) mblogList.sort((a, b) => { // 先进行排序 // 根据接口 https://m.weibo.cn/feed/friends?max_id=4448802586999203 可以确认, id为确认时间线的关键 // 经测试, 仅通过id并不靠谱, 因此还是要使用发布日期作为排序依据. // 同一日期内再用id排序 let aSortBy = a.created_timestamp_at let bSortBy = b.created_timestamp_at if (a.created_timestamp_at === b.created_timestamp_at) { // 日期相同时, 以id作为排序依据 aSortBy = parseInt(a.id) bSortBy = parseInt(b.id) } if (this.CUSTOMER_CONFIG_postAtOrderBy === 'asc') { return aSortBy! - bSortBy! } else { return bSortBy! - aSortBy! } }) this.log(`数据获取完毕, 共收录${mblogList.length}条微博`) let weiboEpubList = this.packageMblogList(mblogList, userInfo) let bookCounter = 0 for (let resourcePackage of weiboEpubList) { bookCounter++ let booktitle = '' if (weiboEpubList.length <= 1) { booktitle = `${resourcePackage.userInfo.screen_name}-微博整理-(${moment .unix(resourcePackage.startDayAt) .format(DATE_FORMAT.DISPLAY_BY_DAY)}~${moment .unix(resourcePackage.endDayAt) .format(DATE_FORMAT.DISPLAY_BY_DAY)})` } else { booktitle = `${resourcePackage.userInfo.screen_name}-微博整理-第${resourcePackage.bookIndex}/${resourcePackage.totalBookCount }卷-(${moment.unix(resourcePackage.startDayAt).format(DATE_FORMAT.DISPLAY_BY_DAY)}~${moment .unix(resourcePackage.endDayAt) .format(DATE_FORMAT.DISPLAY_BY_DAY)})` } this.log(`输出第${bookCounter}/${weiboEpubList.length}本电子书:${booktitle}`) await this.asyncGenerateEbook(bookCounter, booktitle, resourcePackage) this.log(`第${bookCounter}/${weiboEpubList.length}本电子书:${booktitle}输出完毕`) } } } /** * 1. 将微博按时间顺序排列 * 2. 将微博按配置合并到一起 * 3. 按配置 * 1. 单本电子书最大微博数, 切分成微博Epub列表 * 2. 按年切分成微博Epub列表 * @param mblogList * @param userInfo */ packageMblogList(mblogList: Array<TypeMblog>, userInfo: TypeWeiboUserInfo) { // 其次, 按天分隔微博 let mblogListByMergeBy: Map<string, TypeWeiboListByDay> = new Map() let index = 0 for (let mblog of mblogList) { index++ let splitByStr = '' let mblogCreateAtTimestamp = <number>mblog.created_timestamp_at // 按日期分页 splitByStr = moment.unix(mblogCreateAtTimestamp).format(this.CONST_CONFIG_DATE_FORMAT) let record = mblogListByMergeBy.get(splitByStr) if (record === undefined) { let a: TypeWeiboListByDay = { title: `${moment.unix(mblogCreateAtTimestamp).format(this.CONST_CONFIG_DATE_FORMAT)}`, dayStartAt: moment .unix(mblogCreateAtTimestamp) .startOf(DATE_FORMAT.UNIT.DAY) .unix(), weiboList: [mblog], splitByStr: splitByStr, postStartAt: mblogCreateAtTimestamp, postEndAt: mblogCreateAtTimestamp, } record = a } else { record.weiboList.push(mblog) // 更新文件标题 if (mblogCreateAtTimestamp > record.postEndAt) { record.postEndAt = mblogCreateAtTimestamp } if (mblogCreateAtTimestamp < record.postStartAt) { record.postStartAt = mblogCreateAtTimestamp record.dayStartAt = moment .unix(mblogCreateAtTimestamp) .startOf(DATE_FORMAT.UNIT.DAY) .unix() } } mblogListByMergeBy.set(splitByStr, record) } // 然后, 按日期先后对记录 let mblogListByDayList_OrderByPostStartAt = [] for (let record of mblogListByMergeBy.values()) { mblogListByDayList_OrderByPostStartAt.push(record) } // 按记录开始日期从早到晚排序 mblogListByDayList_OrderByPostStartAt.sort((a, b) => { return a.postStartAt - b.postStartAt }) // 解除引用依赖 mblogListByDayList_OrderByPostStartAt = _.cloneDeep(mblogListByDayList_OrderByPostStartAt) // 最后, 按条目数拆分微博记录, 将微博列表分包 let rawWeiboEpubList: Array<TypeWeiboEpub> = [] // book index 应该从1开始 let bookIndex = 1 let bookCounter = 1 let weiboEpubTemplate: TypeWeiboEpub = { bookIndex: bookIndex, startDayAt: 0, endDayAt: 0, userInfo: userInfo, screenName: userInfo.screen_name, weiboDayList: [], totalBookCount: 0, mblogInThisBookCount: 0, totalMblogCount: mblogList.length, } let weiboEpub = _.cloneDeep(weiboEpubTemplate) let bufEndDayAt = moment().unix() // 将按时间顺序排列的日级别微博记录, 处理为电子书数据包 for (let mblogListByDay of mblogListByDayList_OrderByPostStartAt) { // 备份一下, 循环结束时使用 bufEndDayAt = mblogListByDay.postEndAt if (weiboEpub.weiboDayList.length === 0) { // 首次添加 weiboEpub.weiboDayList.push(mblogListByDay) weiboEpub.mblogInThisBookCount = mblogListByDay.weiboList.length weiboEpub.startDayAt = mblogListByDay.dayStartAt weiboEpub.bookIndex = bookIndex } else { // 首先检测是否超过了单卷最大数量(超过10000条, 由于pdf生成库本身的限制, 会导致pdf生成速度巨慢) if (weiboEpub.mblogInThisBookCount > Const_Max_Mblog_In_Single_Book) { // 超出单卷最大微博数, 需要进行分卷 weiboEpub.endDayAt = weiboEpub.weiboDayList[weiboEpub.weiboDayList.length - 1].postEndAt let buffer = _.cloneDeep(weiboEpub) rawWeiboEpubList.push(buffer) // 重新起一个 bookCounter = bookCounter + 1 bookIndex = bookIndex + 1 weiboEpub = _.cloneDeep(weiboEpubTemplate) // 初始化新容器 weiboEpub.startDayAt = mblogListByDay.dayStartAt weiboEpub.bookIndex = bookIndex } else { // 然后在考虑其他情况 if (this.CUSTOMER_CONFIG_volumeSplitBy !== 'single') { // 如果分卷依据不是single, 那么要先按照设定的分卷条件, 检查是否需要进行分卷 switch (this.CUSTOMER_CONFIG_volumeSplitBy) { case 'year': { if (moment.unix(weiboEpub.startDayAt).format("YYYY") !== moment.unix(mblogListByDay.dayStartAt).format("YYYY")) { // 发生换年, 需要进行分卷 weiboEpub.endDayAt = weiboEpub.weiboDayList[weiboEpub.weiboDayList.length - 1].postEndAt let buffer = _.cloneDeep(weiboEpub) rawWeiboEpubList.push(buffer) // 重新起一个 bookCounter = bookCounter + 1 bookIndex = bookIndex + 1 weiboEpub = _.cloneDeep(weiboEpubTemplate) // 初始化新容器 weiboEpub.startDayAt = mblogListByDay.dayStartAt weiboEpub.bookIndex = bookIndex } } break; case 'month': { if (moment.unix(weiboEpub.startDayAt).format("YYYY-MM") !== moment.unix(mblogListByDay.dayStartAt).format("YYYY-MM")) { // 发生换月, 需要进行分卷 weiboEpub.endDayAt = weiboEpub.weiboDayList[weiboEpub.weiboDayList.length - 1].postEndAt let buffer = _.cloneDeep(weiboEpub) rawWeiboEpubList.push(buffer) // 重新起一个 bookCounter = bookCounter + 1 bookIndex = bookIndex + 1 weiboEpub = _.cloneDeep(weiboEpubTemplate) // 初始化新容器 weiboEpub.startDayAt = mblogListByDay.dayStartAt weiboEpub.bookIndex = bookIndex } } break; case 'count': default: { if (weiboEpub.mblogInThisBookCount > this.CUSTOMER_CONFIG_volumeSplitCount) { // 超出单卷最大微博数, 需要进行分卷 weiboEpub.endDayAt = weiboEpub.weiboDayList[weiboEpub.weiboDayList.length - 1].postEndAt let buffer = _.cloneDeep(weiboEpub) rawWeiboEpubList.push(buffer) // 重新起一个 bookCounter = bookCounter + 1 bookIndex = bookIndex + 1 weiboEpub = _.cloneDeep(weiboEpubTemplate) // 初始化新容器 weiboEpub.startDayAt = mblogListByDay.dayStartAt weiboEpub.bookIndex = bookIndex } } } } } weiboEpub.weiboDayList.push(mblogListByDay) weiboEpub.mblogInThisBookCount = weiboEpub.mblogInThisBookCount + mblogListByDay.weiboList.length } } // 循环结束, 记录最后一卷数据 weiboEpub.endDayAt = bufEndDayAt let buffer = _.cloneDeep(weiboEpub) rawWeiboEpubList.push(buffer) // 最后, 格式化一下代码 let weiboEpubList = [] for (let record of rawWeiboEpubList) { record.totalBookCount = bookCounter weiboEpubList.push(_.cloneDeep(record)) } // 得到最终结果, 可以渲染电子书了 return weiboEpubList } /** * 生成电子书(html/pdf) * @param bookCounter * @param bookname * @param epubResourcePackage */ async asyncGenerateEbook(bookCounter: number, bookname: string, epubResourcePackage: TypeWeiboEpub) { // 初始化资源, 重置所有静态类变量 this.bookname = StringUtil.encodeFilename(`${bookname}`) // 重载基类中的imageQuilty this.imageQuilty = this.CUSTOMER_CONFIG_imageQuilty let { weiboDayList } = epubResourcePackage this.imgUriPool = new Set() // 若配置跳过图片缓存, 则重置 if (this.CUSTOMER_CONFIG_isRegenerateHtml2PdfImage) { this.log(`配置了重新生成将html转为pdf的图片, 清空pdf图片生成缓存`) this.resetHtml2pdfImageCache() } // 初始化文件夹 this.initStaticRecource() this.log(`生成微博记录html列表`) let htmlUriList = [] let recordCounter = 0 for (let weiboDayRecord of weiboDayList) { // 生成前一页, 后一页导航栏 recordCounter++ let beforeRecord = weiboDayList[recordCounter - 2] let nextRecord = weiboDayList[recordCounter] let title = weiboDayRecord.title let content = WeiboView.render(weiboDayRecord.weiboList, { renderGuideLine: true, nextRecord: nextRecord, beforeRecord: beforeRecord }) content = this.processContent(content) let htmlUri = path.resolve(this.htmlCacheHtmlPath, `${title}.html`) fs.writeFileSync(htmlUri, content) // 渲染页面 htmlUriList.push(htmlUri) } // 生成目录 this.log(`生成目录`) let indexContent = BaseView.renderIndex(this.bookname, weiboDayList) fs.writeFileSync(path.resolve(this.htmlCacheHtmlPath, `index.html`), indexContent) // 处理静态资源 await this.asyncProcessStaticResource() if (this.CUSTOMER_CONFIG_isSkipGeneratePdf) { this.log(`isSkipGeneratePdf为${this.CUSTOMER_CONFIG_isSkipGeneratePdf}, 自动跳过pdf输出阶段`) } else { let weiboDayConfigList = await this.transWeiboDayList2Image(weiboDayList) // 保存配置,方便调试 fs.writeFileSync(path.resolve(this.html2ImageCache_ImagePath, `output.json`), JSON.stringify(weiboDayConfigList)) await this.generatePdf(weiboDayConfigList) } // 输出完毕后, 将结果复制到dist文件夹中 await this.asyncCopyToDist() this.log(`第${bookCounter}本电子书${this.bookname}生成完毕`) } async transWeiboDayList2Image(weiboDayList: TypeWeiboEpub['weiboDayList']) { // 首先生成单条微博对应的静态html文件, 以及对应配置 let dayIndex = 0 let weiboDayConfigList: TypeTransConfigPackageList = [] for (let weiboDayRecord of weiboDayList) { dayIndex++ this.log(`开始将记录${weiboDayRecord.title}(第${dayIndex}/${weiboDayList.length}项)下的微博渲染为图片`) let weiboRecordImgList: TypeTransConfigPackage = { title: weiboDayRecord.title, dayIndex, postStartAt: weiboDayRecord.postStartAt, postEndAt: weiboDayRecord.postEndAt, configList: [] } let weiboIndex = 0 for (let weiboRecord of weiboDayRecord.weiboList) { weiboIndex++ this.log( `将记录${weiboDayRecord.title}(第${dayIndex}/${weiboDayList.length}项)下第${weiboIndex}/${weiboDayRecord.weiboList.length}条微博渲染为图片`, ) let { htmlUri, imageUriList, htmlContent } = await this.transWeiboRecord2Image(weiboRecord) let transConfigItem: TypeTransConfigItem = { dayIndex, weiboIndex, htmlUri, imageUriList, htmlContent }; weiboRecordImgList.configList.push(transConfigItem) } weiboDayConfigList.push(weiboRecordImgList) } // 处理完毕, 返回配置内容 return weiboDayConfigList } async transWeiboRecord2Image(weiboRecord: TypeMblog) { // 以微博创建时间和微博id作为唯一key let baseFileTitle = `${moment.unix(weiboRecord.created_timestamp_at).format("YYYY-MM-DD HH:mm:ss")}_${weiboRecord.id}` let htmlUri = path.resolve(this.html2ImageCache_HtmlPath, `${baseFileTitle}.html`) let imageUriList: string[] = [] let baseImageUri = path.resolve(this.html2ImageCache_ImagePath, `${baseFileTitle}_`) let content = WeiboView.render([weiboRecord]) content = this.processContent(content) let transConfigItem = { htmlUri, imageUriList, htmlContent: content } for (let i = 0; i < 20; i++) { imageUriList.push(baseImageUri + `${i}.jpg`) } let existUriList: string[] = [] for (let checkImgUri of imageUriList) { // 若已生成过文件, 则不需要重新生成, 自动跳过即可 // 只要有一个文件生成, 就视为已生成 if (fs.existsSync(checkImgUri)) { existUriList.push(checkImgUri) } else { // 到第一个不存在的图片自动停止 break; } } if (existUriList.length > 0) { // 只要有一张图片存在, 就视为渲染成功 transConfigItem.imageUriList = existUriList return transConfigItem } fs.writeFileSync(htmlUri, content) { // 渲染图片, 重复尝试3次, 避免因为意外导致js执行超时 let { imageUriList, isRenderSuccess } = await this.html2Image(htmlUri, baseImageUri) if (isRenderSuccess === true) { transConfigItem.imageUriList = imageUriList return transConfigItem } } this.log(`${transConfigItem.htmlUri}第1次渲染失败, 渲染时间超过${Const_Render_Html_Timeout_Second}s, 自动退出. 进行第2次尝试`) { let { imageUriList, isRenderSuccess } = await this.html2Image(htmlUri, baseImageUri) if (isRenderSuccess === true) { this.log(`${transConfigItem.htmlUri}渲染成功`) transConfigItem.imageUriList = imageUriList return transConfigItem } } this.log(`${transConfigItem.htmlUri}第2次渲染失败, 渲染时间超过${Const_Render_Html_Timeout_Second}s, 自动退出. 进行第2次尝试`) { let { imageUriList, isRenderSuccess } = await this.html2Image(htmlUri, baseImageUri) if (isRenderSuccess === true) { this.log(`${transConfigItem.htmlUri}渲染成功`) transConfigItem.imageUriList = imageUriList return transConfigItem } } this.log(`${transConfigItem.htmlUri}第3次渲染失败, 渲染时间超过${Const_Render_Html_Timeout_Second}s, 自动退出. 不再尝试`) // 每生成一张图片休眠1s, 避免界面卡死 await CommonUtil.asyncSleep(1000 * 0.1) return transConfigItem } /** * 将html渲染为图片, 成功返回true, 渲染失败或超时返回false * @param pageConfig */ async html2Image(htmlUri: string, baseImageUri: string): Promise<{ imageUriList: string[], isRenderSuccess: boolean }> { let webview = globalSubWindow.webContents; let subWindow = globalSubWindow if (htmlUri.startsWith("file://") === false && htmlUri.startsWith("http://") === false) { // mac上载入文件时, 必须要有file://前缀 htmlUri = 'file://' + htmlUri } return await new Promise((reslove, reject) => { let timmerId = setTimeout(() => { // 增加20s超时退出限制 globalSubWindow.reload() reslove({ imageUriList: [], isRenderSuccess: false }) }, Const_Render_Html_Timeout_Second * 1000) let render = async () => { // this.log("load url -> ", pageConfig.htmlUri) await webview.loadURL(htmlUri); // this.log("setContentSize -> ", Const_Default_Webview_Width, Const_Default_Webview_Height) await globalSubWindow.setContentSize( Const_Default_Webview_Width, Const_Default_Webview_Height, ); // @alert 注意, 在这里有可能卡死, 表现为卡住停止执行. 所以需要在外部加一个超时限制 // this.log("resize page, executeJavaScript ") let scrollHeight = await webview.executeJavaScript( `document.children[0].children[1].scrollHeight`, ); let imageUriList: string[] = [] if (scrollHeight > Const_Max_Webview_Render_Height_Px) { // html页面太大, 需要分页输出, 最后再合成一张图片返回 let imgContentList: { input: Buffer, top: number, left: 0, // 本张图片高度 imgHeightPx: number, }[] = [] let remainHeight = scrollHeight await subWindow.setContentSize(Const_Default_Webview_Width, Const_Max_Webview_Render_Height_Px); while (remainHeight >= Const_Max_Webview_Render_Height_Px) { let imgIndex = imgContentList.length; let currentOffsetHeight = Const_Max_Webview_Render_Height_Px * imgIndex // 先移动到offset高度 let command = `document.children[0].children[1].scrollTop = ${currentOffsetHeight}` await webview.executeJavaScript(command); // 然后对界面截屏 // js指令执行后, 滚动到指定位置还需要时间, 所以截屏前需要sleep一下 await CommonUtil.asyncSleep(1000 * 0.2) let nativeImg = await webview.capturePage(); let content = await nativeImg.toJPEG(100) if (Is_Normal_Display_Rate === false) { // 不等于1则需要缩放 content = await sharp(content).resize(Const_Default_Webview_Width).toBuffer() } remainHeight = remainHeight - Const_Max_Webview_Render_Height_Px imgContentList.push( { input: content, top: Const_Max_Webview_Render_Height_Px * imgIndex, left: 0, imgHeightPx: Const_Max_Webview_Render_Height_Px, } ) } if (remainHeight > 0) { // 最后捕捉剩余高度页面 // 首先调整页面高度 await subWindow.setContentSize(Const_Default_Webview_Width, remainHeight); // 然后走流程, 捕捉界面 let currentOffsetHeight = Const_Max_Webview_Render_Height_Px * imgContentList.length let imgIndex = imgContentList.length; // 先移动到offset高度 let command = `document.children[0].children[1].scrollTop = ${currentOffsetHeight}` await webview.executeJavaScript(command); // 然后对界面截屏 // js指令执行后, 滚动到指定位置还需要时间, 所以截屏前需要sleep一下 await CommonUtil.asyncSleep(1000 * 0.2) let nativeImg = await webview.capturePage(); let content = await nativeImg.toJPEG(100) if (Is_Normal_Display_Rate === false) { // 不等于1则需要缩放 content = await sharp(content).resize(Const_Default_Webview_Width).toBuffer() } imgContentList.push( { input: content, top: Const_Max_Webview_Render_Height_Px * imgIndex, left: 0, imgHeightPx: remainHeight, } ) } // 拿到所有分页图后, 将图片分组合并 let currentTotalHeight = 0; let currentImgContentList: any[] = []; let currentImgIndex = 0; let currentHeightOffset = 0 // 先颠倒一下, 方便pop imgContentList.reverse() while (imgContentList.length > 0) { let item = imgContentList.pop() let rawTop = item!.top let rawImgHeightPx = item!.imgHeightPx // 高度差需要减去偏移量 item!.top = item!.top - currentHeightOffset currentTotalHeight += item!.imgHeightPx currentImgContentList.push(item) // 对元素分组处理 if (currentTotalHeight > Const_Max_Jpge_Height_In_Sharp_Px) { // 保存偏移量, 下一组元素要统一减去上一组的偏移量 currentHeightOffset = rawTop + rawImgHeightPx let imgUri = baseImageUri + `${currentImgIndex}.jpg` let mergeImg = sharp({ create: { width: Const_Default_Webview_Width, height: currentTotalHeight, channels: 4, background: { r: 255, g: 255, b: 255, alpha: 1, }, } }).jpeg() mergeImg.composite( currentImgContentList ) let jpgContent = await mergeImg.toBuffer().catch(e => { this.log("mergeImg error => ", e) return new Buffer("") }) let out = mozjpeg.encode(jpgContent, { //处理质量 百分比 quality: 80 }); jpgContent = out.data fs.writeFileSync( path.resolve(imgUri), jpgContent, ); imageUriList.push(imgUri) currentImgIndex = currentImgIndex + 1 currentTotalHeight = 0 currentImgContentList = [] } } // 处理剩余元素 if (currentImgContentList.length > 0) { let imgUri = baseImageUri + `${currentImgIndex}.jpg` let mergeImg = sharp({ create: { width: Const_Default_Webview_Width, height: currentTotalHeight, channels: 4, background: { r: 255, g: 255, b: 255, alpha: 1, }, } }).jpeg() mergeImg.composite( currentImgContentList ) let jpgContent = await mergeImg.toBuffer().catch(e => { this.log("mergeImg error => ", e) return new Buffer("") }) let out = mozjpeg.encode(jpgContent, { //处理质量 百分比 quality: 80 }); jpgContent = out.data fs.writeFileSync( path.resolve(imgUri), jpgContent, ); imageUriList.push(imgUri) currentImgIndex = currentImgIndex + 1 currentTotalHeight = 0 currentImgContentList = [] } } else { // 小于最大宽度, 只要截屏一次就可以 await subWindow.setContentSize(Const_Default_Webview_Width, scrollHeight); // this.log("setContentSize with scrollHeight -> ", scrollHeight) let nativeImg = await webview.capturePage(); let jpgContent = await nativeImg.toJPEG(100); if (Is_Normal_Display_Rate === false) { // 不等于1则需要缩放 jpgContent = await sharp(jpgContent).resize(Const_Default_Webview_Width).toBuffer() } let out = mozjpeg.encode(jpgContent, { //处理质量 百分比 quality: 80 }); jpgContent = out.data let imageUri = baseImageUri + '0.jpg' fs.writeFileSync( path.resolve(imageUri), jpgContent, ); imageUriList.push(imageUri) } // this.log(`jpgContent 输出完毕. length => ${jpgContent.length}`) // this.log('generateImage complete'); // 每张图片最大渲染时间不能超过10s clearTimeout(timmerId) reslove({ imageUriList, isRenderSuccess: true }) } render() }) } async generatePdf(weiboDayList: TypeTransConfigPackageList) { let doc = new jsPDF({ unit: 'px', format: [Const_Default_Webview_Width, 500], orientation: "landscape" }) let fontUri = path.resolve(__dirname, '../../public/font/alibaba_PuHuiTi_Regular.ttf') let fontContent = fs.readFileSync(fontUri) let fontName = "alibaba_PuHuiTi_Regular" doc.addFileToVFS(`${fontName}.ttf`, fontContent.toString("base64")) doc.addFont(`${fontName}.ttf`, fontName, "normal") doc.setFont(fontName, "normal"); doc.setFontSize(32) // demo => yaozeyuan93-微博整理-第1/2卷-(2011-07-07~2012-01-25) let rawBooktitle = this.bookname let contentList = rawBooktitle.split(`-微博整理-`) let accountName = contentList[0] let timeRangeStartAt = contentList[1].indexOf('(') let timeRangeEndAt = contentList[1].indexOf(')') let timeRangeStr = contentList[1].slice(timeRangeStartAt + '('.length, timeRangeEndAt) let columnStartAt = contentList[1].indexOf('第') let columnEndAt = contentList[1].indexOf('卷') let columnStr = '' if (columnStartAt >= 0) { // 先把关键语句提取出来, 后续根据需要再处理 columnStr = contentList[1].slice(columnStartAt + '第'.length, columnEndAt) columnStr = `-第${columnStr}卷` } let lineAt = 0 let lineHeight = 40 let paddingLeft = Const_Default_Webview_Width / 2 function addLine(content: string) { lineAt = lineAt + 1 doc.text(content, paddingLeft, lineHeight * lineAt, { align: 'center', }) } function addLink(content: string) { lineAt = lineAt + 1 doc.setTextColor("blue") doc.textWithLink(content, paddingLeft, lineHeight * lineAt, { align: 'center', url: content }) } addLine("") addLine(accountName) addLine(`微博整理${columnStr}`) addLine(timeRangeStr) addLine("") addLine("该文件由稳部落自动生成") addLine("") addLine("项目主页") addLink("https://www.yaozeyuan.online/stablog") let currentPageNo = 2 let outlineConfigList: { title: string, pageNo: number, }[] = [] // 先加一页, 避免出现空白页 let dayIndex = 0 for (let weiboDayRecord of weiboDayList) { dayIndex++ this.log(`将页面${weiboDayRecord.title}(第${dayIndex}/${weiboDayList.length}项)添加到pdf文件中`) let weiboIndex = 0 outlineConfigList.push({ title: weiboDayRecord.title, pageNo: currentPageNo, }) for (let weiboRecord of weiboDayRecord.configList) { weiboIndex++ this.log( `正在添加页面${weiboDayRecord.title}(第${dayIndex}/${weiboDayList.length}项)下,第${weiboIndex}/${weiboDayRecord.configList.length}条微博`, ) for (let i = 0; i < weiboRecord.imageUriList.length; i++) { let imgUri = weiboRecord.imageUriList[i]; if (fs.existsSync(imgUri) === false) { // 图片本身不存在, 说明渲染失败 this.log(`第${weiboIndex}/${weiboDayRecord.configList.length}条微博渲染失败, 自动跳过`) continue } else { let imageBuffer = fs.readFileSync(imgUri) let size = await imageSize.imageSize(imageBuffer) let { width, height } = size if (!width || width <= 0 || !height || height <= 0) { this.log(`第${weiboIndex}/${weiboDayRecord.configList.length}条微博截图捕获失败, 自动跳过`) continue } doc.addPage([width, height], width > height ? "landscape" : "portrait") doc.addImage( { imageData: imageBuffer, x: 0, y: 0, width: width, height: height }) if (i === 0) { // 只在第一页添加文字 doc.setFontSize(0.001) doc.text(weiboRecord.htmlContent, 0, 0, { // align: 'center', }) } currentPageNo = currentPageNo + 1 if (currentPageNo % 10 === 0) { // 休眠0.1秒, 避免因频繁添加页面导致界面卡死 await CommonUtil.asyncSleep(1000 * 0.1) } } } } } // 开始补充导航栏 var node = doc.outline.add(null, '首页', { pageNumber: 1 }); // 通过hack的方式, 生成年月日三级目录 type Type_Node = { node: any, pageNo: number, children: { [key: string]: Type_Node } } let node_map: { [year: string]: Type_Node } = {} for (let outlineConfig of outlineConfigList) { let [year, month, day] = outlineConfig.title.split('-'); if (node_map[year] === undefined) { // 初始化年份 let yearNode = doc.outline.add(node, year, { pageNumber: outlineConfig.pageNo }); node_map[year] = { node: yearNode, pageNo: outlineConfig.pageNo, children: {} } let monthNode = doc.outline.add(yearNode, `${year}-${month}`, { pageNumber: outlineConfig.pageNo }); node_map[year] = { node: yearNode, pageNo: outlineConfig.pageNo, children: { [month]: { node: monthNode, pageNo: outlineConfig.pageNo, children: {} } } } let dayNode = doc.outline.add(monthNode, `${year}-${month}-${day}`, { pageNumber: outlineConfig.pageNo }); node_map[year] = { node: yearNode, pageNo: outlineConfig.pageNo, children: { [month]: { node: monthNode, pageNo: outlineConfig.pageNo, children: { [day]: { node: dayNode, pageNo: outlineConfig.pageNo, children: {} } } } } } continue; } if (node_map[year]['children'][month] === undefined) { // 初始化月份 let yearNode = node_map[year]['node'] let monthNode = doc.outline.add(yearNode, `${year}-${month}`, { pageNumber: outlineConfig.pageNo }); node_map[year]['children'][month] = { node: monthNode, pageNo: outlineConfig.pageNo, children: {} } let dayNode = doc.outline.add(monthNode, `${year}-${month}-${day}`, { pageNumber: outlineConfig.pageNo }); node_map[year]['children'][month]['children'][day] = { node: dayNode, pageNo: outlineConfig.pageNo, children: {} } continue; } // 否则, 添加日期节点 let yearNode = node_map[year]['node'] let monthNode = node_map[year]['children'][month]['node'] let dayNode = doc.outline.add(monthNode, `${year}-${month}-${day}`, { pageNumber: outlineConfig.pageNo }); node_map[year]['children'][month]['children'][day] = { node: dayNode, pageNo: outlineConfig.pageNo, children: {} } } await doc.save(path.resolve(this.htmlCachePdfPath, `${this.bookname}.pdf`), { returnPromise: true }) this.log(`pdf输出完毕`) } } export default GenerateCustomer
the_stack
import { Blob } from "./Blob"; import { GDIContext } from "./GDIContext"; import { EMFJSError, Helper } from "./Helper"; import { PointL, PointS, RectL, SizeL } from "./Primitives"; import { Region } from "./Region"; import { Brush, ColorRef, Pen } from "./Style"; class EmfHeader { private size: number; private bounds: RectL; private frame: RectL; private nPalEntries: number; private refDevCx: number; private refDevCy: number; private refDevCxMm: number; private refDevCyMm: number; private description: string; private displayDevCxUm: number; private displayDevCyUm: number; constructor(reader: Blob, headerSize: number) { const recordStart = reader.pos - 8; this.size = headerSize; this.bounds = new RectL(reader); this.frame = new RectL(reader); if (reader.readUint32() !== Helper.GDI.FormatSignature.ENHMETA_SIGNATURE) { throw new EMFJSError("Invalid header signature"); } reader.skip(4); // version reader.skip(4); // bytes (size of metafile) reader.skip(4); // number of records reader.skip(2); // number of handles reader.skip(2); // reserved const descriptionLen = reader.readUint32(); const descriptionOff = reader.readUint32(); this.nPalEntries = reader.readUint32(); this.refDevCx = reader.readUint32(); this.refDevCy = reader.readUint32(); this.refDevCxMm = reader.readUint32(); this.refDevCyMm = reader.readUint32(); let hdrSize = headerSize; if (descriptionLen > 0) { if (descriptionOff < 88) { throw new EMFJSError("Invalid header description offset"); } hdrSize = descriptionOff + (descriptionLen * 2); if (hdrSize > headerSize) { throw new EMFJSError("Invalid header description length"); } const prevPos = reader.pos; reader.seek(recordStart + descriptionOff); this.description = reader.readFixedSizeUnicodeString(descriptionLen); reader.seek(prevPos); } else { this.description = ""; } if (hdrSize >= 100) { // We have a EmfMetafileHeaderExtension1 record const pixelFormatSize = reader.readUint32(); const pixelFormatOff = reader.readUint32(); const haveOpenGl = reader.readUint32(); if (haveOpenGl !== 0) { throw new EMFJSError("OpenGL records are not yet supported"); } if (pixelFormatOff !== 0) { if (pixelFormatOff < 100 || pixelFormatOff < hdrSize) { throw new EMFJSError("Invalid pixel format offset"); } hdrSize = pixelFormatOff + pixelFormatSize; if (hdrSize > headerSize) { throw new EMFJSError("Invalid pixel format size"); } // TODO: read pixel format blob } if (hdrSize >= 108) { // We have a EmfMetafileHeaderExtension2 record this.displayDevCxUm = reader.readUint32(); // in micrometers this.displayDevCyUm = reader.readUint32(); // in micrometers } } } public toString(): string { return "{bounds: " + this.bounds.toString() + ", frame: " + this.frame.toString() + ", description: " + this.description + "}"; } } export class EMFRecords { private _records: ((gdi: GDIContext) => void)[]; private _header: EmfHeader; constructor(reader: Blob, first: number) { this._records = []; this._header = new EmfHeader(reader, first); let all = false; let curpos = first; main_loop: while (!all) { reader.seek(curpos); const type = reader.readUint32(); const size = reader.readUint32(); if (size < 8) { throw new EMFJSError("Invalid record size"); } switch (type) { case Helper.GDI.RecordType.EMR_EOF: all = true; break main_loop; case Helper.GDI.RecordType.EMR_SETMAPMODE: { const mapMode = reader.readInt32(); this._records.push((gdi) => { gdi.setMapMode(mapMode); }); break; } case Helper.GDI.RecordType.EMR_SETWINDOWORGEX: { const x = reader.readInt32(); const y = reader.readInt32(); this._records.push((gdi) => { gdi.setWindowOrgEx(x, y); }); break; } case Helper.GDI.RecordType.EMR_SETWINDOWEXTEX: { const x = reader.readUint32(); const y = reader.readUint32(); this._records.push((gdi) => { gdi.setWindowExtEx(x, y); }); break; } case Helper.GDI.RecordType.EMR_SETVIEWPORTORGEX: { const x = reader.readInt32(); const y = reader.readInt32(); this._records.push((gdi) => { gdi.setViewportOrgEx(x, y); }); break; } case Helper.GDI.RecordType.EMR_SETVIEWPORTEXTEX: { const x = reader.readUint32(); const y = reader.readUint32(); this._records.push((gdi) => { gdi.setViewportExtEx(x, y); }); break; } case Helper.GDI.RecordType.EMR_SAVEDC: { this._records.push((gdi) => { gdi.saveDC(); }); break; } case Helper.GDI.RecordType.EMR_RESTOREDC: { const saved = reader.readInt32(); this._records.push((gdi) => { gdi.restoreDC(saved); }); break; } case Helper.GDI.RecordType.EMR_SETBKMODE: { const bkMode = reader.readUint32(); this._records.push((gdi) => { gdi.setBkMode(bkMode); }); break; } case Helper.GDI.RecordType.EMR_SETBKCOLOR: { const bkColor = new ColorRef(reader); this._records.push((gdi) => { gdi.setBkColor(bkColor); }); break; } case Helper.GDI.RecordType.EMR_CREATEBRUSHINDIRECT: { const index = reader.readUint32(); const brush = new Brush(reader); this._records.push((gdi) => { gdi.createBrush(index, brush); }); break; } case Helper.GDI.RecordType.EMR_CREATEPEN: { const index = reader.readUint32(); const pen = new Pen(reader, null); this._records.push((gdi) => { gdi.createPen(index, pen); }); break; } case Helper.GDI.RecordType.EMR_EXTCREATEPEN: { const index = reader.readUint32(); const offBmi = reader.readUint32(); const cbBmi = reader.readUint32(); const offBits = reader.readUint32(); const cbBits = reader.readUint32(); const pen = new Pen(reader, { header: { off: offBmi, size: cbBmi, }, data: { off: offBits, size: cbBits, }, }); this._records.push((gdi) => { gdi.createPen(index, pen); }); break; } case Helper.GDI.RecordType.EMR_SELECTOBJECT: { const idx = reader.readUint32(); this._records.push((gdi) => { gdi.selectObject(idx, null); }); break; } case Helper.GDI.RecordType.EMR_DELETEOBJECT: { const idx = reader.readUint32(); this._records.push((gdi) => { gdi.deleteObject(idx); }); break; } case Helper.GDI.RecordType.EMR_RECTANGLE: { const rect = new RectL(reader); this._records.push((gdi) => { gdi.rectangle(rect, 0, 0); }); break; } case Helper.GDI.RecordType.EMR_ROUNDRECT: { const rect = new RectL(reader); const corner = new SizeL(reader); this._records.push((gdi) => { gdi.rectangle(rect, corner.cx, corner.cy); }); break; } case Helper.GDI.RecordType.EMR_LINETO: { const x = reader.readInt32(); const y = reader.readInt32(); this._records.push((gdi) => { gdi.lineTo(x, y); }); break; } case Helper.GDI.RecordType.EMR_MOVETOEX: { const x = reader.readInt32(); const y = reader.readInt32(); this._records.push((gdi) => { gdi.moveToEx(x, y); }); break; } case Helper.GDI.RecordType.EMR_POLYGON: case Helper.GDI.RecordType.EMR_POLYGON16: { const isSmall = (type === Helper.GDI.RecordType.EMR_POLYGON16); const bounds = new RectL(reader); let cnt = reader.readUint32(); const points: PointS[] | PointL[] = []; while (cnt > 0) { points.push(isSmall ? new PointS(reader) : new PointL(reader)); cnt--; } this._records.push((gdi) => { gdi.polygon(points, bounds, true); }); break; } case Helper.GDI.RecordType.EMR_POLYPOLYGON: case Helper.GDI.RecordType.EMR_POLYPOLYGON16: { const isSmall = (type === Helper.GDI.RecordType.EMR_POLYPOLYGON16); const bounds = new RectL(reader); const polyCnt = reader.readUint32(); reader.skip(4); // count const polygonsPtCnts = []; for (let i = 0; i < polyCnt; i++) { polygonsPtCnts.push(reader.readUint32()); } const polygons: PointS[][] | PointL[][] = []; for (let i = 0; i < polyCnt; i++) { const ptCnt = polygonsPtCnts[i]; const p = []; for (let ip = 0; ip < ptCnt; ip++) { p.push(isSmall ? new PointS(reader) : new PointL(reader)); } polygons.push(p); } this._records.push((gdi) => { gdi.polyPolygon(polygons, bounds); }); break; } case Helper.GDI.RecordType.EMR_SETPOLYFILLMODE: { const polyfillmode = reader.readUint32(); this._records.push((gdi) => { gdi.setPolyFillMode(polyfillmode); }); break; } case Helper.GDI.RecordType.EMR_POLYLINE16: case Helper.GDI.RecordType.EMR_POLYLINETO16: { const isLineTo = (type === Helper.GDI.RecordType.EMR_POLYLINETO16); const bounds = new RectL(reader); let cnt = reader.readUint32(); const points: PointS[] = []; while (cnt > 0) { points.push(new PointS(reader)); cnt--; } this._records.push((gdi) => { gdi.polyline(isLineTo, points, bounds); }); break; } case Helper.GDI.RecordType.EMR_POLYBEZIER: case Helper.GDI.RecordType.EMR_POLYBEZIERTO: { const isPolyBezierTo = (type === Helper.GDI.RecordType.EMR_POLYBEZIERTO); const bounds = new RectL(reader); let cnt = reader.readUint32(); const points: PointL[] = []; while (cnt > 0) { points.push(new PointL(reader)); cnt--; } this._records.push((gdi) => { gdi.polybezier(isPolyBezierTo, points, bounds); }); break; } case Helper.GDI.RecordType.EMR_POLYBEZIER16: { const bounds = new RectL(reader); const start = new PointL(reader); let cnt = reader.readUint32(); const points = [start]; while (cnt > 0) { points.push(new PointS(reader)); cnt--; } this._records.push((gdi) => { gdi.polybezier(false, points, bounds); }); break; } case Helper.GDI.RecordType.EMR_POLYBEZIERTO16: { const bounds = new RectL(reader); let cnt = reader.readUint32(); const points: PointS[] = []; while (cnt > 0) { points.push(new PointS(reader)); cnt--; } this._records.push((gdi) => { gdi.polybezier(true, points, bounds); }); break; } case Helper.GDI.RecordType.EMR_SETTEXTALIGN: { const textAlign = reader.readUint32(); this._records.push((gdi) => { gdi.setTextAlign(textAlign); }); break; } case Helper.GDI.RecordType.EMR_SETSTRETCHBLTMODE: { const stretchMode = reader.readUint32(); this._records.push((gdi) => { gdi.setStretchBltMode(stretchMode); }); break; } case Helper.GDI.RecordType.EMR_SETBRUSHORGEX: { const origin = new PointL(reader); this._records.push((gdi) => { gdi.setBrushOrgEx(origin); }); break; } case Helper.GDI.RecordType.EMR_BEGINPATH: { this._records.push((gdi) => { gdi.beginPath(); }); break; } case Helper.GDI.RecordType.EMR_ENDPATH: { this._records.push((gdi) => { gdi.endPath(); }); break; } case Helper.GDI.RecordType.EMR_ABORTPATH: { this._records.push((gdi) => { gdi.abortPath(); }); break; } case Helper.GDI.RecordType.EMR_CLOSEFIGURE: { this._records.push((gdi) => { gdi.closeFigure(); }); break; } case Helper.GDI.RecordType.EMR_FILLPATH: { const bounds = new RectL(reader); this._records.push((gdi) => { gdi.fillPath(bounds); }); break; } case Helper.GDI.RecordType.EMR_STROKEPATH: { const bounds = new RectL(reader); this._records.push((gdi) => { gdi.strokePath(bounds); }); break; } case Helper.GDI.RecordType.EMR_SELECTCLIPPATH: { const rgnMode = reader.readUint32(); this._records.push((gdi) => { gdi.selectClipPath(rgnMode); }); break; } case Helper.GDI.RecordType.EMR_EXTSELECTCLIPRGN: { reader.skip(4); const rgnMode = reader.readUint32(); const region = rgnMode !== Helper.GDI.RegionMode.RGN_COPY ? new Region(reader) : null; this._records.push((gdi) => { gdi.selectClipRgn(rgnMode, region); }); break; } case Helper.GDI.RecordType.EMR_OFFSETCLIPRGN: { const offset = new PointL(reader); this._records.push((gdi) => { gdi.offsetClipRgn(offset); }); break; } case Helper.GDI.RecordType.EMR_SETMITERLIMIT: { const miterLimit = reader.readUint32(); this._records.push((gdi) => { gdi.setMiterLimit(miterLimit); }); break; } case Helper.GDI.RecordType.EMR_POLYLINE: case Helper.GDI.RecordType.EMR_POLYLINETO: case Helper.GDI.RecordType.EMR_POLYPOLYLINE: case Helper.GDI.RecordType.EMR_SETPIXELV: case Helper.GDI.RecordType.EMR_SETMAPPERFLAGS: case Helper.GDI.RecordType.EMR_SETROP2: case Helper.GDI.RecordType.EMR_SETCOLORADJUSTMENT: case Helper.GDI.RecordType.EMR_SETTEXTCOLOR: case Helper.GDI.RecordType.EMR_SETMETARGN: case Helper.GDI.RecordType.EMR_EXCLUDECLIPRECT: case Helper.GDI.RecordType.EMR_INTERSECTCLIPRECT: case Helper.GDI.RecordType.EMR_SCALEVIEWPORTEXTEX: case Helper.GDI.RecordType.EMR_SCALEWINDOWEXTEX: case Helper.GDI.RecordType.EMR_SETWORLDTRANSFORM: case Helper.GDI.RecordType.EMR_MODIFYWORLDTRANSFORM: case Helper.GDI.RecordType.EMR_ANGLEARC: case Helper.GDI.RecordType.EMR_ELLIPSE: case Helper.GDI.RecordType.EMR_ARC: case Helper.GDI.RecordType.EMR_CHORD: case Helper.GDI.RecordType.EMR_PIE: case Helper.GDI.RecordType.EMR_SELECTPALETTE: case Helper.GDI.RecordType.EMR_CREATEPALETTE: case Helper.GDI.RecordType.EMR_SETPALETTEENTRIES: case Helper.GDI.RecordType.EMR_RESIZEPALETTE: case Helper.GDI.RecordType.EMR_REALIZEPALETTE: case Helper.GDI.RecordType.EMR_EXTFLOODFILL: case Helper.GDI.RecordType.EMR_ARCTO: case Helper.GDI.RecordType.EMR_POLYDRAW: case Helper.GDI.RecordType.EMR_SETARCDIRECTION: case Helper.GDI.RecordType.EMR_STROKEANDFILLPATH: case Helper.GDI.RecordType.EMR_FLATTENPATH: case Helper.GDI.RecordType.EMR_WIDENPATH: case Helper.GDI.RecordType.EMR_COMMENT: case Helper.GDI.RecordType.EMR_FILLRGN: case Helper.GDI.RecordType.EMR_FRAMERGN: case Helper.GDI.RecordType.EMR_INVERTRGN: case Helper.GDI.RecordType.EMR_PAINTRGN: case Helper.GDI.RecordType.EMR_BITBLT: case Helper.GDI.RecordType.EMR_STRETCHBLT: case Helper.GDI.RecordType.EMR_MASKBLT: case Helper.GDI.RecordType.EMR_PLGBLT: case Helper.GDI.RecordType.EMR_SETDIBITSTODEVICE: case Helper.GDI.RecordType.EMR_STRETCHDIBITS: case Helper.GDI.RecordType.EMR_EXTCREATEFONTINDIRECTW: case Helper.GDI.RecordType.EMR_EXTTEXTOUTA: case Helper.GDI.RecordType.EMR_EXTTEXTOUTW: case Helper.GDI.RecordType.EMR_POLYPOLYLINE16: case Helper.GDI.RecordType.EMR_POLYDRAW16: case Helper.GDI.RecordType.EMR_CREATEMONOBRUSH: case Helper.GDI.RecordType.EMR_CREATEDIBPATTERNBRUSHPT: case Helper.GDI.RecordType.EMR_POLYTEXTOUTA: case Helper.GDI.RecordType.EMR_POLYTEXTOUTW: case Helper.GDI.RecordType.EMR_SETICMMODE: case Helper.GDI.RecordType.EMR_CREATECOLORSPACE: case Helper.GDI.RecordType.EMR_SETCOLORSPACE: case Helper.GDI.RecordType.EMR_DELETECOLORSPACE: case Helper.GDI.RecordType.EMR_GLSRECORD: case Helper.GDI.RecordType.EMR_GLSBOUNDEDRECORD: case Helper.GDI.RecordType.EMR_PIXELFORMAT: case Helper.GDI.RecordType.EMR_DRAWESCAPE: case Helper.GDI.RecordType.EMR_EXTESCAPE: case Helper.GDI.RecordType.EMR_SMALLTEXTOUT: case Helper.GDI.RecordType.EMR_FORCEUFIMAPPING: case Helper.GDI.RecordType.EMR_NAMEDESCAPE: case Helper.GDI.RecordType.EMR_COLORCORRECTPALETTE: case Helper.GDI.RecordType.EMR_SETICMPROFILEA: case Helper.GDI.RecordType.EMR_SETICMPROFILEW: case Helper.GDI.RecordType.EMR_ALPHABLEND: case Helper.GDI.RecordType.EMR_SETLAYOUT: case Helper.GDI.RecordType.EMR_TRANSPARENTBLT: case Helper.GDI.RecordType.EMR_GRADIENTFILL: case Helper.GDI.RecordType.EMR_SETLINKEDUFIS: case Helper.GDI.RecordType.EMR_SETTEXTJUSTIFICATION: case Helper.GDI.RecordType.EMR_COLORMATCHTOTARGETW: case Helper.GDI.RecordType.EMR_CREATECOLORSPACEW: default: { let recordName = "UNKNOWN"; for (const name in Helper.GDI.RecordType) { const recordTypes: any = Helper.GDI.RecordType; if (recordTypes[name] === type) { recordName = name; break; } } Helper.log("[EMF] " + recordName + " record (0x" + type.toString(16) + ") at offset 0x" + curpos.toString(16) + " with " + size + " bytes"); break; } } curpos += size; } if (!all) { throw new EMFJSError("Could not read all records"); } } public play(gdi: GDIContext): void { const len = this._records.length; for (let i = 0; i < len; i++) { this._records[i](gdi); } } }
the_stack
import { CodeBuild } from 'aws-sdk'; import * as setup from './hotswap-test-setup'; let hotswapMockSdkProvider: setup.HotswapMockSdkProvider; let mockUpdateProject: (params: CodeBuild.UpdateProjectInput) => CodeBuild.UpdateProjectOutput; beforeEach(() => { hotswapMockSdkProvider = setup.setupHotswapTests(); mockUpdateProject = jest.fn(); hotswapMockSdkProvider.setUpdateProjectMock(mockUpdateProject); }); test('returns undefined when a new CodeBuild Project is added to the Stack', async () => { // GIVEN const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); }); test('calls the updateProject() API when it receives only a source difference in a CodeBuild project', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'current-spec', Type: 'NO_SOURCE', }, Name: 'my-project', }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'new-spec', Type: 'NO_SOURCE', }, Name: 'my-project', }, Metadata: { 'aws:asset:path': 'new-path', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).not.toBeUndefined(); expect(mockUpdateProject).toHaveBeenCalledWith({ name: 'my-project', source: { type: 'NO_SOURCE', buildspec: 'new-spec', }, }); }); test('calls the updateProject() API when it receives only a source version difference in a CodeBuild project', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'current-spec', Type: 'NO_SOURCE', }, Name: 'my-project', SourceVersion: 'v1', }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'current-spec', Type: 'NO_SOURCE', }, Name: 'my-project', SourceVersion: 'v2', }, Metadata: { 'aws:asset:path': 'new-path', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).not.toBeUndefined(); expect(mockUpdateProject).toHaveBeenCalledWith({ name: 'my-project', sourceVersion: 'v2', }); }); test('calls the updateProject() API when it receives only an environment difference in a CodeBuild project', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'current-spec', Type: 'NO_SOURCE', }, Name: 'my-project', Environment: { ComputeType: 'BUILD_GENERAL1_SMALL', EnvironmentVariables: [ { Name: 'SUPER_IMPORTANT_ENV_VAR', Type: 'PLAINTEXT', Value: 'super cool value', }, { Name: 'SECOND_IMPORTANT_ENV_VAR', Type: 'PLAINTEXT', Value: 'yet another super cool value', }, ], Image: 'aws/codebuild/standard:1.0', ImagePullCredentialsType: 'CODEBUILD', PrivilegedMode: false, Type: 'LINUX_CONTAINER', }, }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'current-spec', Type: 'NO_SOURCE', }, Name: 'my-project', Environment: { ComputeType: 'BUILD_GENERAL1_SMALL', EnvironmentVariables: [ { Name: 'SUPER_IMPORTANT_ENV_VAR', Type: 'PLAINTEXT', Value: 'changed value', }, { Name: 'NEW_IMPORTANT_ENV_VAR', Type: 'PLAINTEXT', Value: 'new value', }, ], Image: 'aws/codebuild/standard:1.0', ImagePullCredentialsType: 'CODEBUILD', PrivilegedMode: false, Type: 'LINUX_CONTAINER', }, }, Metadata: { 'aws:asset:path': 'new-path', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).not.toBeUndefined(); expect(mockUpdateProject).toHaveBeenCalledWith({ name: 'my-project', environment: { computeType: 'BUILD_GENERAL1_SMALL', environmentVariables: [ { name: 'SUPER_IMPORTANT_ENV_VAR', type: 'PLAINTEXT', value: 'changed value', }, { name: 'NEW_IMPORTANT_ENV_VAR', type: 'PLAINTEXT', value: 'new value', }, ], image: 'aws/codebuild/standard:1.0', imagePullCredentialsType: 'CODEBUILD', privilegedMode: false, type: 'LINUX_CONTAINER', }, }); }); test("correctly evaluates the project's name when it references a different resource from the template", async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { Bucket: { Type: 'AWS::S3::Bucket', }, CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'current-spec', Type: 'NO_SOURCE', }, Name: { 'Fn::Join': ['-', [ { Ref: 'Bucket' }, 'project', ]], }, }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); setup.pushStackResourceSummaries(setup.stackSummaryOf('Bucket', 'AWS::S3::Bucket', 'mybucket')); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { Bucket: { Type: 'AWS::S3::Bucket', }, CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'new-spec', Type: 'NO_SOURCE', }, Name: { 'Fn::Join': ['-', [ { Ref: 'Bucket' }, 'project', ]], }, }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).not.toBeUndefined(); expect(mockUpdateProject).toHaveBeenCalledWith({ name: 'mybucket-project', source: { type: 'NO_SOURCE', buildspec: 'new-spec', }, }); }); test("correctly falls back to taking the project's name from the current stack if it can't evaluate it in the template", async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Parameters: { Param1: { Type: 'String' }, AssetBucketParam: { Type: 'String' }, }, Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'current-spec', Type: 'NO_SOURCE', }, Name: { Ref: 'Param1' }, }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); setup.pushStackResourceSummaries(setup.stackSummaryOf('CodeBuildProject', 'AWS::CodeBuild::Project', 'my-project')); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Parameters: { Param1: { Type: 'String' }, AssetBucketParam: { Type: 'String' }, }, Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'new-spec', Type: 'NO_SOURCE', }, Name: { Ref: 'Param1' }, }, Metadata: { 'aws:asset:path': 'new-path', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact, { AssetBucketParam: 'asset-bucket' }); // THEN expect(deployStackResult).not.toBeUndefined(); expect(mockUpdateProject).toHaveBeenCalledWith({ name: 'my-project', source: { type: 'NO_SOURCE', buildspec: 'new-spec', }, }); }); test("will not perform a hotswap deployment if it cannot find a Ref target (outside the project's name)", async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Parameters: { Param1: { Type: 'String' }, }, Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: { 'Fn::Sub': '${Param1}' }, Type: 'NO_SOURCE', }, }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); setup.pushStackResourceSummaries(setup.stackSummaryOf('CodeBuildProject', 'AWS::CodeBuild::Project', 'my-project')); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Parameters: { Param1: { Type: 'String' }, }, Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: { 'Fn::Sub': '${Param1}' }, Type: 'CODEPIPELINE', }, }, Metadata: { 'aws:asset:path': 'new-path', }, }, }, }, }); // THEN await expect(() => hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact), ).rejects.toThrow(/Parameter or resource 'Param1' could not be found for evaluation/); }); test("will not perform a hotswap deployment if it doesn't know how to handle a specific attribute (outside the project's name)", async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { Bucket: { Type: 'AWS::S3::Bucket', }, CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: { 'Fn::GetAtt': ['Bucket', 'UnknownAttribute'] }, Type: 'NO_SOURCE', }, }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); setup.pushStackResourceSummaries( setup.stackSummaryOf('CodeBuildProject', 'AWS::CodeBuild::Project', 'my-project'), setup.stackSummaryOf('Bucket', 'AWS::S3::Bucket', 'my-bucket'), ); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { Bucket: { Type: 'AWS::S3::Bucket', }, CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: { 'Fn::GetAtt': ['Bucket', 'UnknownAttribute'] }, Type: 'S3', }, }, Metadata: { 'aws:asset:path': 'new-path', }, }, }, }, }); // THEN await expect(() => hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact), ).rejects.toThrow("We don't support the 'UnknownAttribute' attribute of the 'AWS::S3::Bucket' resource. This is a CDK limitation. Please report it at https://github.com/aws/aws-cdk/issues/new/choose"); }); test('calls the updateProject() API when it receives a difference in a CodeBuild project with no name', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'current-spec', Type: 'NO_SOURCE', }, }, Metadata: { 'aws:asset:path': 'current-path', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'new-spec', Type: 'NO_SOURCE', }, }, Metadata: { 'aws:asset:path': 'current-path', }, }, }, }, }); // WHEN setup.pushStackResourceSummaries(setup.stackSummaryOf('CodeBuildProject', 'AWS::CodeBuild::Project', 'mock-project-resource-id')); const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).not.toBeUndefined(); expect(mockUpdateProject).toHaveBeenCalledWith({ name: 'mock-project-resource-id', source: { type: 'NO_SOURCE', buildspec: 'new-spec', }, }); }); test('does not call the updateProject() API when it receives a change that is not Source, SourceVersion, or Environment difference in a CodeBuild project', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'current-spec', Type: 'NO_SOURCE', }, ConcurrentBuildLimit: 1, }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { CodeBuildProject: { Type: 'AWS::CodeBuild::Project', Properties: { Source: { BuildSpec: 'current-spec', Type: 'NO_SOURCE', }, ConcurrentBuildLimit: 2, }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockUpdateProject).not.toHaveBeenCalled(); }); test('does not call the updateProject() API when a resource with type that is not AWS::CodeBuild::Project but has the same properties is changed', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { CodeBuildProject: { Type: 'AWS::NotCodeBuild::NotAProject', Properties: { Source: { BuildSpec: 'current-spec', Type: 'NO_SOURCE', }, }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { CodeBuildProject: { Type: 'AWS::NotCodeBuild::NotAProject', Properties: { Source: { BuildSpec: 'new-spec', Type: 'NO_SOURCE', }, }, Metadata: { 'aws:asset:path': 'old-path', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockUpdateProject).not.toHaveBeenCalled(); });
the_stack
enum SegmentStyle { //% block="blank" Blank = 0, //% block="thin" Thin = 1, //% block="narrow" Narrow = 2, //% block="medium" Medium = 3, //% block="thick" Thick = 4 } enum DigitRadix { //% block="decimal" Decimal = 10, //% block="hex" Hex = 16, //% block="octal" Octal = 8, //% block="alpha" Alpha = 26 } enum SegmentScale { //% block="full" Full, //% block="half" Half } // "0123456789ABCDEFHJLoPrUY-°" enum SegmentCharacter { //% block="0" ZERO, //% block="1" ONE, //% block="2" TWO, //% block="3" THREE, //% block="4" FOUR, //% block="5" FIVE, //% block="6" SIX, //% block="7" SEVEN, //% block="8" EIGHT, //% block="9" NINE, //% block="A" A, //% block="B" B, //% block="C" C, //% block="D" D, //% block="E" E, //% block="F" F, //% block="H" H, //% block="J" J, //% block="L" L, //% block="o" o, //% block="P" P, //% block="r" r, //% block="U" U, //% block="Y" Y, //% block="-" Hyphen, //% block="°" Degree } /** * Seven segment display digits and gizmos */ //% icon="\uf2a1" color="#4682B4" blockGap=8 //% groups='["Create", "Counter", "Digits"]' namespace sevenseg { // Copy these array sets along with the array mapping string into Node to get the // formatting of the segment buffer data. /* var fullSegment: number[][] = [ [1, 0, 14, 0, 2, 1, 13, 1, 3, 2, 12, 2, 4, 3, 11, 3], [15, 2, 15, 14, 14, 3, 14, 13, 13, 4, 13, 12, 12, 5, 12, 11], [15, 17, 15, 29, 14, 18, 14, 28, 13, 19, 13, 27, 12, 20, 12, 26], [1, 31, 14, 31, 2, 30, 13, 30, 3, 29, 12, 29, 4, 28, 11, 28], [0, 17, 0, 29, 1, 18, 1, 28, 2, 19, 2, 27, 3, 20, 3, 26], [0, 2, 0, 14, 1, 3, 1, 13, 2, 4, 2, 12, 3, 5, 3, 11], [2, 15, 13, 15, 2, 16, 13, 16, 3, 14, 12, 14, 3, 17, 12, 17] ]; "hex`" + fullSegment.map(n => n.toString(16)).map(n => n.length < 2 ? "0" + n : n).join("") + "`" */ // packed metrics of pixel drawing for full size digit segments const fullSegment: Buffer[] = [ hex`01000e0002010d0103020c0204030b03`, hex`0f020f0e0e030e0d0d040d0c0c050c0b`, hex`0f110f1d0e120e1c0d130d1b0c140c1a`, hex`011f0e1f021e0d1e031d0c1d041c0b1c`, hex`0011001d0112011c0213021b0314031a`, hex`0002000e0103010d0204020c0305030b`, hex`020f0d0f02100d10030e0c0e03110c11` ]; /* var halfSegment: number[][] = [ [1, 0, 6, 0, 2, 1, 5, 1], [7, 2, 7, 6, 6, 3, 6, 5], [7, 8, 7, 13, 6, 9, 6, 12], [1, 15, 6, 15, 2, 14, 5, 14], [0, 8, 0, 13, 1, 9, 1, 12], [0, 2, 0, 6, 1, 3, 1, 5], [2, 7, 5, 7, 2, 7, 5, 7] ]; "hex`" + halfSegment.map(n => n.toString(16)).map(n => n.length < 2 ? "0" + n : n).join("") + "`" */ // packed metrics of pixel drawing for half size digit segments const halfSegment: Buffer[] = [ hex`0100060002010501`, hex`0702070606030605`, hex`0708070d0609060c`, hex`010f060f020e050e`, hex`0008000d0109010c`, hex`0002000601030105`, hex`0207050702070507` ]; // Seven segment layout and id assignments // // a // ========= // || || // f || || b // || g || // ========= // || || // e || || c // || d || // ========= /* const segmapIds = ["abcdef", "bc", "abdeg", "abcdg", "bcfg", "acdfg", "acdefg", "abc", "abcdefg", "abcdfg"]; var segmap = [ 0b11111100, // '0' digit maps "abcdef.." 0b01100000, // '1' digit maps ".bc....." 0b11011010, // '2' digit maps "ab.de.g." 0b11110010, // '3' digit maps "abcd..g." 0b01100110, // '4' digit maps ".bc..fg." 0b10110110, // '5' digit maps "a.cd.fg." 0b10111110, // '6' digit maps "a.cdefg." 0b11100000, // '7' digit maps "abc....." 0b11111110, // '8' digit maps "abcdefg." 0b11110110, // '9' digit maps "abcd.fg." 0b11101110, // 'A' digit maps "abc.efg." 0b00111110, // 'b' digit maps "..cdefg." 0b10011100, // 'C' digit maps "a..def.." 0b01111010, // 'd' digit maps ".bcde.g." 0b10011110, // 'E' digit maps "a..defg." 0b10001110, // 'F' digit maps "a...efg." 0b01101110, // 'H' digit maps ".bc.efg." 0b01111000, // 'J' digit maps ".bcde..." 0b00011100, // 'L' digit maps "...def.." 0b00111010, // 'o' digit maps "..cde.g." 0b11001110, // 'P' digit maps "ab..efg." 0b00001010, // 'r' digit maps "....e.g." 0b01111100, // 'U' digit maps ".bcdef.." 0b01110110, // 'Y' digit maps ".bcd.fg." 0b00000010, // '-' digit maps "......g." 0b11000110 // '°' digit maps "ab...fg." ]; "hex`" + segmap.map(n => n.toString(16)).map(n => n.length < 2 ? "0" + n : n).join("") + "`" */ const segmap: Buffer = hex`fc60daf266b6bee0fef6ee3e9c7a9e8e6e781c3ace0a7c7602c6`; export function drawSegment(digit: Image, segment: Buffer, thickness: SegmentStyle, color: number) { let offset = 0; let x, y, w, h = 0; if (segment.length >= thickness * 4) { for (let i = 0; i < thickness; i++) { x = segment.getNumber(NumberFormat.Int8LE, offset + 0); y = segment.getNumber(NumberFormat.Int8LE, offset + 1); w = segment.getNumber(NumberFormat.Int8LE, offset + 2) - x + 1; h = segment.getNumber(NumberFormat.Int8LE, offset + 3) - y + 1; digit.fillRect(x, y, w, h, color); offset += 4; } } } export function drawDigit(digit: Image, value: number, thickness: SegmentStyle, scale: SegmentScale, color: number) { let segment: Buffer = null; let digitMap = segmap.getNumber(NumberFormat.Int8LE, value) digit.fill(0); for (let i = 0; digitMap != 0; i++) { if ((digitMap & 0x80) != 0) { segment = scale == SegmentScale.Full ? fullSegment[i] : halfSegment[i]; if (scale == SegmentScale.Half && thickness > SegmentStyle.Narrow) { thickness = SegmentStyle.Narrow; } drawSegment(digit, segment, thickness, color) } digitMap = digitMap << 1; } } /** * Create a seven segment display digit * @param thickness the width of the segments, eg: SegmentStyle.Thick * @param value optional initial display value, eg: 0 */ //% group="Create" //% blockId=sevenseg_create block="seven segment digit || of %thickness with value %value" //% expandableArgumentMode=toggle //% blockSetVariable=myDigit //% value.min=0 value.max=9 value.defl=0 //% weight=99 //% help=sevenseg/create-digit export function createDigit(thickness: SegmentStyle = SegmentStyle.Thick, value: number = 0): SevenSegDigit { return new SevenSegDigit(thickness, value) } /** * Create a seven segment counter display * @param thickness the width of the segments, eg: SegmentStyle.Thick * @param scale the size of the segments, eg: SegmentScale.Full * @param numDigits the number of digits displayed, eg: 1 */ //% group="Create" //% blockId=sevenseg_createcounter block="counter || of %thickness segments at %scale size with %numDigits digits" //% expandableArgumentMode=toggle //% blockSetVariable=myCounter //% numDigits.min=1 numDigits.max=5 numDigits.defl=1 //% weight=100 //% help=sevenseg/create-counter export function createCounter(thickness: SegmentStyle = SegmentStyle.Thick, scale: SegmentScale = SegmentScale.Full, numDigits: number = 1): DigitCounter { return new DigitCounter(thickness, scale, numDigits) } } //% blockNamespace=sevenseg color="#4682B4" blockGap=8 class SevenSegDigit { private digit: Image; private digitSprite: Sprite; private _value: number; private thickness: SegmentStyle; private color: number; private scale: SegmentScale; private _x: number; private _y: number; private _radix: number; constructor(thickness: SegmentStyle = SegmentStyle.Thick, value: number = 0) { this._value = value; this.digit = image.create(16, 32); this.digitSprite = sprites.create(this.digit, 0); this._x = this.digitSprite.x this._y = this.digitSprite.y this.thickness = thickness; this.color = 2; this.scale = SegmentScale.Full; this._radix = DigitRadix.Decimal; sevenseg.drawDigit(this.digit, this.value, thickness, this.scale, this.color); } /** * Set the display value to a digit character: '0'- '9' * @param alphaChar the display value, eg: "0" */ //% group="Digits" //% blockId=sevenseg_setalpha block="set %sevenseg(myDigit) display value to %alphaChar" //% weight=40 setDigitAlpha(alphaChar: SegmentCharacter) { const matchChars = "0123456789ABCDEFHJLoPrUY-°"; if (alphaChar == this.value || alphaChar < 0 || alphaChar >= matchChars.length) return; this._value = alphaChar; sevenseg.drawDigit(this.digit, this.value, this.thickness, this.scale, this.color); } //% group="Digits" blockSetVariable="myDigit" //% blockCombine block="value" weight=90 get value(): number { return this._value; } //% group="Digits" blockSetVariable="myDigit" //% blockCombine block="value" weight=90 set value(value: number) { value = value | 0; if (value != this.value) { if (value >= 0 && value < this._radix) { this._value = value; } else { this._value = value % this._radix; } sevenseg.drawDigit(this.digit, this._value, this.thickness, this.scale, this.color); } } /** * Set the display digit color * @param color of the digit display, eg: 2 */ //% group="Digits" //% blockId=sevenseg_setcolor block="set %sevenseg(myDigit) display color to %color=colorindexpicker" //% weight=35 //% help=sevenseg/sevensegdigit/set-digit-color setDigitColor(color: number): void { this.color = color; sevenseg.drawDigit(this.digit, this.value, this.thickness, this.scale, this.color); } //% group="Digits" blockSetVariable="myDigit" //% blockCombine block="x" get x(): number { return this.digitSprite.x; } //% group="Digits" blockSetVariable="myDigit" //% blockCombine block="x" set x(v: number) { this._x = v; this.digitSprite.x = v; } //% group="Digits" blockSetVariable="myDigit" //% blockCombine block="y" get y(): number { return this.digitSprite.y; } //% group="Digits" blockSetVariable="myDigit" //% blockCombine block="y" set y(v: number) { this._y = v; this.digitSprite.y = v; } //% group="Digits" blockSetVariable="myDigit" //% blockCombine block="width" get width(): number { return this.digitSprite.width; } //% group="Digits" blockSetVariable="myDigit" //% blockCombine block="height" get height(): number { return this.digitSprite.height; } /** * Set the display radix of the digit * @param radix of the digit display, eg: DigitRadix.Decimal */ //% blockId=sevenseg_setradix block="set display radix of %sevenseg(myDigit) to %radix" //% group="Digits" weight=30 //% help=sevenseg/sevensegdigit/set-radix setRadix(radix: DigitRadix) { this._radix = radix; sevenseg.drawDigit(this.digit, this.value, this.thickness, this.scale, this.color); } /** * Set the display digit size * @param scale of the digit display, eg: SegmentScale.Full */ //% group="Digits" //% blockId=sevenseg_setdigitscale block="set %sevenseg(myDigit) to %scale size" //% weight=25 //% help=sevenseg/sevensegdigit/set-scale setScale(scale: SegmentScale): void { if (scale != this.scale) { this.scale = scale; if (scale == SegmentScale.Full) { this.digit = image.create(16, 32) } else { this.digit = image.create(8, 16) } this.digitSprite.setImage(this.digit); this.digitSprite.x = this._x; this.digitSprite.y = this._y; sevenseg.drawDigit(this.digit, this.value, this.thickness,this.scale, this.color); } } } //% blockNamespace=sevenseg color="#4682B4" blockGap=8 class DigitCounter { private _count: number; private limit: number private _x: number; private _y: number; private numDigits: number; private maxDigits: number private digits: SevenSegDigit[]; private thickness: SegmentStyle; private color: number; private scale: SegmentScale; constructor(thickness: SegmentStyle = SegmentStyle.Thick, scale: SegmentScale = SegmentScale.Full, numDigits: number = 3) { this._count = 0; this.maxDigits = 5; this.color = 2 this.scale = scale; numDigits = Math.clamp(1, this.maxDigits, numDigits); this.thickness = thickness; this.digits = []; this.digits.push(new SevenSegDigit(this.thickness, 0)); this.digits[0].setScale(this.scale); this.digits[0].setDigitColor(this.color); this.numDigits = 1; this.limit = 10; this._x = this.digits[0].x; this._y = this.digits[0].y; for (let i = 1; i < numDigits; i++) { this.addDigit(); } } /** * Add a digit to the counter */ addDigit() { let newDigit: SevenSegDigit = null if (this.numDigits < this.maxDigits) { newDigit = new SevenSegDigit(this.thickness, 0); newDigit.setScale(this.scale) newDigit.setDigitColor(this.color) this.digits.push(newDigit); this.numDigits += 1; this.limit = this.limit * 10; this.adjustDigitPositions(); } } //% group="Counter" blockSetVariable="myCounter" //% blockCombine block="count" get count() { return this._count; } //% group="Counter" blockSetVariable="myCounter" //% blockCombine block="count" set count(value: number) { if (value >= 0 && value < this.limit) { this._count = value; this.updateDisplayValue() } } private updateDisplayValue() { let decimator = 1; let updateValue = 0; for (let i = 0; i < this.digits.length; i++) { updateValue = this._count / decimator % 10; this.digits[i].value = updateValue; decimator = decimator * 10; } } private adjustDigitPositions() { let spacing = this.digits[0].width * 4 / 3; let offset = this.digits[0].x + spacing / 2; for (let i = 0; i < this.numDigits; i++) { this.digits[i].x = offset; offset -= spacing; } } private moveDigits() { let spacing = this.digits[0].width * 4 / 3; for (let i = 1; i < this.numDigits; i++) { this.digits[i].x = this.digits[i - 1].x - spacing; this.digits[i].y = this.digits[0].y; } this._x = (this.digits[0].x + this.digits[this.numDigits - 1].x) / 2; this._y = this.digits[0].y; } /** * Set the counter display digit color * @param color of the digit display, eg: 2 */ //% group="Counter" //% blockId=sevenseg_setcountercolor block="set %sevenseg(myCounter) display color to %color=colorindexpicker" //% weight=86 //% help=sevenseg/digitcounter/set-digit-color setDigitColor(color: number): void { this.color = color; for (let i = 0; i < this.numDigits; i++) { this.digits[i].setDigitColor(color); } } //% group="Counter" blockSetVariable="myCounter" //% blockCombine block="x" get x(): number { return this._x; } //% group="Counter" blockSetVariable="myCounter" //% blockCombine block="x" set x(v: number) { this.digits[0].x += v - this._x; this.moveDigits() } //% group="Counter" blockSetVariable="myCounter" //% blockCombine block="y" get y(): number { return this._y; } //% group="Counter" blockSetVariable="myCounter" //% blockCombine block="y" set y(v: number) { this.digits[0].y = v; this.moveDigits() } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [dax](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazondynamodbacceleratordax.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Dax extends PolicyStatement { public servicePrefix = 'dax'; /** * Statement provider for service [dax](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazondynamodbacceleratordax.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * The BatchGetItem action returns the attributes of one or more items from one or more tables. * * Access Level: Read * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchGetItem.html */ public toBatchGetItem() { return this.to('BatchGetItem'); } /** * The BatchWriteItem action operation puts or deletes multiple items in one or more tables. * * Access Level: Write * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html */ public toBatchWriteItem() { return this.to('BatchWriteItem'); } /** * The ConditionCheckItem operation checks the existence of a set of attributes for the item with the given primary key * * Access Level: Read * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ConditionCheckItem.html */ public toConditionCheckItem() { return this.to('ConditionCheckItem'); } /** * The CreateCluster action creates a DAX cluster. * * Access Level: Write * * Dependent actions: * - dax:CreateParameterGroup * - dax:CreateSubnetGroup * - ec2:CreateNetworkInterface * - ec2:DeleteNetworkInterface * - ec2:DescribeNetworkInterfaces * - ec2:DescribeSecurityGroups * - ec2:DescribeSubnets * - ec2:DescribeVpcs * - iam:GetRole * - iam:PassRole * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_CreateCluster.html */ public toCreateCluster() { return this.to('CreateCluster'); } /** * The CreateParameterGroup action creates collection of parameters that you apply to all of the nodes in a DAX cluster. * * Access Level: Write * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_CreateParameterGroup.html */ public toCreateParameterGroup() { return this.to('CreateParameterGroup'); } /** * The CreateSubnetGroup action creates a new subnet group. * * Access Level: Write * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_CreateSubnetGroup.html */ public toCreateSubnetGroup() { return this.to('CreateSubnetGroup'); } /** * The DecreaseReplicationFactor action removes one or more nodes from a DAX cluster. * * Access Level: Write * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_DecreaseReplicationFactor.html */ public toDecreaseReplicationFactor() { return this.to('DecreaseReplicationFactor'); } /** * The DeleteCluster action deletes a previously provisioned DAX cluster. * * Access Level: Write * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_DeleteCluster.html */ public toDeleteCluster() { return this.to('DeleteCluster'); } /** * The DeleteItem action deletes a single item in a table by primary key. * * Access Level: Write * * Possible conditions: * - .ifEnclosingOperation() * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DeleteItem.html */ public toDeleteItem() { return this.to('DeleteItem'); } /** * The DeleteParameterGroup action deletes the specified parameter group. * * Access Level: Write * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_DeleteParameterGroup.html */ public toDeleteParameterGroup() { return this.to('DeleteParameterGroup'); } /** * The DeleteSubnetGroup action deletes a subnet group. * * Access Level: Write * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_DeleteSubnetGroup.html */ public toDeleteSubnetGroup() { return this.to('DeleteSubnetGroup'); } /** * The DescribeClusters action returns information about all provisioned DAX clusters. * * Access Level: List * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_DescribeClusters.html */ public toDescribeClusters() { return this.to('DescribeClusters'); } /** * The DescribeDefaultParameters action returns the default system parameter information for DAX. * * Access Level: List * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_DescribeDefaultParameters.html */ public toDescribeDefaultParameters() { return this.to('DescribeDefaultParameters'); } /** * The DescribeEvents action returns events related to DAX clusters and parameter groups. * * Access Level: List * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_DescribeEvents.html */ public toDescribeEvents() { return this.to('DescribeEvents'); } /** * The DescribeParameterGroups action returns a list of parameter group descriptions. * * Access Level: List * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_DescribeParameterGroups.html */ public toDescribeParameterGroups() { return this.to('DescribeParameterGroups'); } /** * The DescribeParameters action returns the detailed parameter list for a particular parameter group. * * Access Level: Read * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_DescribeParameters.html */ public toDescribeParameters() { return this.to('DescribeParameters'); } /** * The DescribeSubnetGroups action returns a list of subnet group descriptions. * * Access Level: List * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_DescribeSubnetGroups.html */ public toDescribeSubnetGroups() { return this.to('DescribeSubnetGroups'); } /** * The GetItem action returns a set of attributes for the item with the given primary key. * * Access Level: Read * * Possible conditions: * - .ifEnclosingOperation() * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_GetItem.html */ public toGetItem() { return this.to('GetItem'); } /** * The IncreaseReplicationFactor action adds one or more nodes to a DAX cluster. * * Access Level: Write * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_IncreaseReplicationFactor.html */ public toIncreaseReplicationFactor() { return this.to('IncreaseReplicationFactor'); } /** * The ListTags action returns a list all of the tags for a DAX cluster. * * Access Level: Read * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_ListTags.html */ public toListTags() { return this.to('ListTags'); } /** * The PutItem action creates a new item, or replaces an old item with a new item. * * Access Level: Write * * Possible conditions: * - .ifEnclosingOperation() * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html */ public toPutItem() { return this.to('PutItem'); } /** * The Query action finds items based on primary key values. You can query any table or secondary index that has a composite primary key (a partition key and a sort key). * * Access Level: Read * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html */ public toQuery() { return this.to('Query'); } /** * The RebootNode action reboots a single node of a DAX cluster. * * Access Level: Write * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_RebootNode.html */ public toRebootNode() { return this.to('RebootNode'); } /** * The Scan action returns one or more items and item attributes by accessing every item in a table or a secondary index. * * Access Level: Read * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html */ public toScan() { return this.to('Scan'); } /** * The TagResource action associates a set of tags with a DAX resource. * * Access Level: Tagging * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * The UntagResource action removes the association of tags from a DAX resource. * * Access Level: Tagging * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * The UpdateCluster action modifies the settings for a DAX cluster. * * Access Level: Write * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_UpdateCluster.html */ public toUpdateCluster() { return this.to('UpdateCluster'); } /** * The UpdateItem action edits an existing item's attributes, or adds a new item to the table if it does not already exist. * * Access Level: Write * * Possible conditions: * - .ifEnclosingOperation() * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html */ public toUpdateItem() { return this.to('UpdateItem'); } /** * The UpdateParameterGroup action modifies the parameters of a parameter group. * * Access Level: Write * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_UpdateParameterGroup.html */ public toUpdateParameterGroup() { return this.to('UpdateParameterGroup'); } /** * The UpdateSubnetGroup action modifies an existing subnet group. * * Access Level: Write * * https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_dax_UpdateSubnetGroup.html */ public toUpdateSubnetGroup() { return this.to('UpdateSubnetGroup'); } protected accessLevelList: AccessLevelList = { "Read": [ "BatchGetItem", "ConditionCheckItem", "DescribeParameters", "GetItem", "ListTags", "Query", "Scan" ], "Write": [ "BatchWriteItem", "CreateCluster", "CreateParameterGroup", "CreateSubnetGroup", "DecreaseReplicationFactor", "DeleteCluster", "DeleteItem", "DeleteParameterGroup", "DeleteSubnetGroup", "IncreaseReplicationFactor", "PutItem", "RebootNode", "UpdateCluster", "UpdateItem", "UpdateParameterGroup", "UpdateSubnetGroup" ], "List": [ "DescribeClusters", "DescribeDefaultParameters", "DescribeEvents", "DescribeParameterGroups", "DescribeSubnetGroups" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type application to the statement * * https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.access-control.html * * @param clusterName - Identifier for the clusterName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onApplication(clusterName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:dax:${Region}:${Account}:cache/${ClusterName}'; arn = arn.replace('${ClusterName}', clusterName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Used to block Transactions APIs calls and allow the non-Transaction APIs calls and vice-versa. * * Applies to actions: * - .toDeleteItem() * - .toGetItem() * - .toPutItem() * - .toUpdateItem() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifEnclosingOperation(value: string | string[], operator?: Operator | string) { return this.if(`EnclosingOperation`, value, operator || 'StringLike'); } }
the_stack
import * as React from "react"; import { Panel } from "azure-devops-ui/Panel"; import "./DependencyPanel.scss"; import { ITimelineItem, LoadingStatus, ProgressTrackingCriteria, IWorkItemIcon, IProject, IProjectConfiguration } from "../../Contracts"; import { PortfolioPlanningDataService } from "../../Common/Services/PortfolioPlanningDataService"; import { BacklogConfigurationDataService } from "../../Common/Services/BacklogConfigurationDataService"; import { PortfolioPlanningDependencyQueryResult, PortfolioPlanningQueryResultItem } from "../../Models/PortfolioPlanningQueryModels"; import { Spinner, SpinnerSize } from "azure-devops-ui/Spinner"; import { CollapsiblePanel } from "../../Common/Components/CollapsiblePanel"; import { ScrollableList, IListItemDetails, ListItem } from "azure-devops-ui/List"; import { ArrayItemProvider } from "azure-devops-ui/Utilities/Provider"; import { IListBoxItem } from "azure-devops-ui/ListBox"; import { Tooltip } from "azure-devops-ui/TooltipEx"; import { ProgressDetails } from "../../Common/Components/ProgressDetails"; import { Image, ImageFit, IImageProps } from "office-ui-fabric-react/lib/Image"; import { MessageCard, MessageCardSeverity } from "azure-devops-ui/MessageCard"; import { connect } from "react-redux"; import { Icon } from "azure-devops-ui/Icon"; import moment = require("moment"); type WorkItemIconMap = { [projectIdKey: string]: { [workItemType: string]: IWorkItemIcon } }; type WorkItemInProgressStatesMap = { [projectIdKey: string]: { [WorkItemType: string]: string[] } }; export interface IDependencyPanelProps { workItem: ITimelineItem; projectInfo: IProject; progressTrackingCriteria: ProgressTrackingCriteria; onDismiss: () => void; } export interface IDependencyPanelState { loading: LoadingStatus; errorMessage: string; predecessors: PortfolioPlanningQueryResultItem[]; successors: PortfolioPlanningQueryResultItem[]; workItemIcons: WorkItemIconMap; workItemTypeMappedStatesInProgress: WorkItemInProgressStatesMap; } interface IDependencyItemRenderData { projectId: string; workItemType: string; completed: number; total: number; showInfoIcon: boolean; infoMessage: string; } export class DependencyPanel extends React.Component<IDependencyPanelProps, IDependencyPanelState> { constructor(props) { super(props); this.state = { loading: LoadingStatus.NotLoaded, predecessors: [], successors: [], workItemIcons: {}, errorMessage: "", workItemTypeMappedStatesInProgress: {} }; try { this._initialize(); } catch (error) { const errorMessage = JSON.stringify(error, null, " "); this.setState({ errorMessage, loading: LoadingStatus.NotLoaded }); } } private _initialize = () => { this._getDependencies().then( dependencies => { if (dependencies && dependencies.exceptionMessage && dependencies.exceptionMessage.length > 0) { this.setState({ errorMessage: dependencies.exceptionMessage, loading: LoadingStatus.NotLoaded }); return; } let Predecessors: PortfolioPlanningQueryResultItem[] = []; let Successors: PortfolioPlanningQueryResultItem[] = []; const newWorkItemIconMap: WorkItemIconMap = {}; const newInProgressStatesMap: WorkItemInProgressStatesMap = {}; const allWorkItemIconPromises: Promise<WorkItemIconMap>[] = []; const allInProgressStatePromises: Promise<WorkItemInProgressStatesMap>[] = []; Object.keys(dependencies.byProject).forEach(projectIdKey => { let { Predecessors: ProjectPredecessors, Successors: ProjectSuccessors } = dependencies.byProject[ projectIdKey ]; const projectConfiguration = dependencies.targetsProjectConfiguration[projectIdKey]; Predecessors = Predecessors.concat(ProjectPredecessors); Successors = Successors.concat(ProjectSuccessors); allWorkItemIconPromises.push( this._getWorkItemIcons(ProjectPredecessors, ProjectSuccessors, projectConfiguration) ); allInProgressStatePromises.push(this._getWorkItemTypeMappedStatesInProgress(projectIdKey)); }); Promise.all(allInProgressStatePromises).then( allInProgressStates => { Promise.all(allWorkItemIconPromises).then( allWorkItemIcons => { allInProgressStates.forEach(res => { Object.keys(res).forEach(projectIdKey => { if (!newInProgressStatesMap[projectIdKey]) { newInProgressStatesMap[projectIdKey] = {}; } Object.keys(res[projectIdKey]).forEach(workItemTypeKey => { const inProgressStates = res[projectIdKey][workItemTypeKey]; if (!newInProgressStatesMap[projectIdKey][workItemTypeKey]) { newInProgressStatesMap[projectIdKey][ workItemTypeKey ] = inProgressStates; } }); }); }); allWorkItemIcons.forEach(res => { Object.keys(res).forEach(projectIdKey => { if (!newWorkItemIconMap[projectIdKey]) { newWorkItemIconMap[projectIdKey] = {}; } Object.keys(res[projectIdKey]).forEach(workItemTypeKey => { const icon: IWorkItemIcon = res[projectIdKey][workItemTypeKey]; if (!newWorkItemIconMap[projectIdKey][workItemTypeKey]) { newWorkItemIconMap[projectIdKey][workItemTypeKey] = icon; } }); }); }); // Sort items from all projects by target date. Predecessors.sort((a, b) => (a.TargetDate > b.TargetDate ? 1 : -1)); Successors.sort((a, b) => (a.TargetDate > b.TargetDate ? 1 : -1)); this.setState({ loading: LoadingStatus.Loaded, predecessors: Predecessors, successors: Successors, workItemIcons: newWorkItemIconMap, errorMessage: dependencies.exceptionMessage, workItemTypeMappedStatesInProgress: newInProgressStatesMap }); }, error => this.setState({ errorMessage: error.message, loading: LoadingStatus.NotLoaded }) ); }, error => this.setState({ errorMessage: error.message, loading: LoadingStatus.NotLoaded }) ); }, error => { this.setState({ errorMessage: error.message, loading: LoadingStatus.NotLoaded }); } ); }; private _getWorkItemIcons = async ( Predecessors: PortfolioPlanningQueryResultItem[], Successors: PortfolioPlanningQueryResultItem[], configuration: IProjectConfiguration ): Promise<WorkItemIconMap> => { const projectIdKey = configuration.id.toLowerCase(); let result: WorkItemIconMap = { [projectIdKey]: { ...configuration.iconInfoByWorkItemType } }; const missingWorkItemTypes: { [workItemTypeKey: string]: boolean } = {}; const allPromises: Promise<IWorkItemIcon>[] = []; Predecessors.concat(Successors).forEach(item => { const workItemTypeKey = item.WorkItemType.toLowerCase(); if (!configuration.iconInfoByWorkItemType[workItemTypeKey] && !missingWorkItemTypes[workItemTypeKey]) { missingWorkItemTypes[workItemTypeKey] = true; allPromises.push( BacklogConfigurationDataService.getInstance().getWorkItemTypeIconInfo(projectIdKey, workItemTypeKey) ); } }); if (allPromises.length > 0) { const missingIcons = await Promise.all(allPromises); missingIcons.forEach(missingIcon => { const workItemTypeKey = missingIcon.workItemType.toLowerCase(); if (!result[projectIdKey][workItemTypeKey]) { result[projectIdKey][workItemTypeKey] = missingIcon; } }); } return result; }; public render(): JSX.Element { // TODO: Add red ! icon to indicate problems // TODO: Dependencies should probably be links return ( <Panel onDismiss={this.props.onDismiss} titleProps={{ text: `Dependencies for ${this.props.workItem.title}` }} footerButtonProps={[ { text: "Close", primary: true, onClick: this.props.onDismiss } ]} > <div className="dependency-panel">{this._renderDependencies()}</div> </Panel> ); } private _renderDependencies(): JSX.Element { if (this.state.errorMessage) { return <MessageCard severity={MessageCardSeverity.Error}>{this.state.errorMessage}</MessageCard>; } else if (this.state.loading != LoadingStatus.Loaded) { return <Spinner label="Loading dependencies..." size={SpinnerSize.large} className="loading-spinner" />; } else { return ( <> <CollapsiblePanel contentKey="depends-on" animate={false} headerLabel="Waiting for others" headerClassName={"list-header"} renderContent={(key: string) => this._renderDependencyGroup(this.state.predecessors, true)} isCollapsible={true} initialIsExpanded={true} forceContentUpdate={true} alwaysRenderContents={false} /> <CollapsiblePanel contentKey="has-dependency" animate={false} headerLabel="Others waiting on" headerClassName={"list-header"} renderContent={(key: string) => this._renderDependencyGroup(this.state.successors, false)} isCollapsible={true} initialIsExpanded={true} forceContentUpdate={true} alwaysRenderContents={false} /> </> ); } } private _renderDependencyGroup = (dependencies: PortfolioPlanningQueryResultItem[], isPredecessor): JSX.Element => { const items: IListBoxItem<IDependencyItemRenderData>[] = []; if (dependencies.length === 0) { return <div className="empty-group-message">No dependencies found.</div>; } dependencies.forEach(dependency => { items.push({ id: dependency.WorkItemId.toString(), text: dependency.Title, data: { projectId: dependency.ProjectId, workItemType: dependency.WorkItemType, completed: this.props.progressTrackingCriteria === ProgressTrackingCriteria.CompletedCount ? dependency.CompletedCount : dependency.CompletedEffort, total: this.props.progressTrackingCriteria === ProgressTrackingCriteria.CompletedCount ? dependency.TotalCount : dependency.TotalEffort, showInfoIcon: this._showInfoIcon(dependency, isPredecessor), infoMessage: isPredecessor ? "Target date is later than " + this.props.workItem.title + "'s start date" : "Start date is earlier than " + this.props.workItem.title + "'s target date" } }); }); return ( <ScrollableList className="item-list" itemProvider={new ArrayItemProvider<IListBoxItem<IDependencyItemRenderData>>(items)} renderRow={this._renderDependencyItem} /> ); }; private _showInfoIcon = (item: PortfolioPlanningQueryResultItem, isPredecessor: boolean): boolean => { // only show info icon if the item is in InProgress state. let statesForInProgress: string[] = []; const projectIdKey = item.ProjectId.toLowerCase(); const workItemTypeKey = item.WorkItemType.toLowerCase(); if ( this.state.workItemTypeMappedStatesInProgress[projectIdKey] && this.state.workItemTypeMappedStatesInProgress[projectIdKey][workItemTypeKey] ) { statesForInProgress = this.state.workItemTypeMappedStatesInProgress[projectIdKey][workItemTypeKey]; } if (statesForInProgress.indexOf(item.State) === -1) { return false; } // if this depends-on item has end date later than selected work item's start date. if (moment(item.TargetDate) > this.props.workItem.start_time && isPredecessor) { return true; } // if this has-dependency item has start date earlier than selected work item's end date. if (moment(item.StartDate) < this.props.workItem.end_time && !isPredecessor) { return true; } return false; }; private _renderDependencyItem = ( index: number, item: IListBoxItem<IDependencyItemRenderData>, details: IListItemDetails<IListBoxItem<IDependencyItemRenderData>>, key?: string ): JSX.Element => { const workItemTypeKey = item.data.workItemType.toLowerCase(); const projectIdKey = item.data.projectId.toLowerCase(); let imageUrl: string = null; if (this.state.workItemIcons[projectIdKey] && this.state.workItemIcons[projectIdKey][workItemTypeKey]) { imageUrl = this.state.workItemIcons[projectIdKey]![workItemTypeKey]!.url; } const imageProps: IImageProps = { src: imageUrl, className: "item-list-icon", imageFit: ImageFit.center, maximizeFrame: true }; return ( <ListItem key={key || item.id} index={index} details={details}> <div className="item-list-row"> {item.data.showInfoIcon ? ( <Tooltip text={item.data.infoMessage}> <div> <Icon ariaLabel="Info icon" iconName="Info" className="info-icon" /> </div> </Tooltip> ) : null} <Image {...imageProps as any} /> <div className="item-text-and-progress"> <Tooltip overflowOnly={true}> <span className="item-text"> {item.id} - {item.text} </span> </Tooltip> <div className="item-progress"> <ProgressDetails completed={item.data.completed} total={item.data.total} onClick={() => {}} /> </div> </div> </div> </ListItem> ); }; private _getDependencies = async (): Promise<PortfolioPlanningDependencyQueryResult> => { const byProject: { [projectIdKey: string]: number[] } = {}; byProject[this.props.projectInfo.id] = [this.props.workItem.id]; const dependencies = await PortfolioPlanningDataService.getInstance().runDependencyQuery({ byProject }); return dependencies; }; private _getWorkItemTypeMappedStatesInProgress = async ( projectId: string ): Promise<WorkItemInProgressStatesMap> => { const workItemTypeMappedStatesInProgress = await BacklogConfigurationDataService.getInstance().getInProgressStates( projectId ); const result: WorkItemInProgressStatesMap = {}; result[projectId] = workItemTypeMappedStatesInProgress; return Promise.resolve(result); }; } const mapStateToProps = (state: IDependencyPanelState, ownProps: IDependencyPanelProps) => ({ workItem: ownProps.workItem, progressTrackingCriteria: ownProps.progressTrackingCriteria, onDismiss: ownProps.onDismiss }); export const ConnectedDependencyPanel = connect(mapStateToProps)(DependencyPanel);
the_stack
import '@lib/crash/reporter' import '@lib/logger/main' import '@lib/tracker/main' import Fs from 'fs' import Path from 'path' import { isEmpty, identity, pickBy } from 'lodash' import { app, BrowserWindow, dialog, ipcMain } from 'electron' import { applicationMenu, Menu as ContextMenu, ProjectMenu, RepositoryMenu, FrameworkMenu, SuiteMenu, TestMenu, FileMenu } from '@main/menu' import { ApplicationWindow } from '@main/application-window' import { Updater } from '@main/updater' import { LogLevel } from '@lib/logger/levels' import { mergeEnvFromShell } from '@lib/process/shell' import { state } from '@lib/state' import { log as writeLog } from '@lib/logger' import { ProjectIdentifier, ProjectActiveIdentifiers, ProjectEntities, ProjectOptions, IProject } from '@lib/frameworks/project' import { IRepository } from '@lib/frameworks/repository' import { Frameworks } from '@lib/frameworks' import { FrameworkOptions, FrameworkFilter } from '@lib/frameworks/framework' import { Nugget } from '@lib/frameworks/nugget' import { ISuite } from '@lib/frameworks/suite' import { ITest } from '@lib/frameworks/test' import { PotentialRepositoryOptions, RepositoryValidator, FrameworkValidator, PotentialFrameworkOptions } from '@lib/frameworks/validator' let currentWindow: ApplicationWindow | null = null // Merge environment variables from shell, if needed. mergeEnvFromShell() // Set `__static` path to static files in production if (!__DEV__) { (global as any).__static = Path.join(__dirname, '/static').replace(/\\/g, '\\\\') } function getProject (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent): IProject { return ApplicationWindow.getProjectFromWebContents(event.sender)! } function getRepository (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent, repositoryId: string): Promise<IRepository> { return new Promise(async (resolve, reject) => { const project: IProject = getProject(event) const repository: IRepository = project.getRepositoryById(repositoryId)! if (repository) { resolve(repository!) return } log.error(`Error while getting repository ${repositoryId}.`) reject() }) } function entities ( event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent, frameworkId: string, identifiers: Array<string> = [] ): Promise<ProjectEntities> { return new Promise(async (resolve, reject) => { try { const project: IProject = getProject(event) const context = project.getContextByFrameworkId(frameworkId) if (context) { const { repository, framework } = context const entities = { project, repository, framework } if (!identifiers.length) { resolve(entities) return } let nugget: Nugget | undefined const nuggets: Array<Nugget> = [] do { // First nugget is always a suite, all others are tests. nugget = nugget ? nugget.findTest(identifiers.shift()!) : framework.getSuiteById(identifiers.shift()!) if (!nugget) { throw Error } nuggets.push(nugget) if (!nugget.expanded) { await nugget.toggleExpanded(true, false) } } while (identifiers.length > 0) resolve({ ...entities, nuggets, nugget }) return } } catch (_) {} log.error(`Unable to find requested entities '${JSON.stringify({ frameworkId, identifiers })}'`) reject() }) } app .on('ready', () => { track.screenview('Application started') currentWindow = ApplicationWindow.init(state.getCurrentProject()) applicationMenu.build(currentWindow) if (!__DEV__) { // Start auto-updating process. new Updater() return } }) ipcMain .on('log', (event: Electron.IpcMainEvent, level: LogLevel, message: string) => { // Write renderer messages to log, if they meet the level threshold. // We're using the main log function directly so that they are not // marked as being from the "main" process. writeLog(level, message) }) .on('track-screenview', (event: Electron.IpcMainEvent, screen: string) => { track.screenview(screen) }) .on('track-event', (event: Electron.IpcMainEvent, category: string, action: string, label: string | null, value: string | null) => { track.event(category, action, label, value) }) .on('window-set', (event: Electron.IpcMainEvent, args: any[]) => { currentWindow = event as any }) .on('maximize', (event: Electron.IpcMainEvent) => { if (currentWindow) { if (currentWindow.getChild().isMaximized()) { currentWindow.getChild().unmaximize() return } currentWindow.getChild().maximize() } }) .on('minimize', (event: Electron.IpcMainEvent) => { if (currentWindow) { currentWindow.getChild().minimize() } }) .on('close', (event: Electron.IpcMainEvent) => { if (currentWindow) { currentWindow.getChild().close() } }) .on('menu-refresh', (event: Electron.IpcMainEvent) => { applicationMenu.build(currentWindow) }) .on('menu-event', (event: Electron.IpcMainEvent, args: any[]) => { const { name, properties } = event as any if (currentWindow) { currentWindow.sendMenuEvent({ name, properties }) } }) .on('project-switch', (event: Electron.IpcMainEvent, identifier?: ProjectIdentifier | null) => { const window: ApplicationWindow = ApplicationWindow.getFromWebContents(event.sender)! const project: IProject | null = window.getProject() if (identifier && !isEmpty(pickBy(identifier, identity))) { window.setProject(identifier) state.set('currentProject', window.getProject()!.getId()) } else { window.clear() } if (project) { project.stop() } }) .on('project-repositories', (event: Electron.IpcMainEvent, identifier: ProjectIdentifier) => { getProject(event).emitRepositoriesToRenderer() }) .on('project-active-framework', (event: Electron.IpcMainEvent, frameworkId: ProjectActiveIdentifiers['framework']) => { const project = getProject(event) project.setActiveFramework(frameworkId) applicationMenu.setOptions(project.getActive()) }) .on('repository-remove', (event: Electron.IpcMainEvent, repositoryId: string) => { const project: IProject = getProject(event) project.removeRepository(repositoryId) project.emitRepositoriesToRenderer() ApplicationWindow.getFromWebContents(event.sender)!.refreshActiveFramework() }) .on('repository-toggle', async (event: Electron.IpcMainEvent, repositoryId: string, toggle: boolean) => { const repository = await getRepository(event, repositoryId) if (toggle) { repository.expand() return } repository.collapse() }) .on('framework-add', async (event: Electron.IpcMainEvent, repositoryId: string, options: FrameworkOptions) => { const repository: IRepository = await getRepository(event, repositoryId) repository.addFramework(options).then(framework => { framework.refresh() }) repository.emitFrameworksToRenderer() ApplicationWindow.getFromWebContents(event.sender)!.refreshActiveFramework() }) .on('framework-remove', async (event: Electron.IpcMainEvent, frameworkId: string) => { entities(event, frameworkId).then(({ repository, framework }) => { repository.removeFramework(framework.getId()) repository.emitFrameworksToRenderer() ApplicationWindow.getFromWebContents(event.sender)!.refreshActiveFramework() }) }) .on('framework-update', (event: Electron.IpcMainEvent, frameworkId: string, options: FrameworkOptions) => { entities(event, frameworkId).then(async ({ repository, framework }) => { await framework.updateOptions({ ...options, repositoryPath: repository.getPath() }) repository.emitFrameworksToRenderer() event.sender.send('framework-options-updated', framework.render()) framework.emitSuitesToRenderer() }) }) .on('framework-refresh', (event: Electron.IpcMainEvent, frameworkId: string) => { entities(event, frameworkId).then(({ framework }) => { framework.refresh() }) }) .on('framework-start', (event: Electron.IpcMainEvent, frameworkId: string) => { entities(event, frameworkId).then(({ framework }) => { framework.start() }) }) .on('framework-stop', (event: Electron.IpcMainEvent, frameworkId: string) => { entities(event, frameworkId).then(({ framework }) => { framework.stop() }) }) .on('framework-suites', (event: Electron.IpcMainEvent, frameworkId: string) => { entities(event, frameworkId).then(({ framework }) => { framework.emitSuitesToRenderer() }) }) .on('framework-filter', (event: Electron.IpcMainEvent, frameworkId: string, key: FrameworkFilter, value: any) => { entities(event, frameworkId).then(({ framework }) => { framework.setFilter(key, value) }) }) .on('framework-reset-filters', (event: Electron.IpcMainEvent, frameworkId: string) => { entities(event, frameworkId).then(({ framework }) => { framework.resetFilters() }) }) .on('framework-toggle-child', async (event: Electron.IpcMainEvent, frameworkId: string, identifiers: Array<string>, toggle: boolean) => { entities(event, frameworkId, identifiers).then(({ nugget }) => { if (toggle) { // If we're expanding it, send the tests to the renderer. nugget!.emitTestsToRenderer() return } // If collapsing, just wither the nugget, no response is needed. nugget!.toggleExpanded(false, true) }) }) .on('framework-select', async (event: Electron.IpcMainEvent, frameworkId: string, identifiers: Array<string>, toggle: boolean) => { entities(event, frameworkId, identifiers).then(({ nugget }) => { nugget!.toggleSelected(toggle, true) }) }) .on('nugget-context-menu', async (event: Electron.IpcMainEvent, frameworkId: string, identifiers: Array<string>) => { entities(event, frameworkId, identifiers).then(({ nuggets }) => { if (nuggets) { if (nuggets.length === 1) { new SuiteMenu((nuggets.pop() as ISuite), event.sender) .open() } else { new TestMenu((nuggets.shift() as ISuite), (nuggets.pop() as ITest), event.sender) .open() } } }) }) .on('select-all', (event: Electron.IpcMainEvent) => { event.sender.selectAll() }) .on('settings-update', (event: Electron.IpcMainEvent, setting: string, value: any) => { state.set(setting, value) event.sender.send('settings-updated', state.get()) }) .on('settings-reset', async (event: Electron.IpcMainEvent) => { await state.reset() const window: ApplicationWindow | null = ApplicationWindow.getFromWebContents(event.sender) if (window) { window.clear() window.reload() } }) ipcMain .handle('project-remove', async (event: Electron.IpcMainInvokeEvent) => { const project: IProject = getProject(event) await project.delete() return state.removeProject(project.getId()) }) ipcMain .handle('project-update', async (event: Electron.IpcMainInvokeEvent, options: ProjectOptions) => { const project: IProject | null = ApplicationWindow.getProjectFromWebContents(event.sender) if (project) { project.updateOptions(options) return project.render() } return null }) ipcMain .handle('project-empty-repositories', async (event: Electron.IpcMainInvokeEvent) => { return getProject(event).getEmptyRepositories().map(repository => repository.render()) }) ipcMain .handle('project-add-repositories-menu', async (event: Electron.IpcMainInvokeEvent) => { return (await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender)!, { properties: ['openDirectory', 'multiSelections'] })).filePaths }) ipcMain .handle('project-context-menu', async (event: Electron.IpcMainInvokeEvent): Promise<void> => { return new Promise(resolve => { new ProjectMenu(getProject(event), event.sender) .after(() => { resolve() }) .open() }) }) ipcMain .handle('repository-add', async (event: Electron.IpcMainInvokeEvent, paths: Array<string>) => { const project: IProject = getProject(event) const repositories = await Promise.all(paths.map(path => { return project.addRepository({ path }) })) project.emitRepositoriesToRenderer() return repositories.map(repository => repository.render()) }) ipcMain .handle('repository-scan', async (event: Electron.IpcMainInvokeEvent, repositoryId: string) => { return await (await getRepository(event, repositoryId)).scan() }) ipcMain .handle('repository-validate', async (event: Electron.IpcMainInvokeEvent, options: PotentialRepositoryOptions) => { const project: IProject = getProject(event) const validator = new RepositoryValidator(project.repositories.map((repository: IRepository) => repository.getPath())) return validator.validate(options).getErrors() }) ipcMain .handle('repository-exists', async (event: Electron.IpcMainInvokeEvent, repositoryId: string) => { return await (await getRepository(event, repositoryId)).exists() }) ipcMain .handle('repository-locate', async (event: Electron.IpcMainInvokeEvent, repositoryId: string) => { return (await getRepository(event, repositoryId)).locate(currentWindow!.getChild()) }) ipcMain .handle('repository-frameworks', async (event: Electron.IpcMainInvokeEvent, repositoryId: string) => { return (await getRepository(event, repositoryId)).frameworks.map(framework => framework.render()) }) ipcMain .handle('repository-context-menu', async (event: Electron.IpcMainInvokeEvent, repositoryId: string): Promise<void> => { const repository: IRepository = await getRepository(event, repositoryId) return new Promise(resolve => { new RepositoryMenu(repository, event.sender) .after(() => { resolve() }) .open() }) }) ipcMain .handle('framework-types', async (event: Electron.IpcMainInvokeEvent) => { return Frameworks.map(framework => { return { ...framework.getDefaults(), instructions: framework.instructions() } }) }) ipcMain .handle('framework-get', async (event: Electron.IpcMainInvokeEvent, frameworkId: string) => { const { framework } = await entities(event, frameworkId) return framework.render() }) ipcMain .handle('framework-get-ledger', async (event: Electron.IpcMainInvokeEvent, frameworkId: string) => { const { framework } = await entities(event, frameworkId) return { ledger: framework.getLedger(), status: framework.getStatusMap() } }) ipcMain .handle('framework-validate', async (event: Electron.IpcMainInvokeEvent, repositoryId: string, options: PotentialFrameworkOptions) => { const repository: IRepository = await getRepository(event, repositoryId) const validator = new FrameworkValidator(repository.getPath()) return validator.validate(options).getErrors() }) ipcMain .handle('framework-autoload-path-menu', async (event: Electron.IpcMainInvokeEvent, defaultPath: string) => { return (await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender)!, { properties: ['openFile'], defaultPath })).filePaths }) ipcMain .handle('framework-tests-path-menu', async (event: Electron.IpcMainInvokeEvent, defaultPath: string) => { return (await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender)!, { properties: ['createDirectory', 'openDirectory'], defaultPath })).filePaths }) ipcMain .handle('framework-identity-menu', async (event: Electron.IpcMainInvokeEvent) => { return (await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender)!, { properties: ['openFile', 'showHiddenFiles'], message: 'Choose a custom SSH key file to use with this connection.\nNote that ~/.ssh/id_rsa and identities defined in your SSH configuration are included by default.' })).filePaths }) ipcMain .handle('framework-context-menu', async (event: Electron.IpcMainInvokeEvent, frameworkId: string, rect?: DOMRect): Promise<void> => { const { repository, framework } = await entities(event, frameworkId) return new Promise(resolve => { new FrameworkMenu(repository, framework, event.sender) .attachTo(rect) .after(() => { resolve() }) .open() }) }) ipcMain .handle('test-get', async (event: Electron.IpcMainInvokeEvent, frameworkId: string, identifiers: Array<string>) => { try { const { repository, framework, nuggets, nugget } = await entities(event, frameworkId, identifiers) return { repository: repository.render(), framework: framework.render(), nuggets: nuggets!.map((nugget: Nugget) => nugget.render(false)), nugget: nugget!.render(false), results: { ...(nugget as ITest)!.getResult(), 'suite-console': (nuggets![0] as ISuite).getConsole() } } } catch (_) { // If any entity is not found while trying to load a test, assume // something's been removed and force the user to select one again. return {} } }) ipcMain .handle('file-context-menu', async (event: Electron.IpcMainInvokeEvent, filePath: string): Promise<void> => { return new Promise(resolve => { new FileMenu(filePath, event.sender) .after(() => { resolve() }) .open() }) }) ipcMain .handle('titlebar-menu', (event: Electron.IpcMainInvokeEvent, item: string, rect: DOMRect): void => { const menu: ContextMenu = applicationMenu.getSection(item) if (!menu) { return } menu .attachTo(rect, false) .after(() => { event.sender.send('titlebar-menu-closed', item) }) .open() }) ipcMain .handle('terms', async (event: Electron.IpcMainInvokeEvent) => { return Fs.readFileSync(Path.join(__static, '/LICENSE'), 'utf8') || '' }) ipcMain .handle('licenses', async (event: Electron.IpcMainInvokeEvent) => { return Fs.readFileSync(Path.join(__static, '/licenses.json'), 'utf8') }) ipcMain .handle('log-project', async (event: Electron.IpcMainInvokeEvent) => { const project: IProject = getProject(event) const projectState = state.project({ id: project.getId() }) return { object: projectState.get(), string: JSON.stringify(projectState.get()) } }) ipcMain .handle('log-settings', async (event: Electron.IpcMainInvokeEvent) => { return { object: state.get(), string: JSON.stringify(state.get()) } })
the_stack
import {BindItem, ContainerContextType, ContainerNodeOptions} from '../../types'; import {IContainerState} from '../Container/reducer'; import {isObjectLike, each, isPlainObject, get} from 'lodash'; import {RunTimeContextCollection} from '../context'; import { compileExpressionString, evalInContext, isExpression, parseExpressionString } from '../util/vm'; import {setWith, deleteWith, getRuntimeContext, injectFilterIntoContext, combineKeys} from '../util/util'; import {parseExpressionToken} from 'rcre-runtime'; /** * 是否是不会被同步到父级的值 * @param value * @returns {boolean} */ function isUnExportValue(value: any) { return value === null || value === undefined; } export class ContainerNode { public model: string; public parent: ContainerNode | undefined; public children: ContainerNode[]; public props?: Object; public export?: Object | string; public bind?: BindItem[]; public options: ContainerNodeOptions; constructor( model: string, props?: Object, _export?: Object, bind?: BindItem[], options: ContainerNodeOptions = {} ) { this.model = model; this.children = []; this.export = _export; this.props = props; this.bind = bind; this.options = options; } public addChild(child: ContainerNode) { if (child.parent !== this) { child.parent = this; } this.children.push(child); } public removeChild(child: ContainerNode) { let index = this.children.indexOf(child); if (index >= 0) { this.children.splice(index, 1); } } } /** * 自动根据Container组件的export或者bind属性。来同步数据到state。 * @param {IContainerState} state * @param {ContainerNode[]} affectNode * @param {ContainerNode} node * @param {Object} context */ export function syncExportContainerState( state: IContainerState, affectNode: ContainerNode[], context: RunTimeContextCollection, node?: ContainerNode ) { if (!node) { return state; } if (affectNode.indexOf(node) === -1) { affectNode.push(node); } let exportConfig = node.export; let bindConfig = node.bind; if (!exportConfig && !bindConfig) { return state; } if (exportConfig && bindConfig) { console.error('bind和export功能不建议一起使用,会有值覆盖的风险'); return state; } let model = node.model; let $data = state[model]; let runTime = getRuntimeContext({ $data: $data } as ContainerContextType, context.rcre, { iteratorContext: context.iterator }); let parentNode = node.parent; if (parentNode) { let parentModel = parentNode.model; if (!state[parentModel]) { state[parentModel] = {}; } if (isObjectLike(exportConfig)) { let exportValue = compileExpressionString(exportConfig, runTime) as Object; each(exportValue, (value, key) => { if (isUnExportValue(value) && node.options.noNilToParent) { return; } state = setWith(state, combineKeys(parentModel, key), value); }); } else if (isExpression(exportConfig)) { let exportValue = parseExpressionString(exportConfig, runTime); if (isObjectLike(exportValue)) { each(exportValue, (value, key) => { if (isUnExportValue(value) && node.options.noNilToParent) { return; } state = setWith(state, combineKeys(parentModel, key), value); }); } } else if (bindConfig instanceof Array) { bindConfig.forEach(bind => { if (!bind.parent || !bind.child) { console.error('设置Bind属性的时候,parent和child都是必须选项'); return; } let childValue = state[model][bind.child]; if (isUnExportValue(childValue) && node.options.noNilToParent) { return; } state = setWith(state, combineKeys(parentModel, bind.parent), childValue); }); } else if (exportConfig === 'all') { Object.keys(state[model]).forEach(key => { state = setWith(state, combineKeys(parentModel, key), state[model][key]); }); } state = syncExportContainerState(state, affectNode, context, parentNode); } return state; } export function syncPropsContainerState(state: IContainerState, context: RunTimeContextCollection, node?: ContainerNode) { if (!node) { return state; } if (node.children.length > 0) { let model = node.model; let $data = state[model]; for (let child of node.children) { if (!child.props && !child.bind) { continue; } let inheritValue = {}; let childModel = child.model; let child$data = state[childModel]; let childRunTime = getRuntimeContext({ $data: child$data, $parent: $data } as ContainerContextType, context.rcre, { iteratorContext: context.iterator }); let props = child.props; let bindList = child.bind; if (typeof props === 'string' || typeof props === 'function') { if (props === 'inherit') { inheritValue = $data; } else if (isExpression(props)) { inheritValue = parseExpressionString(props, childRunTime); } } else if (typeof props === 'object') { each(props, (expression: any, name) => { if (typeof expression === 'string' || typeof expression === 'function') { if (!isExpression(expression)) { inheritValue[name] = expression; return; } inheritValue[name] = parseExpressionString(expression, childRunTime); } else if (typeof expression === 'object') { let prop = expression.prop; let priority = expression.priority; // priority === child and nothing// let result = parseExpressionString(prop, childRunTime); // 字级优先,而字级又没有值的时候,就给个初始值 if (priority === 'parent') { console.warn('priority === parent is no longer supported'); } inheritValue = setWith(inheritValue, name, result); } else { inheritValue[name] = expression; } }); } else if (bindList instanceof Array) { bindList.forEach(bind => { if (!bind.parent || !bind.child) { console.error('设置Bind属性的时候,parent和child都是必须选项'); return; } let parentValue = get(state[model], bind.parent); state = setWith(state, combineKeys(childModel, bind.child), parentValue); }); } if (!state[childModel]) { state = setWith(state, childModel, {}); } each(inheritValue, (value, key) => { state = setWith(state, combineKeys(childModel, key), value); }); state = syncPropsContainerState(state, context, child); } } return state; } /** * 同步删除当前container中的字段 * * @param {IContainerState} state * @param {string} key * @param {Object} context * @param {ContainerNode} node * @returns {any} */ export function syncDeleteContainerState(state: IContainerState, context: RunTimeContextCollection, node?: ContainerNode, key?: string) { if (!node) { return state; } let exportConfig = node.export; let bindConfig = node.bind; if (!exportConfig && !bindConfig) { return state; } let model = node.model; let parentNode = node.parent; if (parentNode) { let parentModel = parentNode.model; if (exportConfig) { if (typeof exportConfig === 'string' || typeof exportConfig === 'function') { let runTime = getRuntimeContext({ $data: state[model] } as ContainerContextType, context.rcre, { iteratorContext: context.iterator }); let ret = parseExpressionString(exportConfig, runTime); if (!isPlainObject(ret)) { console.warn('使用字符串的export功能,返回值必须是一个普通对象'); return state; } if (key && !node.options.forceSyncDelete) { console.warn('使用字符串的export配置将无法执行按照key进行删除的操作,请使用对象作为export的值,让RCRE能够获取到具体要删除的key'); return state; } Object.keys(ret).map((depKey) => { state = deleteWith(state, combineKeys(parentModel, depKey)); }); } else if (typeof exportConfig === 'object' && !Array.isArray(exportConfig)) { let depKey = {}; each(exportConfig, (expression: any, name) => { if (!isExpression(expression)) { return; } let runTime = getRuntimeContext({ $data: state[model] } as ContainerContextType, context.rcre, { iteratorContext: context.iterator }); let proxyHandler = { get(obj: any, prop: string) { depKey[name] = prop; return obj[prop]; } }; runTime.$data = new Proxy(runTime.$data, proxyHandler); injectFilterIntoContext(runTime); if (typeof expression === 'string') { let tokens = parseExpressionToken(expression); tokens.forEach(token => { if (!token.token) { return; } try { evalInContext(token.token, runTime); } catch (e) { console.error('RCRE CORE: runTime error when collect delete properties; token=' + token.token + '\n errmsg: ' + e.message + '\n'); console.groupCollapsed('runTime: '); console.error(runTime); console.groupEnd(); } }); } else if (typeof expression === 'function') { expression(runTime); } }); if (key) { each(depKey, (dep, depName) => { if (dep === key) { state = deleteWith(state, combineKeys(parentModel, depName)); } }); } else { each(depKey, (dep, depName) => { state = deleteWith(state, combineKeys(parentModel, depName)); }); } } state = syncDeleteContainerState(state, context, parentNode, key); } return state; } return state; }
the_stack
import { Construct } from 'constructs'; import { CfnHook } from './cfn-hook'; import { FromCloudFormationOptions } from './cfn-parse'; /** * The possible types of traffic shifting for the blue-green deployment configuration. * * The type of the {@link CfnTrafficRoutingConfig.type} property. * * @stability stable */ export declare enum CfnTrafficRoutingType { /** * Switch from blue to green at once. * * @stability stable */ ALL_AT_ONCE = "AllAtOnce", /** * Specifies a configuration that shifts traffic from blue to green in two increments. * * @stability stable */ TIME_BASED_CANARY = "TimeBasedCanary", /** * Specifies a configuration that shifts traffic from blue to green in equal increments, with an equal number of minutes between each increment. * * @stability stable */ TIME_BASED_LINEAR = "TimeBasedLinear" } /** * The traffic routing configuration if {@link CfnTrafficRoutingConfig.type} is {@link CfnTrafficRoutingType.TIME_BASED_CANARY}. * * @stability stable */ export interface CfnTrafficRoutingTimeBasedCanary { /** * The percentage of traffic to shift in the first increment of a time-based canary deployment. * * The step percentage must be 14% or greater. * * @default 15 * @stability stable */ readonly stepPercentage?: number; /** * The number of minutes between the first and second traffic shifts of a time-based canary deployment. * * @default 5 * @stability stable */ readonly bakeTimeMins?: number; } /** * The traffic routing configuration if {@link CfnTrafficRoutingConfig.type} is {@link CfnTrafficRoutingType.TIME_BASED_LINEAR}. * * @stability stable */ export interface CfnTrafficRoutingTimeBasedLinear { /** * The percentage of traffic that is shifted at the start of each increment of a time-based linear deployment. * * The step percentage must be 14% or greater. * * @default 15 * @stability stable */ readonly stepPercentage?: number; /** * The number of minutes between the first and second traffic shifts of a time-based linear deployment. * * @default 5 * @stability stable */ readonly bakeTimeMins?: number; } /** * Traffic routing configuration settings. * * The type of the {@link CfnCodeDeployBlueGreenHookProps.trafficRoutingConfig} property. * * @stability stable */ export interface CfnTrafficRoutingConfig { /** * The type of traffic shifting used by the blue-green deployment configuration. * * @stability stable */ readonly type: CfnTrafficRoutingType; /** * The configuration for traffic routing when {@link type} is {@link CfnTrafficRoutingType.TIME_BASED_CANARY}. * * @default - none * @stability stable */ readonly timeBasedCanary?: CfnTrafficRoutingTimeBasedCanary; /** * The configuration for traffic routing when {@link type} is {@link CfnTrafficRoutingType.TIME_BASED_LINEAR}. * * @default - none * @stability stable */ readonly timeBasedLinear?: CfnTrafficRoutingTimeBasedLinear; } /** * Additional options for the blue/green deployment. * * The type of the {@link CfnCodeDeployBlueGreenHookProps.additionalOptions} property. * * @stability stable */ export interface CfnCodeDeployBlueGreenAdditionalOptions { /** * Specifies time to wait, in minutes, before terminating the blue resources. * * @default - 5 minutes * @stability stable */ readonly terminationWaitTimeInMinutes?: number; } /** * Lifecycle events for blue-green deployments. * * The type of the {@link CfnCodeDeployBlueGreenHookProps.lifecycleEventHooks} property. * * @stability stable */ export interface CfnCodeDeployBlueGreenLifecycleEventHooks { /** * Function to use to run tasks before the replacement task set is created. * * @default - none * @stability stable */ readonly beforeInstall?: string; /** * Function to use to run tasks after the replacement task set is created and one of the target groups is associated with it. * * @default - none * @stability stable */ readonly afterInstall?: string; /** * Function to use to run tasks after the test listener serves traffic to the replacement task set. * * @default - none * @stability stable */ readonly afterAllowTestTraffic?: string; /** * Function to use to run tasks after the second target group is associated with the replacement task set, but before traffic is shifted to the replacement task set. * * @default - none * @stability stable */ readonly beforeAllowTraffic?: string; /** * Function to use to run tasks after the second target group serves traffic to the replacement task set. * * @default - none * @stability stable */ readonly afterAllowTraffic?: string; } /** * Type of the {@link CfnCodeDeployBlueGreenApplication.target} property. * * @stability stable */ export interface CfnCodeDeployBlueGreenApplicationTarget { /** * The resource type of the target being deployed. * * Right now, the only allowed value is 'AWS::ECS::Service'. * * @stability stable */ readonly type: string; /** * The logical id of the target resource. * * @stability stable */ readonly logicalId: string; } /** * A traffic route, representing where the traffic is being directed to. * * @stability stable */ export interface CfnTrafficRoute { /** * The resource type of the route. * * Today, the only allowed value is 'AWS::ElasticLoadBalancingV2::Listener'. * * @stability stable */ readonly type: string; /** * The logical id of the target resource. * * @stability stable */ readonly logicalId: string; } /** * Type of the {@link CfnCodeDeployBlueGreenEcsAttributes.trafficRouting} property. * * @stability stable */ export interface CfnTrafficRouting { /** * The listener to be used by your load balancer to direct traffic to your target groups. * * @stability stable */ readonly prodTrafficRoute: CfnTrafficRoute; /** * The listener to be used by your load balancer to direct traffic to your target groups. * * @stability stable */ readonly testTrafficRoute: CfnTrafficRoute; /** * The logical IDs of the blue and green, respectively, AWS::ElasticLoadBalancingV2::TargetGroup target groups. * * @stability stable */ readonly targetGroups: string[]; } /** * The attributes of the ECS Service being deployed. * * Type of the {@link CfnCodeDeployBlueGreenApplication.ecsAttributes} property. * * @stability stable */ export interface CfnCodeDeployBlueGreenEcsAttributes { /** * The logical IDs of the blue and green, respectively, AWS::ECS::TaskDefinition task definitions. * * @stability stable */ readonly taskDefinitions: string[]; /** * The logical IDs of the blue and green, respectively, AWS::ECS::TaskSet task sets. * * @stability stable */ readonly taskSets: string[]; /** * The traffic routing configuration. * * @stability stable */ readonly trafficRouting: CfnTrafficRouting; } /** * The application actually being deployed. * * Type of the {@link CfnCodeDeployBlueGreenHookProps.applications} property. * * @stability stable */ export interface CfnCodeDeployBlueGreenApplication { /** * The target that is being deployed. * * @stability stable */ readonly target: CfnCodeDeployBlueGreenApplicationTarget; /** * The detailed attributes of the deployed target. * * @stability stable */ readonly ecsAttributes: CfnCodeDeployBlueGreenEcsAttributes; } /** * Construction properties of {@link CfnCodeDeployBlueGreenHook}. * * @stability stable */ export interface CfnCodeDeployBlueGreenHookProps { /** * The IAM Role for CloudFormation to use to perform blue-green deployments. * * @stability stable */ readonly serviceRole: string; /** * Properties of the Amazon ECS applications being deployed. * * @stability stable */ readonly applications: CfnCodeDeployBlueGreenApplication[]; /** * Traffic routing configuration settings. * * @default - time-based canary traffic shifting, with a 15% step percentage and a five minute bake time * @stability stable */ readonly trafficRoutingConfig?: CfnTrafficRoutingConfig; /** * Additional options for the blue/green deployment. * * @default - no additional options * @stability stable */ readonly additionalOptions?: CfnCodeDeployBlueGreenAdditionalOptions; /** * Use lifecycle event hooks to specify a Lambda function that CodeDeploy can call to validate a deployment. * * You can use the same function or a different one for deployment lifecycle events. * Following completion of the validation tests, * the Lambda {@link CfnCodeDeployBlueGreenLifecycleEventHooks.afterAllowTraffic} * function calls back CodeDeploy and delivers a result of 'Succeeded' or 'Failed'. * * @default - no lifecycle event hooks * @stability stable */ readonly lifecycleEventHooks?: CfnCodeDeployBlueGreenLifecycleEventHooks; } /** * A CloudFormation Hook for CodeDeploy blue-green ECS deployments. * * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/blue-green.html#blue-green-template-reference * @stability stable */ export declare class CfnCodeDeployBlueGreenHook extends CfnHook { /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: Construct, id: string, hookAttributes: any, options: FromCloudFormationOptions): CfnCodeDeployBlueGreenHook; private _serviceRole; private _applications; private _trafficRoutingConfig?; private _additionalOptions?; private _lifecycleEventHooks?; /** * Creates a new CodeDeploy blue-green ECS Hook. * * @param scope the scope to create the hook in (usually the containing Stack object). * @param id the identifier of the construct - will be used to generate the logical ID of the Hook. * @param props the properties of the Hook. * @stability stable */ constructor(scope: Construct, id: string, props: CfnCodeDeployBlueGreenHookProps); /** * The IAM Role for CloudFormation to use to perform blue-green deployments. * * @stability stable */ get serviceRole(): string; /** * The IAM Role for CloudFormation to use to perform blue-green deployments. * * @stability stable */ set serviceRole(serviceRole: string); /** * Properties of the Amazon ECS applications being deployed. * * @stability stable */ get applications(): CfnCodeDeployBlueGreenApplication[]; /** * Properties of the Amazon ECS applications being deployed. * * @stability stable */ set applications(value: CfnCodeDeployBlueGreenApplication[]); /** * Traffic routing configuration settings. * * @default - time-based canary traffic shifting, with a 15% step percentage and a five minute bake time * @stability stable */ get trafficRoutingConfig(): CfnTrafficRoutingConfig | undefined; /** * Traffic routing configuration settings. * * @default - time-based canary traffic shifting, with a 15% step percentage and a five minute bake time * @stability stable */ set trafficRoutingConfig(value: CfnTrafficRoutingConfig | undefined); /** * Additional options for the blue/green deployment. * * @default - no additional options * @stability stable */ get additionalOptions(): CfnCodeDeployBlueGreenAdditionalOptions | undefined; /** * Additional options for the blue/green deployment. * * @default - no additional options * @stability stable */ set additionalOptions(value: CfnCodeDeployBlueGreenAdditionalOptions | undefined); /** * Use lifecycle event hooks to specify a Lambda function that CodeDeploy can call to validate a deployment. * * You can use the same function or a different one for deployment lifecycle events. * Following completion of the validation tests, * the Lambda {@link CfnCodeDeployBlueGreenLifecycleEventHooks.afterAllowTraffic} * function calls back CodeDeploy and delivers a result of 'Succeeded' or 'Failed'. * * @default - no lifecycle event hooks * @stability stable */ get lifecycleEventHooks(): CfnCodeDeployBlueGreenLifecycleEventHooks | undefined; /** * Use lifecycle event hooks to specify a Lambda function that CodeDeploy can call to validate a deployment. * * You can use the same function or a different one for deployment lifecycle events. * Following completion of the validation tests, * the Lambda {@link CfnCodeDeployBlueGreenLifecycleEventHooks.afterAllowTraffic} * function calls back CodeDeploy and delivers a result of 'Succeeded' or 'Failed'. * * @default - no lifecycle event hooks * @stability stable */ set lifecycleEventHooks(value: CfnCodeDeployBlueGreenLifecycleEventHooks | undefined); /** * @stability stable */ protected renderProperties(_props?: { [p: string]: any; }): { [p: string]: any; } | undefined; }
the_stack
import { SushiTokenInstance, MockERC20Instance, MasterChefInstance, UniswapV2FactoryInstance, UniswapV2Router02Instance, UniswapV2PairInstance, StrategyAllETHOnlyInstance, StrategyLiquidateInstance, BankInstance, SimpleBankConfigInstance, SushiswapGoblinInstance, WETHInstance, } from '../typechain'; const SushiToken = artifacts.require('SushiToken'); const MasterChef = artifacts.require('MasterChef'); const UniswapV2Factory = artifacts.require('UniswapV2Factory'); const UniswapV2Router02 = artifacts.require('UniswapV2Router02'); const UniswapV2Pair = artifacts.require('UniswapV2Pair'); const StrategyAllETHOnly = artifacts.require('StrategyAllETHOnly'); const StrategyLiquidate = artifacts.require('StrategyLiquidate'); const Bank = artifacts.require('Bank'); const SimpleBankConfig = artifacts.require('SimpleBankConfig'); const SushiswapGoblin = artifacts.require('SushiswapGoblin'); const WETH = artifacts.require('WETH'); const MockERC20 = artifacts.require('MockERC20'); const { expectRevert, time, BN, ether } = require('@openzeppelin/test-helpers'); // Assert that actual is less than 0.01% difference from expected function assertAlmostEqual(expected: string | BN, actual: string | BN) { const expectedBN = BN.isBN(expected) ? expected : new BN(expected); const actualBN = BN.isBN(actual) ? actual : new BN(actual); const diffBN = expectedBN.gt(actualBN) ? expectedBN.sub(actualBN) : actualBN.sub(expectedBN); return assert.ok( diffBN.lt(expectedBN.div(new BN('1000'))), `Not almost equal. Expected ${expectedBN.toString()}. Actual ${actualBN.toString()}` ); } const FOREVER = '2000000000'; const TOLERANCE = new BN('10000'); contract('SushiswapBank', ([deployer, alice, bob, eve]) => { const SUSHI_REWARD_PER_BLOCK = ether('0.076'); const REINVEST_BOUNTY_BPS = new BN('100'); // 1% reinvest bounty const RESERVE_POOL_BPS = new BN('1000'); // 10% reserve pool const KILL_PRIZE_BPS = new BN('1000'); // 10% Kill prize const INTEREST_RATE = new BN('3472222222222'); // 30% per year const MIN_DEBT_SIZE = ether('1'); // 1 ETH min debt size const WORK_FACTOR = new BN('7000'); const KILL_FACTOR = new BN('8000'); let factory: UniswapV2FactoryInstance; let weth: WETHInstance; let router: UniswapV2Router02Instance; let token: MockERC20Instance; let sushi: SushiTokenInstance; let lp: UniswapV2PairInstance; let addStrat: StrategyAllETHOnlyInstance; let liqStrat: StrategyLiquidateInstance; let config: SimpleBankConfigInstance; let bank: BankInstance; let masterChef: MasterChefInstance; let poolId: number; let goblin: SushiswapGoblinInstance; beforeEach(async () => { factory = await UniswapV2Factory.new(deployer); weth = await WETH.new(); router = await UniswapV2Router02.new(factory.address, weth.address); token = await MockERC20.new('MOCK', 'MOCK'); sushi = await SushiToken.new(); await token.mint(deployer, ether('100')); await token.mint(alice, ether('100')); await token.mint(bob, ether('100')); await sushi.mint(deployer, ether('100')); await factory.createPair(weth.address, token.address); lp = await UniswapV2Pair.at(await factory.getPair(token.address, weth.address)); addStrat = await StrategyAllETHOnly.new(router.address); liqStrat = await StrategyLiquidate.new(router.address); config = await SimpleBankConfig.new(MIN_DEBT_SIZE, INTEREST_RATE, RESERVE_POOL_BPS, KILL_PRIZE_BPS); bank = await Bank.new(config.address); masterChef = await MasterChef.new(sushi.address, deployer, SUSHI_REWARD_PER_BLOCK, 0, 0); // Transfer ownership so masterChef can mint SUSHI await sushi.transferOwnership(masterChef.address); // Add lp to masterChef's pool await masterChef.add(1, lp.address, false); poolId = 0; goblin = await SushiswapGoblin.new( bank.address, masterChef.address, router.address, poolId, addStrat.address, liqStrat.address, REINVEST_BOUNTY_BPS ); await config.setGoblin(goblin.address, true, true, WORK_FACTOR, KILL_FACTOR); // Deployer adds 1e17 MOCK + 1e18 WEI await token.approve(router.address, ether('0.1')); await router.addLiquidityETH(token.address, ether('0.1'), '0', '0', deployer, FOREVER, { value: ether('1'), }); // Deployer adds 1e17 SUSHI + 1e18 WEI await sushi.approve(router.address, ether('1')); await router.addLiquidityETH(sushi.address, ether('0.1'), '0', '0', deployer, FOREVER, { value: ether('1'), }); }); it('should has MOCK as fToken in SushiswapGoblin', async () => { // Deployer sends some LP tokens to Alice and Bob expect(await goblin.fToken()).to.be.equal(token.address); }); it('should give rewards out when you stake LP tokens', async () => { // Deployer sends some LP tokens to Alice and Bob await lp.transfer(alice, ether('0.05')); await lp.transfer(bob, ether('0.05')); // Alice stakes 0.01 LP tokens and waits for 1 day await lp.approve(masterChef.address, ether('100'), { from: alice }); await lp.approve(masterChef.address, ether('100'), { from: bob }); await masterChef.deposit(poolId, ether('0.01'), { from: alice }); await masterChef.deposit(poolId, ether('0.02'), { from: bob }); // alice +1 Reward await masterChef.withdraw(poolId, ether('0.02'), { from: bob }); // alice +1/3 Reward Bob + 2/3 Reward await masterChef.withdraw(poolId, ether('0.01'), { from: alice }); // alice +1 Reward expect(await sushi.balanceOf(alice)).to.be.bignumber.closeTo( SUSHI_REWARD_PER_BLOCK.mul(new BN('7')).div(new BN('3')), TOLERANCE ); expect(await sushi.balanceOf(bob)).to.be.bignumber.closeTo( SUSHI_REWARD_PER_BLOCK.mul(new BN('2')).div(new BN('3')), TOLERANCE ); }); it('should allow positions without debt', async () => { // Deployer deposits 3 ETH to the bank await bank.deposit({ value: ether('3') }); // Alice can take 0 debt ok await bank.work( 0, goblin.address, ether('0'), '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('0.3'), from: alice } ); }); it('should not allow positions with debt less than MIN_DEBT_SIZE', async () => { // Deployer deposits 3 ETH to the bank await bank.deposit({ value: ether('3') }); // Alice cannot take 0.3 debt because it is too small await expectRevert( bank.work( 0, goblin.address, ether('0.3'), '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('0.3'), from: alice } ), 'too small debt size' ); }); it('should not allow positions with bad work factor', async () => { // Deployer deposits 3 ETH to the bank await bank.deposit({ value: ether('3') }); // Alice cannot take 1 ETH loan but only put in 0.3 ETH await expectRevert( bank.work( 0, goblin.address, ether('1'), '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('0.3'), from: alice } ), 'bad work factor' ); }); it('should not allow positions if Bank has less ETH than requested loan', async () => { // Alice cannot take 1 ETH loan because the contract does not have it await expectRevert( bank.work( 0, goblin.address, ether('1'), '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('1'), from: alice } ), 'insufficient ETH in the bank' ); }); it('should work', async () => { // Deployer deposits 3 ETH to the bank const deposit = ether('3'); await bank.deposit({ value: deposit }); // Now Alice can take 1 ETH loan + 1 ETH of her to create a new position const loan = ether('1'); await bank.work( 0, goblin.address, loan, '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('1'), from: alice } ); // Her position should have ~2 ETH health (minus some small trading fee) assert.equal('1997459271062521105', await goblin.health('1')); await time.increase(time.duration.days(1)); await goblin.reinvest({ from: eve }); assertAlmostEqual( SUSHI_REWARD_PER_BLOCK.mul(new BN('2')).mul(REINVEST_BOUNTY_BPS).div(new BN('10000')), await sushi.balanceOf(eve) ); await bank.deposit(); // Random action to trigger interest computation const healthDebt = await bank.positionInfo('1'); expect(healthDebt[0]).to.be.bignumber.above(ether('2')); const interest = ether('0.3'); //30% interest rate assertAlmostEqual(healthDebt[1], interest.add(loan)); assertAlmostEqual(await web3.eth.getBalance(bank.address), deposit.sub(loan)); assertAlmostEqual(await bank.glbDebtVal(), interest.add(loan)); const reservePool = interest.mul(RESERVE_POOL_BPS).div(new BN('10000')); assertAlmostEqual(reservePool, await bank.reservePool()); assertAlmostEqual(deposit.add(interest).sub(reservePool), await bank.totalETH()); }); it('should not able to liquidate healthy position', async () => { // Deployer deposits 3 ETH to the bank const deposit = ether('3'); await bank.deposit({ value: deposit }); // Now Alice can take 1 ETH loan + 1 ETH of her to create a new position const loan = ether('1'); await bank.work( 0, goblin.address, loan, '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('1'), from: alice } ); // Her position should have ~2 ETH health (minus some small trading fee) await time.increase(time.duration.days(1)); await goblin.reinvest({ from: eve }); await bank.deposit(); // Random action to trigger interest computation // You can't liquidate her position yet await expectRevert(bank.kill('1'), "can't liquidate", { from: eve }); await time.increase(time.duration.days(1)); await expectRevert(bank.kill('1'), "can't liquidate", { from: eve }); }); it('should has correct interest rate growth', async () => { // Deployer deposits 3 ETH to the bank const deposit = ether('3'); await bank.deposit({ value: deposit }); // Now Alice can take 1 ETH loan + 1 ETH of her to create a new position const loan = ether('1'); await bank.work( 0, goblin.address, loan, '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('1'), from: alice } ); await time.increase(time.duration.days(1)); await goblin.reinvest({ from: eve }); await bank.deposit(); // Random action to trigger interest computation await time.increase(time.duration.days(1)); await time.increase(time.duration.days(1)); await bank.deposit(); // Random action to trigger interest computation const interest = ether('0.3'); //30% interest rate const reservePool = interest.mul(RESERVE_POOL_BPS).div(new BN('10000')); assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(new BN(13)).div(new BN(10))) .add(interest.sub(reservePool).mul(new BN(13)).div(new BN(10))), await bank.totalETH() ); }); it('should be able to liquidate bad position', async () => { // Deployer deposits 3 ETH to the bank const deposit = ether('3'); await bank.deposit({ value: deposit }); // Now Alice can take 1 ETH loan + 1 ETH of her to create a new position const loan = ether('1'); await bank.work( 0, goblin.address, loan, '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('1'), from: alice } ); await time.increase(time.duration.days(1)); await goblin.reinvest({ from: eve }); await bank.deposit(); // Random action to trigger interest computation await time.increase(time.duration.days(1)); await time.increase(time.duration.days(1)); await bank.deposit(); // Random action to trigger interest computation const interest = ether('0.3'); //30% interest rate const reservePool = interest.mul(RESERVE_POOL_BPS).div(new BN('10000')); assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(new BN(13)).div(new BN(10))) .add(interest.sub(reservePool).mul(new BN(13)).div(new BN(10))), await bank.totalETH() ); const eveBefore = new BN(await web3.eth.getBalance(eve)); // Now you can liquidate because of the insane interest rate await bank.kill('1', { from: eve }); expect(new BN(await web3.eth.getBalance(eve))).to.be.bignumber.gt(eveBefore); //Should get rewards assertAlmostEqual( deposit .add(interest) .add(interest.mul(new BN(13)).div(new BN(10))) .add(interest.mul(new BN(13)).div(new BN(10))), await web3.eth.getBalance(bank.address) ); assert.equal('0', await bank.glbDebtVal()); assertAlmostEqual( reservePool.add(reservePool.mul(new BN(13)).div(new BN(10))).add(reservePool.mul(new BN(13)).div(new BN(10))), await bank.reservePool() ); assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(new BN(13)).div(new BN(10))) .add(interest.sub(reservePool).mul(new BN(13)).div(new BN(10))), await bank.totalETH() ); // Alice creates a new position again console.log( ( await bank.work( 0, goblin.address, ether('1'), '0', web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('1'), from: alice } ) ).receipt.gasUsed ); // She can close position await bank.work( 2, goblin.address, '0', '115792089237316195423570985008687907853269984665640564039457584007913129639935', web3.eth.abi.encodeParameters( ['address', 'bytes'], [liqStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { from: alice } ); }); it('Should deposit and withdraw eth from Bank (bad debt case)', async () => { // Deployer deposits 10 ETH to the bank const deposit = ether('10'); await bank.deposit({ value: deposit }); expect(await bank.balanceOf(deployer)).to.be.bignumber.equal(deposit); // Bob borrows 2 ETH loan const loan = ether('2'); await bank.work( 0, goblin.address, loan, '0', // max return = 0, don't return ETH to the debt web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('1'), from: bob } ); expect(new BN(await web3.eth.getBalance(bank.address))).to.be.bignumber.equal(deposit.sub(loan)); expect(await bank.glbDebtVal()).to.be.bignumber.equal(loan); expect(await bank.totalETH()).to.be.bignumber.equal(deposit); // Alice deposits 2 ETH const aliceDeposit = ether('2'); await bank.deposit({ value: aliceDeposit, from: alice, }); // check Alice gETH balance = 2/10 * 10 = 2 gETH assertAlmostEqual(aliceDeposit, await bank.balanceOf(alice)); assertAlmostEqual(deposit.add(aliceDeposit), await bank.totalSupply()); // Simulate ETH price is very high by swap fToken to ETH (reduce ETH supply) await token.mint(deployer, ether('100')); await token.approve(router.address, ether('100')); await router.swapExactTokensForTokens(ether('100'), '0', [token.address, weth.address], deployer, FOREVER); assertAlmostEqual(deposit.sub(loan).add(aliceDeposit), await web3.eth.getBalance(bank.address)); // Alice liquidates Bob position#1 let aliceBefore = new BN(await web3.eth.getBalance(alice)); await bank.kill(1, { from: alice, gasPrice: 0 }); let aliceAfter = new BN(await web3.eth.getBalance(alice)); // Bank balance is increase by liquidation assertAlmostEqual('10002702699312215556', await web3.eth.getBalance(bank.address)); // Alice is liquidator, Alice should receive 10% Kill prize // ETH back from liquidation 3002999235795062, 10% of 3002999235795062 is 300299923579506 assertAlmostEqual('300299923579506', aliceAfter.sub(aliceBefore)); // Alice withdraws 2 gETH aliceBefore = new BN(await web3.eth.getBalance(alice)); await bank.withdraw(await bank.balanceOf(alice), { from: alice, gasPrice: 0, }); aliceAfter = new BN(await web3.eth.getBalance(alice)); // alice gots 2/12 * 10.002702699312215556 = 1.667117116552036 assertAlmostEqual('1667117116552036400', aliceAfter.sub(aliceBefore)); }); it('should liquidate user position correctly', async () => { // Bob deposits 20 ETH await bank.deposit({ value: ether('20'), from: bob, }); // Position#1: Alice borrows 10 ETH loan await bank.work( 0, goblin.address, ether('10'), '0', // max return = 0, don't return ETH to the debt web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('10'), from: alice } ); await token.mint(deployer, ether('100')); await token.approve(router.address, ether('100')); // Price swing 10% // Add more token to the pool equals to sqrt(10*((0.1)**2) / 9) - 0.1 = 0.005409255338945984, (0.1 is the balance of token in the pool) await router.swapExactTokensForTokens( web3.utils.toWei('0.005409255338945984', 'ether'), '0', [token.address, weth.address], deployer, FOREVER ); await expectRevert(bank.kill('1'), "can't liquidate"); // Price swing 20% // Add more token to the pool equals to // sqrt(10*((0.10540925533894599)**2) / 8) - 0.10540925533894599 = 0.012441874858811944 // (0.10540925533894599 is the balance of token in the pool) await router.swapExactTokensForTokens( web3.utils.toWei('0.012441874858811944', 'ether'), '0', [token.address, weth.address], deployer, FOREVER ); await expectRevert(bank.kill('1'), "can't liquidate"); // Price swing 23.43% // Existing token on the pool = 0.10540925533894599 + 0.012441874858811944 = 0.11785113019775793 // Add more token to the pool equals to // sqrt(10*((0.11785113019775793)**2) / 7.656999999999999) - 0.11785113019775793 = 0.016829279312591913 await router.swapExactTokensForTokens( web3.utils.toWei('0.016829279312591913', 'ether'), '0', [token.address, weth.address], deployer, FOREVER ); await expectRevert(bank.kill('1'), "can't liquidate"); // Price swing 30% // Existing token on the pool = 0.11785113019775793 + 0.016829279312591913 = 0.13468040951034985 // Add more token to the pool equals to // sqrt(10*((0.13468040951034985)**2) / 7) - 0.13468040951034985 = 0.026293469053292218 await router.swapExactTokensForTokens( web3.utils.toWei('0.026293469053292218', 'ether'), '0', [token.address, weth.address], deployer, FOREVER ); // Bob can kill alice's position await bank.kill('1', { from: bob }); }); it('should reinvest correctly', async () => { // Set Bank's debt interests to 0% per year await config.setParams( ether('1'), // 1 ETH min debt size, '0', // 0% per year '1000', // 10% reserve pool '1000' // 10% Kill prize ); // Set Reinvest bounty to 10% of the reward await goblin.setReinvestBountyBps('1000'); // Bob deposits 10 ETH await bank.deposit({ value: ether('10'), from: bob, gasPrice: 0, }); // Alice deposits 12 ETH await bank.deposit({ value: ether('10'), from: alice, gasPrice: 0, }); // Position#1: Bob borrows 10 ETH loan await bank.work( 0, goblin.address, ether('10'), '0', // max return = 0, don't return ETH to the debt web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('10'), from: bob, gasPrice: 0 } ); // Position#2: Alice borrows 2 ETH loan await bank.work( 0, goblin.address, ether('2'), '0', // max return = 0, don't return ETH to the debt web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: ether('1'), from: alice, gasPrice: 0 } ); // ---------------- Reinvest#1 ------------------- // Wait for 1 day and someone calls reinvest await time.increase(time.duration.days(1)); let [goblinLPBefore, goblinDebtBefore] = await masterChef.userInfo(poolId, goblin.address); await goblin.reinvest({ from: eve }); // Goblin receives 227999999998874730 sushi as a reward // Eve got 10% of 227999999998874730 sushi = 0.1 * 227999999998874730 = 22799999999887473 bounty assertAlmostEqual('22799999999887473', await sushi.balanceOf(eve)); // Remaining Goblin reward = 227999999998874730 - 22799999999887473 = 205199999998987257 (~90% reward) // Convert 205199999998987257 sushi to 671683776318381694 ETH // Convert ETH to 1252466339860712438 LP token and stake let [goblinLPAfter, goblinDebtAfter] = await masterChef.userInfo(poolId, goblin.address); // LP tokens of goblin should be inceased from reinvestment // assertAlmostEqual("1252466339860712438", goblinLPAfter.sub(goblinLPBefore)); expect(goblinLPAfter).to.be.bignumber.gt(goblinLPBefore); // Check Bob position info await goblin.health('1'); let [bobHealth, bobDebtToShare] = await bank.positionInfo('1'); expect(bobHealth).to.be.bignumber.gt(ether('20')); // Get Reward and increase health assertAlmostEqual(ether('10'), bobDebtToShare); //Why this is not 13?? // Check Alice position info await goblin.health('2'); let [aliceHealth, aliceDebtToShare] = await bank.positionInfo('2'); expect(aliceHealth).to.be.bignumber.gt(ether('3')); // Get Reward and increase health assertAlmostEqual(ether('2'), aliceDebtToShare); // ---------------- Reinvest#2 ------------------- // Wait for 1 day and someone calls reinvest await time.increase(time.duration.days(1)); [goblinLPBefore, goblinDebtBefore] = await masterChef.userInfo(poolId, goblin.address); await goblin.reinvest({ from: eve }); // Goblin receives 151999999999376792 sushi as a reward // Eve got 10% of 151999999999376792 sushi = 0.1 * 151999999999376792 = 15199999999937679 bounty // Now Eve have 22799999999887473 sushi (1st) + 15199999999937679 sushi (2nd) = 37999999999825152 sushi assertAlmostEqual('37999999999825152', await sushi.balanceOf(eve)); // Remaining Goblin reward = 142858796296283038 - 14285879629628304 = 128572916666654734 (~90% reward) // Convert 128572916666654734 uni to 157462478899282341 ETH // Convert ETH to 5001669421841640 LP token [goblinLPAfter, goblinDebtAfter] = await masterChef.userInfo(poolId, goblin.address); // LP tokens of goblin should be inceased from reinvestment expect(goblinLPAfter).to.be.bignumber.gt(goblinLPBefore); // Check Bob position info [bobHealth, bobDebtToShare] = await bank.positionInfo('1'); expect(bobHealth).to.be.bignumber.gt(ether('20')); // Get Reward and increase health assertAlmostEqual(ether('10'), bobDebtToShare); // Check Alice position info [aliceHealth, aliceDebtToShare] = await bank.positionInfo('2'); expect(aliceHealth).to.be.bignumber.gt(ether('3')); // Get Reward and increase health assertAlmostEqual(ether('2'), aliceDebtToShare); // ---------------- Reinvest#3 ------------------- // Wait for 1 day and someone calls reinvest await time.increase(time.duration.days(1)); [goblinLPBefore, goblinDebtBefore] = await masterChef.userInfo(poolId, goblin.address); await goblin.reinvest({ from: eve }); // Goblin receives 151999999999250105 uni as a reward // Eve got 10% of 151999999999250105 uni = 0.1 * 151999999999250105 = 15199999999925010 bounty // Now Eve have 22799999999887473 sushi (1st) + 15199999999937679 sushi (2nd) + 15199999999925010 sushi (3rd) = 53199999999750162 sushi assertAlmostEqual('53199999999750162', await sushi.balanceOf(eve)); // Remaining Goblin reward = 142858796296283038 - 14285879629628304 = 128572916666654734 (~90% reward) // Convert 128572916666654734 uni to 74159218067697746 ETH // Convert ETH to 2350053120029788 LP token [goblinLPAfter, goblinDebtAfter] = await masterChef.userInfo(poolId, goblin.address); // LP tokens of goblin should be inceased from reinvestment expect(goblinLPAfter).to.be.bignumber.gt(goblinLPBefore); const bobBefore = new BN(await web3.eth.getBalance(bob)); // Bob close position#1 await bank.work( 1, goblin.address, '0', '1000000000000000000000', web3.eth.abi.encodeParameters( ['address', 'bytes'], [liqStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { from: bob, gasPrice: 0 } ); const bobAfter = new BN(await web3.eth.getBalance(bob)); // Check Bob account expect(bobAfter).to.be.bignumber.gt(bobBefore); //Bob must be richer // Alice add ETH again await bank.work( 2, goblin.address, 0, '0', // max return = 0, don't return ETH to the debt web3.eth.abi.encodeParameters( ['address', 'bytes'], [addStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { value: web3.utils.toWei('10', 'ether'), from: alice } ); const aliceBefore = new BN(await web3.eth.getBalance(alice)); // Alice close position#2 await bank.work( 2, goblin.address, '0', '1000000000000000000000000000000', web3.eth.abi.encodeParameters( ['address', 'bytes'], [liqStrat.address, web3.eth.abi.encodeParameters(['address', 'uint256'], [token.address, '0'])] ), { from: alice, gasPrice: 0 } ); const aliceAfter = new BN(await web3.eth.getBalance(alice)); // Check Alice account expect(aliceAfter).to.be.bignumber.gt(aliceBefore); //Alice must be richer }); });
the_stack
module dragonBones { /** * @class dragonBones.Slot * @classdesc * Slot 实例是骨头上的一个插槽,是显示图片的容器。 * 一个 Bone 上可以有多个Slot,每个Slot中同一时间都会有一张图片用于显示,不同的Slot中的图片可以同时显示。 * 每个 Slot 中可以包含多张图片,同一个 Slot 中的不同图片不能同时显示,但是可以在动画进行的过程中切换,用于实现帧动画。 * @extends dragonBones.DBObject * @see dragonBones.Armature * @see dragonBones.Bone * @see dragonBones.SlotData * * @example <pre> //获取动画数据 本例使用Knight例子. //资源下载地址http://dragonbones.github.io/download_forwarding.html?download_url=downloads/dragonbonesdemos_v2.4.zip var skeletonData = RES.getRes("skeleton"); //获取纹理集数据 var textureData = RES.getRes("textureConfig"); //获取纹理集图片 var texture = RES.getRes("texture"); //这个资源需要自己准备 var horseHat = RES.getRes("horseHat"); //创建一个工厂,用来创建Armature var factory:dragonBones.EgretFactory = new dragonBones.EgretFactory(); //把动画数据添加到工厂里 factory.addSkeletonData(dragonBones.DataParser.parseDragonBonesData(skeletonData)); //把纹理集数据和图片添加到工厂里 factory.addTextureAtlas(new dragonBones.EgretTextureAtlas(texture, textureData)); //获取Armature的名字,dragonBones4.0的数据可以包含多个骨架,这里取第一个Armature var armatureName:string = skeletonData.armature[1].name; //从工厂里创建出Armature var armature:dragonBones.Armature = factory.buildArmature(armatureName); //获取装载Armature的容器 var armatureDisplay = armature.display; //把它添加到舞台上 armatureDisplay.x = 200; armatureDisplay.y = 300; this.addChild(armatureDisplay); //以下四句代码,实现给骨骼添加slot的功能 //1.获取马头的骨骼 var horseHead:dragonBones.Bone = armature.getBone("horseHead"); //2.创建一个slot var horseHatSlot:dragonBones.EgretSlot = new dragonBones.EgretSlot(); //3.给这个slot赋一个图片 horseHatSlot.display = new egret.Bitmap(horseHat); //4.把这个slot添加到骨骼上 horseHead.addSlot(horseHatSlot); //以下3句代码,实现了子骨骼的获取和播放子骨架的动画 //1.获取包含子骨架的骨骼 var weaponBone:dragonBones.Bone = armature.getBone("armOutside"); //2.获取骨骼上的子骨架 var childArmature:dragonBones.Armature = weaponBone.childArmature; //3.播放子骨架的动画 childArmature.animation.gotoAndPlay("attack_sword_1",0,-1,0); //取得这个Armature动画列表中的第一个动画的名字 var curAnimationName = armature.animation.animationList[0]; armature.animation.gotoAndPlay(curAnimationName,0.3,-1,0); //把Armature添加到心跳时钟里 dragonBones.WorldClock.clock.add(armature); //心跳时钟开启 egret.Ticker.getInstance().register(function (advancedTime) { dragonBones.WorldClock.clock.advanceTime(advancedTime / 1000); }, this); </pre> */ export class Slot extends DBObject{ /** @private Need to keep the reference of DisplayData. When slot switch displayObject, it need to restore the display obect's origional pivot. */ public _displayDataList:Array<DisplayData>; /** @private */ public _originZOrder:number; /** @private */ public _tweenZOrder:number; /** @private */ public _offsetZOrder:number; /** @private */ public _originDisplayIndex:number; public _displayList:Array<any>; public _currentDisplayIndex:number = 0; public _colorTransform:ColorTransform; //TO DO: 以后把这两个属性变成getter //另外还要处理 isShowDisplay 和 visible的矛盾 public _currentDisplay:any; public _isShowDisplay:boolean; //protected var _childArmature:Armature; public _blendMode:string; public _isColorChanged:boolean; public _needUpdate:boolean; public _timelineStateList:Array<SlotTimelineState> public constructor(self:Slot){ super(); if(self != this){ throw new Error(egret.getString(4001)); } this._displayList = []; this._timelineStateList = []; this._currentDisplayIndex = -1; this._originZOrder = 0; this._tweenZOrder = 0; this._offsetZOrder = 0; this._isShowDisplay = false; this._colorTransform = new ColorTransform(); this._displayDataList = null; //_childArmature = null; this._currentDisplay = null; this.inheritRotation = true; this.inheritScale = true; } /** * 通过传入 SlotData 初始化Slot * @param slotData */ public initWithSlotData(slotData:SlotData):void{ this.name = slotData.name; this.blendMode = slotData.blendMode; this._originZOrder = slotData.zOrder; this._displayDataList = slotData.displayDataList; this._originDisplayIndex = slotData.displayIndex; } /** * @inheritDoc */ public dispose():void{ if(!this._displayList){ return; } super.dispose(); this._displayList.length = 0; this._displayDataList = null; this._displayList = null; this._currentDisplay = null; //_childArmature = null; } private sortState(state1:SlotTimelineState, state2:SlotTimelineState):number{ return state1._animationState.layer < state2._animationState.layer?-1:1; } /** @private */ public _addState(timelineState:SlotTimelineState):void{ if(this._timelineStateList.indexOf(timelineState) < 0){ this._timelineStateList.push(timelineState); this._timelineStateList.sort(this.sortState); } } /** @private */ public _removeState(timelineState:SlotTimelineState):void{ var index:number = this._timelineStateList.indexOf(timelineState); if(index >= 0){ this._timelineStateList.splice(index, 1); } } //骨架装配 /** @private */ public setArmature(value:Armature):void{ if(this._armature == value){ return; } if(this._armature){ this._armature._removeSlotFromSlotList(this); } this._armature = value; if(this._armature){ this._armature._addSlotToSlotList(this); this._armature._slotsZOrderChanged = true; this._addDisplayToContainer(this._armature.display); } else{ this._removeDisplayFromContainer(); } } //动画 /** @private */ public _update():void{ if(this._parent._needUpdate <= 0 && !this._needUpdate){ return; } this._updateGlobal(); this._updateTransform(); this._needUpdate = false; } public _calculateRelativeParentTransform():void { this._global.scaleX = this._origin.scaleX * this._offset.scaleX; this._global.scaleY = this._origin.scaleY * this._offset.scaleY; this._global.skewX = this._origin.skewX + this._offset.skewX; this._global.skewY = this._origin.skewY + this._offset.skewY; this._global.x = this._origin.x + this._offset.x + this._parent._tweenPivot.x; this._global.y = this._origin.y + this._offset.y + this._parent._tweenPivot.y; } private updateChildArmatureAnimation():void{ if(this.childArmature){ if(this._isShowDisplay){ if( this._armature && this._armature.animation.lastAnimationState && this.childArmature.animation.hasAnimation(this._armature.animation.lastAnimationState.name) ){ this.childArmature.animation.gotoAndPlay(this._armature.animation.lastAnimationState.name); } else{ this.childArmature.animation.play(); } } else{ this.childArmature.animation.stop(); this.childArmature.animation._lastAnimationState = null; } } } /** @private */ public _changeDisplay(displayIndex:number = 0):void{ if (displayIndex < 0){ if(this._isShowDisplay){ this._isShowDisplay = false; this._removeDisplayFromContainer(); this.updateChildArmatureAnimation(); } } else if (this._displayList.length > 0){ var length:number = this._displayList.length; if(displayIndex >= length){ displayIndex = length - 1; } if(this._currentDisplayIndex != displayIndex){ this._isShowDisplay = true; this._currentDisplayIndex = displayIndex; this._updateSlotDisplay(); this.updateChildArmatureAnimation(); if( this._displayDataList && this._displayDataList.length > 0 && this._currentDisplayIndex < this._displayDataList.length ){ this._origin.copy(this._displayDataList[this._currentDisplayIndex].transform); } this._needUpdate = true; } else if(!this._isShowDisplay){ this._isShowDisplay = true; if(this._armature){ this._armature._slotsZOrderChanged = true; this._addDisplayToContainer(this._armature.display); } this.updateChildArmatureAnimation(); } } } /** @private * Updates the display of the slot. */ public _updateSlotDisplay():void{ var currentDisplayIndex:number = -1; if(this._currentDisplay){ currentDisplayIndex = this._getDisplayIndex(); this._removeDisplayFromContainer(); } var displayObj:any = this._displayList[this._currentDisplayIndex]; if (displayObj){ if(displayObj instanceof Armature){ //_childArmature = display as Armature; this._currentDisplay = (<Armature><any> displayObj).display; } else{ //_childArmature = null; this._currentDisplay = displayObj; } } else{ this._currentDisplay = null; //_childArmature = null; } this._updateDisplay(this._currentDisplay); if(this._currentDisplay){ if(this._armature && this._isShowDisplay){ if(currentDisplayIndex < 0){ this._armature._slotsZOrderChanged = true; this._addDisplayToContainer(this._armature.display); } else{ this._addDisplayToContainer(this._armature.display, currentDisplayIndex); } } this._updateDisplayBlendMode(this._blendMode); this._updateDisplayColor( this._colorTransform.alphaOffset, this._colorTransform.redOffset, this._colorTransform.greenOffset, this._colorTransform.blueOffset, this._colorTransform.alphaMultiplier, this._colorTransform.redMultiplier, this._colorTransform.greenMultiplier, this._colorTransform.blueMultiplier, true) this._updateDisplayVisible(this._visible); this._updateTransform(); } } /** @private */ public set visible(value:boolean){ if(this._visible != value){ this._visible = value; this._updateDisplayVisible(this._visible); } } /** * 显示对象列表(包含 display 或者 子骨架) * @member {any[]} dragonBones.Slot#displayList */ public get displayList():Array<any>{ return this._displayList; } public set displayList(value:Array<any>){ if(!value){ throw new Error(); } //为什么要修改_currentDisplayIndex? if (this._currentDisplayIndex < 0){ this._currentDisplayIndex = 0; } var i:number = this._displayList.length = value.length; while(i --){ this._displayList[i] = value[i]; } //在index不改变的情况下强制刷新 TO DO需要修改 var displayIndexBackup:number = this._currentDisplayIndex; this._currentDisplayIndex = -1; this._changeDisplay(displayIndexBackup); } /** * 当前的显示对象(可能是 display 或者 子骨架) * @member {any} dragonBones.Slot#display */ public get display():any{ return this._currentDisplay; } public set display(value:any){ if (this._currentDisplayIndex < 0){ this._currentDisplayIndex = 0; } if(this._displayList[this._currentDisplayIndex] == value){ return; } this._displayList[this._currentDisplayIndex] = value; this._updateSlotDisplay(); this.updateChildArmatureAnimation(); this._updateTransform();//是否可以延迟更新? } /** * 不推荐的 API. 使用 display 属性代替 */ public getDisplay():any { return this.display; } /** * Unrecommended API. Please use .display = instead. * @returns {any} */ public setDisplay(value:any):void { this.display = value; } /** * 当前的子骨架 * @member {Armature} dragonBones.Slot#childArmature */ public get childArmature():Armature{ if(this._displayList[this._currentDisplayIndex] instanceof Armature) { return <Armature><any> (this._displayList[this._currentDisplayIndex]); } return null; } public set childArmature(value:Armature){ //设计的不好,要修改 this.display = value; } /** * 显示顺序。(支持小数用于实现动态插入slot) * @member {number} dragonBones.Slot#zOrder */ public get zOrder():number{ return this._originZOrder + this._tweenZOrder + this._offsetZOrder; } public set zOrder(value:number){ if(this.zOrder != value){ this._offsetZOrder = value - this._originZOrder - this._tweenZOrder; if(this._armature){ this._armature._slotsZOrderChanged = true; } } } /** * 混合模式 * @member {string} dragonBones.Slot#blendMode */ public get blendMode():string{ return this._blendMode; } public set blendMode(value:string){ if(this._blendMode != value){ this._blendMode = value; this._updateDisplayBlendMode(this._blendMode); } } //Abstract method /** * @private */ public _updateDisplay(value:any):void{ throw new Error(""); } /** * @private */ public _getDisplayIndex():number{ throw new Error(egret.getString(4001)); } /** * @private * Adds the original display object to another display object. * @param container * @param index */ public _addDisplayToContainer(container:any, index:number = -1):void{ throw new Error(egret.getString(4001)); } /** * @private * remove the original display object from its parent. */ public _removeDisplayFromContainer():void{ throw new Error(egret.getString(4001)); } /** * @private * Updates the transform of the slot. */ public _updateTransform():void{ throw new Error(egret.getString(4001)); } /** * @private */ public _updateDisplayVisible(value:boolean):void{ /** * bone.visible && slot.visible && updateVisible * this._parent.visible && this._visible && value; */ throw new Error(egret.getString(4001)); } /** * @private * Updates the color of the display object. * @param a * @param r * @param g * @param b * @param aM * @param rM * @param gM * @param bM */ public _updateDisplayColor( aOffset:number, rOffset:number, gOffset:number, bOffset:number, aMultiplier:number, rMultiplier:number, gMultiplier:number, bMultiplier:number, colorChanged:boolean = false ):void{ this._colorTransform.alphaOffset = aOffset; this._colorTransform.redOffset = rOffset; this._colorTransform.greenOffset = gOffset; this._colorTransform.blueOffset = bOffset; this._colorTransform.alphaMultiplier = aMultiplier; this._colorTransform.redMultiplier = rMultiplier; this._colorTransform.greenMultiplier = gMultiplier; this._colorTransform.blueMultiplier = bMultiplier; this._isColorChanged = colorChanged; } /** * @private * Update the blend mode of the display object. * @param value The blend mode to use. */ public _updateDisplayBlendMode(value:string):void{ throw new Error("Abstract method needs to be implemented in subclass!"); } /** @private When bone timeline enter a key frame, call this func*/ public _arriveAtFrame(frame:Frame, timelineState:SlotTimelineState, animationState:AnimationState, isCross:boolean):void{ var displayControl:boolean = animationState.displayControl && animationState.containsBoneMask(this.parent.name); if(displayControl){ var slotFrame:SlotFrame = <SlotFrame><any> frame; var displayIndex:number = slotFrame.displayIndex; var childSlot:Slot; this._changeDisplay(displayIndex); this._updateDisplayVisible(slotFrame.visible); if(displayIndex >= 0) { if(!isNaN(slotFrame.zOrder) && slotFrame.zOrder != this._tweenZOrder) { this._tweenZOrder = slotFrame.zOrder; this._armature._slotsZOrderChanged = true; } } //[TODO]currently there is only gotoAndPlay belongs to frame action. In future, there will be more. //后续会扩展更多的action,目前只有gotoAndPlay的含义 if(frame.action) { if(this.childArmature){ this.childArmature.animation.gotoAndPlay(frame.action); } } } } public _updateGlobal():any { this._calculateRelativeParentTransform(); TransformUtil.transformToMatrix(this._global, this._globalTransformMatrix, true); var output:any = this._calculateParentTransform(); if (output) { this._globalTransformMatrix.concat(output.parentGlobalTransformMatrix); TransformUtil.matrixToTransform(this._globalTransformMatrix, this._global, this._global.scaleX * output.parentGlobalTransform.scaleX >= 0, this._global.scaleY * output.parentGlobalTransform.scaleY >= 0); } return output; } public _resetToOrigin():void { this._changeDisplay(this._originDisplayIndex); this._updateDisplayColor(0, 0, 0, 0, 1, 1, 1, 1, true); } } }
the_stack
import assert = require('assert'); import { Context } from 'egg'; import { app, mock } from 'egg-mock/bootstrap'; import dayjs from '../../../../app/common/dayjs'; import { TestUtil } from 'test/TestUtil'; describe('test/port/controller/DownloadController/showPackageDownloads.test.ts', () => { let ctx: Context; let publisher; beforeEach(async () => { publisher = await TestUtil.createUser(); ctx = await app.mockModuleContext(); }); afterEach(() => { app.destroyModuleContext(ctx); }); describe('[GET /downloads/range/:range/:fullname] showPackageDownloads()', () => { it('should get package download infos', async () => { let pkg = await TestUtil.getFullPackage({ name: '@cnpm/koa', version: '1.0.0' }); await app.httpRequest() .put(`/${pkg.name}`) .set('authorization', publisher.authorization) .set('user-agent', publisher.ua) .send(pkg) .expect(201); pkg = await TestUtil.getFullPackage({ name: '@cnpm/koa', version: '2.0.0' }); await app.httpRequest() .put(`/${pkg.name}`) .set('authorization', publisher.authorization) .set('user-agent', publisher.ua) .send(pkg) .expect(201); mock(app.config.cnpmcore, 'allowPublishNonScopePackage', true); const pkg2 = await TestUtil.getFullPackage({ name: 'foo', version: '1.0.0' }); await app.httpRequest() .put(`/${pkg2.name}`) .set('authorization', publisher.authorization) .set('user-agent', publisher.ua) .send(pkg2) .expect(201); const pkg3 = await TestUtil.getFullPackage({ name: '@malware-test-cloth-diner-bosks-zante/foo', version: '1.0.0', }); await app.httpRequest() .put(`/${pkg3.name}`) .set('authorization', publisher.authorization) .set('user-agent', publisher.ua) .send(pkg3) .expect(201); if (app.config.nfs.client) { await app.httpRequest() .get(`/${pkg.name}/-/koa-1.0.0.tgz`) .expect(302); await app.httpRequest() .get(`/${pkg.name}/-/koa-1.0.0.tgz`) .expect(302); await app.httpRequest() .get(`/${pkg.name}/-/koa-1.0.0.tgz`) .expect(302); await app.httpRequest() .get(`/${pkg.name}/-/koa-2.0.0.tgz`) .expect(302); await app.httpRequest() .get(`/${pkg2.name}/-/foo-1.0.0.tgz`) .expect(302); await app.httpRequest() .get(`/${pkg3.name}/-/foo-1.0.0.tgz`) .expect(302); } else { await app.httpRequest() .get(`/${pkg.name}/-/koa-1.0.0.tgz`) .expect('content-type', 'application/octet-stream') .expect(200); await app.httpRequest() .get(`/${pkg.name}/-/koa-1.0.0.tgz`) .expect('content-type', 'application/octet-stream') .expect(200); await app.httpRequest() .get(`/${pkg.name}/-/koa-1.0.0.tgz`) .expect('content-type', 'application/octet-stream') .expect(200); await app.httpRequest() .get(`/${pkg.name}/-/koa-2.0.0.tgz`) .expect('content-type', 'application/octet-stream') .expect(200); await app.httpRequest() .get(`/${pkg2.name}/-/foo-1.0.0.tgz`) .expect('content-type', 'application/octet-stream') .expect(200); await app.httpRequest() .get(`/${pkg3.name}/-/foo-1.0.0.tgz`) .expect('content-type', 'application/octet-stream') .expect(200); } await app.runSchedule('SavePackageVersionDownloadCounter'); const start = dayjs().subtract(100, 'days').format('YYYY-MM-DD'); const end = dayjs().add(100, 'days').format('YYYY-MM-DD'); let res = await app.httpRequest() .get(`/downloads/range/${start}:${end}/@cnpm/koa`) .expect(200) .expect('content-type', 'application/json; charset=utf-8'); let data = res.body; // console.log(data); assert(data.downloads.length > 0); assert.equal(data.downloads[0].downloads, 4); assert.equal(data.versions['1.0.0'][0].downloads, 3); res = await app.httpRequest() .get(`/downloads/range/${start}:${end}/foo`) .expect(200) .expect('content-type', 'application/json; charset=utf-8'); data = res.body; // console.log(data); assert(data.downloads.length > 0); assert(data.downloads[0].downloads === 1); assert(data.versions['1.0.0'][0].downloads === 1); // __total__ res = await app.httpRequest() .get(`/downloads/total/${start}:${end}`) .expect(200) .expect('content-type', 'application/json; charset=utf-8'); data = res.body; // console.log(data); assert(data.downloads.length > 0); assert.equal(data.downloads[0].downloads, 6); assert(!data.versions); // scope res = await app.httpRequest() .get(`/downloads/@cnpm/${start}:${end}`) .expect(200) .expect('content-type', 'application/json; charset=utf-8'); data = res.body; // console.log(data); assert(data.downloads.length > 0); assert.equal(data.downloads[0].downloads, 4); assert(!data.versions); res = await app.httpRequest() .get(`/downloads/@malware-test-cloth-diner-bosks-zante/${start}:${end}`) .expect(200) .expect('content-type', 'application/json; charset=utf-8'); data = res.body; // console.log(data); assert(data.downloads.length > 0); assert.equal(data.downloads[0].downloads, 1); assert(!data.versions); }); it('should get package download infos auto handle start and end position', async () => { const pkg = await TestUtil.getFullPackage({ name: '@cnpm/koa', version: '1.0.0' }); await app.httpRequest() .put(`/${pkg.name}`) .set('authorization', publisher.authorization) .set('user-agent', publisher.ua) .send(pkg) .expect(201); if (app.config.nfs.client) { await app.httpRequest() .get(`/${pkg.name}/-/koa-1.0.0.tgz`) .expect(302); } else { await app.httpRequest() .get(`/${pkg.name}/-/koa-1.0.0.tgz`) .expect('content-type', 'application/octet-stream') .expect(200); } await app.runSchedule('SavePackageVersionDownloadCounter'); const start = dayjs().format('YYYY-MM-DD'); const end = dayjs().add(100, 'days').format('YYYY-MM-DD'); const res = await app.httpRequest() .get(`/downloads/range/${end}:${start}/@cnpm/koa`) .expect(200) .expect('content-type', 'application/json; charset=utf-8'); const data = res.body; // console.log(data); assert(data.downloads.length > 0); assert(data.versions); }); it('should get package download infos with empty data', async () => { const pkg = await TestUtil.getFullPackage({ name: '@cnpm/koa', version: '1.0.0' }); await app.httpRequest() .put(`/${pkg.name}`) .set('authorization', publisher.authorization) .set('user-agent', publisher.ua) .send(pkg) .expect(201); await app.runSchedule('SavePackageVersionDownloadCounter'); const start = dayjs().format('YYYY-MM-DD'); const end = dayjs().format('YYYY-MM-DD'); const res = await app.httpRequest() .get(`/downloads/range/${start}:${end}/@cnpm/koa`) .expect(200) .expect('content-type', 'application/json; charset=utf-8'); const data = res.body; assert.equal(data.downloads.length, 0); }); it('should 404 when package not exists', async () => { const start = dayjs().format('YYYY-MM-DD'); const end = dayjs().format('YYYY-MM-DD'); const res = await app.httpRequest() .get(`/downloads/range/${start}:${end}/@cnpm/koa-not-exists`) .expect(404) .expect('content-type', 'application/json; charset=utf-8'); const data = res.body; assert.equal(data.error, '[NOT_FOUND] @cnpm/koa-not-exists not found'); }); it('should 422 when out of range', async () => { const start = dayjs().format('YYYY-MM-DD'); const end = dayjs().add(1, 'year').add(1, 'day') .format('YYYY-MM-DD'); const res = await app.httpRequest() .get(`/downloads/range/${start}:${end}/@cnpm/koa`) .expect(422) .expect('content-type', 'application/json; charset=utf-8'); const data = res.body; assert.match(data.error, /beyond the processable range/); }); it('should 422 when out of range, switch start and end range', async () => { const start = dayjs().format('YYYY-MM-DD'); const end = dayjs().add(1, 'year').add(10, 'day') .format('YYYY-MM-DD'); const res = await app.httpRequest() .get(`/downloads/range/${end}:${start}/@cnpm/koa`) .expect(422) .expect('content-type', 'application/json; charset=utf-8'); const data = res.body; assert.match(data.error, /beyond the processable range/); }); it('should 422 when range format invalid', async () => { let res = await app.httpRequest() .get('/downloads/range/f:b/@cnpm/koa') .expect('content-type', 'application/json; charset=utf-8'); let data = res.body; assert.equal(res.status, 422); assert.equal(data.error, '[UNPROCESSABLE_ENTITY] range(f:b) format invalid, must be "YYYY-MM-DD:YYYY-MM-DD" style'); res = await app.httpRequest() .get('/downloads/range/2017-10-1:2017-09-10/@cnpm/koa') .expect('content-type', 'application/json; charset=utf-8'); data = res.body; assert.equal(res.status, 422); assert.equal(data.error, '[UNPROCESSABLE_ENTITY] range(2017-10-1:2017-09-10) format invalid, must be "YYYY-MM-DD:YYYY-MM-DD" style'); res = await app.httpRequest() .get('/downloads/range/2017-10-91:2017-09-10/@cnpm/koa') .expect('content-type', 'application/json; charset=utf-8'); data = res.body; assert.equal(res.status, 422); assert.equal(data.error, '[UNPROCESSABLE_ENTITY] range(2017-10-91:2017-09-10) format invalid, must be "YYYY-MM-DD:YYYY-MM-DD" style'); res = await app.httpRequest() .get('/downloads/range/2017-10-91:2017-00-10/@cnpm/koa') .expect('content-type', 'application/json; charset=utf-8'); data = res.body; assert.equal(res.status, 422); assert.equal(data.error, '[UNPROCESSABLE_ENTITY] range(2017-10-91:2017-00-10) format invalid, must be "YYYY-MM-DD:YYYY-MM-DD" style'); res = await app.httpRequest() .get('/downloads/range/2017-10-11:2017-09-99/@cnpm/koa') .expect('content-type', 'application/json; charset=utf-8'); data = res.body; assert.equal(res.status, 422); assert.equal(data.error, '[UNPROCESSABLE_ENTITY] range(2017-10-11:2017-09-99) format invalid, must be "YYYY-MM-DD:YYYY-MM-DD" style'); }); }); });
the_stack
import { Equatable } from "@siteimprove/alfa-equatable"; import { Hash } from "@siteimprove/alfa-hash"; import { Serializable } from "@siteimprove/alfa-json"; import { Mapper } from "@siteimprove/alfa-mapper"; import { Parser } from "@siteimprove/alfa-parser"; import { Slice } from "@siteimprove/alfa-slice"; import { Record } from "@siteimprove/alfa-record"; import * as json from "@siteimprove/alfa-json"; import { Token } from "../syntax/token"; import { Function } from "../syntax/function"; import { Value } from "../value"; import { Angle } from "./angle"; import { Dimension } from "./dimension"; import { Length } from "./length"; import { Number } from "./number"; import { Numeric } from "./numeric"; import { Percentage } from "./percentage"; import { Unit } from "./unit"; import { Option, None } from "@siteimprove/alfa-option"; import { Result, Err } from "@siteimprove/alfa-result"; const { map, flatMap, either, delimited, pair, option } = Parser; const { isAngle } = Angle; const { isDimension } = Dimension; const { isLength } = Length; const { isNumber } = Number; const { isPercentage } = Percentage; /** * {@link https://drafts.csswg.org/css-values/#math} * * @public */ export class Calculation extends Value<"calculation"> { public static of(expression: Calculation.Expression): Calculation { return new Calculation(expression.reduce((value) => value)); } private readonly _expression: Calculation.Expression; private constructor(expression: Calculation.Expression) { super(); this._expression = expression; } public get type(): "calculation" { return "calculation"; } public get expression(): Calculation.Expression { return this._expression; } public reduce(resolve: Mapper<Numeric>): Calculation { return new Calculation(this._expression.reduce(resolve)); } public hash(hash: Hash): void {} public equals(value: unknown): value is this { return ( value instanceof Calculation && value._expression.equals(this._expression) ); } public toJSON(): Calculation.JSON { return { type: "calculation", expression: this._expression.toJSON(), }; } public toString(): string { return `calc(${this._expression})`; } } /** * @public */ export namespace Calculation { export interface JSON { [key: string]: json.JSON; type: "calculation"; expression: Expression.JSON; } /** * {@link https://drafts.css-houdini.org/css-typed-om/#numeric-typing} * * @remarks * The shared `Value` interface already uses the term "type" to denote the * different types of CSS values. We therefore use the term "kind" to denote * the type of a calculation. */ export class Kind implements Equatable, Serializable { public static of(kind?: Kind.Base): Kind { const kinds = this._empty._kinds; return new Kind(kind === undefined ? kinds : kinds.set(kind, 1), None); } private static _empty = new Kind( Record.of({ length: 0, angle: 0, time: 0, frequency: 0, resolution: 0, percentage: 0, }), None ); public static empty(): Kind { return this._empty; } private readonly _kinds: Kind.Map; private readonly _hint: Option<Kind.Hint>; private constructor(kinds: Kind.Map, hint: Option<Kind.Hint>) { this._kinds = kinds; this._hint = hint; } public get kinds(): Kind.Map { return this._kinds; } public get hint(): Option<Kind.Hint> { return this._hint; } /** * {@link https://drafts.css-houdini.org/css-typed-om/#cssnumericvalue-match} */ public is( kind?: Kind.Base, value: number = 1, hinted: boolean = kind === "percentage" ): boolean { for (const entry of this._kinds) { if (entry[1] === 0) { continue; } if (kind !== undefined) { if (entry[0] === kind && entry[1] === value) { break; } } return false; } return this._hint.isNone() || hinted; } /** * {@link https://drafts.css-houdini.org/css-typed-om/#cssnumericvalue-add-two-types} */ public add(kind: Kind): Result<Kind, string> { let a: Kind = this; let b: Kind = kind; if (a._hint.some((a) => b._hint.some((b) => a !== b))) { return Err.of(`Cannot add types ${a} and ${b}`); } if (a._hint.isNone()) { for (const hint of b._hint) { a = a.apply(hint); } } if (b._hint.isNone()) { for (const hint of a._hint) { b = b.apply(hint); } } if (a._kinds.equals(b._kinds)) { return Result.of(a); } if ( [a._kinds, b._kinds].some( (kinds) => kinds.get("percentage").get() !== 0 ) && [a._kinds, b._kinds].some((kinds) => kinds.some((value, kind) => kind !== "percentage" && value !== 0) ) ) { for (const hint of [ "length", "angle", "time", "frequency", "resolution", ] as const) { const kind = a.apply(hint); if (kind._kinds.equals(b.apply(hint)._kinds)) { return Result.of(kind); } } } return Err.of(`Cannot add types ${a} and ${b}`); } /** * {@link https://drafts.css-houdini.org/css-typed-om/#cssnumericvalue-multiply-two-types} */ public multiply(kind: Kind): Result<Kind, string> { let a: Kind = this; let b: Kind = kind; if (a._hint.some((a) => b._hint.some((b) => a !== b))) { return Err.of(`Cannot multiply types ${a} and ${b}`); } if (a._hint.isNone()) { for (const hint of b._hint) { a = a.apply(hint); } } if (b._hint.isNone()) { for (const hint of a._hint) { b = b.apply(hint); } } return Result.of( new Kind( b._kinds.reduce( (kinds, value, kind) => kinds.set(kind, kinds.get(kind).get() + value), a._kinds ), a._hint ) ); } /** * {@link https://drafts.css-houdini.org/css-typed-om/#cssnumericvalue-invert-a-type} */ public invert(): Kind { return new Kind( this._kinds.reduce( (kinds, value, kind) => kinds.set(kind, -1 * value), this._kinds ), None ); } /** * {@link https://drafts.css-houdini.org/css-typed-om/#apply-the-percent-hint} */ public apply(hint: Kind.Hint): Kind { return new Kind( this._kinds .set( hint, this._kinds.get(hint).get() + this._kinds.get("percentage").get() ) .set("percentage", 0), Option.of(hint) ); } public equals(value: this): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof Kind && value._kinds.equals(this._kinds) && value._hint.equals(this._hint) ); } public toJSON(): Kind.JSON { return { kinds: this._kinds.toArray(), hint: this._hint.getOr(null), }; } } export namespace Kind { export interface JSON { [key: string]: json.JSON; kinds: Array<[Base, number]>; hint: Hint | null; } /** * {@link https://drafts.css-houdini.org/css-typed-om/#cssnumericvalue-type} */ export type Map = Record< { [K in Base]: number; } >; /** * {@link https://drafts.css-houdini.org/css-typed-om/#cssnumericvalue-base-type} */ export type Base = | "length" | "angle" | "time" | "frequency" | "resolution" | "percentage"; /** * {@link https://drafts.css-houdini.org/css-typed-om/#cssnumericvalue-percent-hint} */ export type Hint = Exclude<Kind.Base, "percentage">; } /** * {@link https://drafts.csswg.org/css-values/#calculation-tree} */ export abstract class Expression implements Equatable, Serializable { public abstract get type(): string; public abstract get kind(): Kind; /** * {@link https://drafts.csswg.org/css-values/#simplify-a-calculation-tree} */ public abstract reduce(resolve: Mapper<Numeric>): Expression; public toLength(): Option<Length> { if (isValueExpression(this) && isLength(this.value)) { return Option.of(this.value); } return None; } public toPercentage(): Option<Percentage> { if (isValueExpression(this) && isPercentage(this.value)) { return Option.of(this.value); } return None; } public abstract equals(value: unknown): value is this; public toJSON(): Expression.JSON { return { type: this.type, }; } /** * {@link https://drafts.csswg.org/css-values/#serialize-a-calculation-tree} */ public abstract toString(): string; } export namespace Expression { export interface JSON { [key: string]: json.JSON; type: string; } } export class Value extends Expression { public static of(value: Numeric): Value { return new Value(value); } private readonly _value: Numeric; private constructor(value: Numeric) { super(); this._value = value; } public get type(): "value" { return "value"; } public get kind(): Kind { const value = this._value; if (isPercentage(value)) { return Kind.of("percentage"); } if (isLength(value)) { return Kind.of("length"); } if (isAngle(value)) { return Kind.of("angle"); } return Kind.of(); } public get value(): Numeric { return this._value; } public reduce(resolve: Mapper<Numeric>): Expression { const value = this._value; if (isLength(value) && value.isAbsolute()) { return Value.of(value.withUnit("px")); } if (isAngle(value)) { return Value.of(value.withUnit("deg")); } return Value.of(resolve(value)); } public equals(value: unknown): value is this { return value instanceof Value && value._value.equals(this._value); } public toJSON(): Value.JSON { return { type: "value", value: this._value.toJSON(), }; } public toString(): string { return `${this._value}`; } } export namespace Value { export interface JSON extends Expression.JSON { type: "value"; value: Numeric.JSON; } } export function isValueExpression( expression: Expression ): expression is Value { return expression.type === "value"; } /** * {@link https://drafts.csswg.org/css-values/#calculation-tree-operator-nodes} */ export abstract class Operation< O extends Array<Expression> = Array<Expression> > extends Expression { protected readonly _operands: Readonly<O>; protected readonly _kind: Kind; protected constructor(operands: Readonly<O>, kind: Kind) { super(); this._operands = operands; this._kind = kind; } public get operands(): Readonly<O> { return this._operands; } public get kind(): Kind { return this._kind; } public equals(value: this): value is this { return ( value instanceof Operation && value.type === this.type && value._operands.length === this._operands.length && value._operands.every((operand, i) => operand.equals(this._operands[i])) ); } public toJSON(): Operation.JSON { return { ...super.toJSON(), operands: this._operands.map((operand) => operand.toJSON()), }; } } export namespace Operation { export interface JSON extends Expression.JSON { operands: Array<Expression.JSON>; } export abstract class Unary extends Operation<[Expression]> { protected constructor(operands: [Expression], kind: Kind) { super(operands, kind); } } export abstract class Binary extends Operation<[Expression, Expression]> { protected constructor(operands: [Expression, Expression], kind: Kind) { super(operands, kind); } } } export class Sum extends Operation.Binary { public static of( ...operands: [Expression, Expression] ): Result<Sum, string> { const [fst, snd] = operands; const kind = fst.kind.add(snd.kind); return kind.map((kind) => new Sum(operands, kind)); } public get type(): "sum" { return "sum"; } public reduce(resolve: Mapper<Numeric>): Expression { const [fst, snd] = this._operands.map((operand) => operand.reduce(resolve) ); if (isValueExpression(fst) && isValueExpression(snd)) { if (isNumber(fst.value) && isNumber(snd.value)) { return Value.of(Number.of(fst.value.value + snd.value.value)); } if (isPercentage(fst.value) && isPercentage(snd.value)) { return Value.of(Percentage.of(fst.value.value + snd.value.value)); } if ( isDimension(fst.value) && isDimension(snd.value) && fst.value.unit === snd.value.unit ) { const { unit } = fst.value; if (Unit.isLength(unit)) { return Value.of(Length.of(fst.value.value + snd.value.value, unit)); } if (Unit.isAngle(unit)) { return Value.of(Angle.of(fst.value.value + snd.value.value, unit)); } } } return new Sum([fst, snd], this._kind); } public toString(): string { const [fst, snd] = this._operands; if (isNegateExpression(snd)) { return `(${fst} - ${snd.operands[0]})`; } return `(${fst} + ${snd})`; } } export function isSumExpression(expression: Expression): expression is Sum { return expression.type === "sum"; } export class Negate extends Operation.Unary { public static of(operand: Expression): Negate { return new Negate([operand], operand.kind); } public get type(): "negate" { return "negate"; } public reduce(resolve: Mapper<Numeric>): Expression { const [operand] = this._operands.map((operand) => operand.reduce(resolve) ); if (isValueExpression(operand)) { const { value } = operand; if (isNumber(value)) { return Value.of(Number.of(0 - value.value)); } if (isPercentage(value)) { return Value.of(Percentage.of(0 - value.value)); } if (isLength(value)) { return Value.of(Length.of(0 - value.value, value.unit)); } if (isAngle(value)) { return Value.of(Angle.of(0 - value.value, value.unit)); } } if (isNegateExpression(operand)) { return operand._operands[0]; } return Negate.of(operand); } public toString(): string { const [operand] = this._operands; return `(-1 * ${operand})`; } } export function isNegateExpression( expression: Expression ): expression is Negate { return expression.type === "negate"; } export class Product extends Operation.Binary { public static of( ...operands: [Expression, Expression] ): Result<Product, string> { const [fst, snd] = operands; const kind = fst.kind.multiply(snd.kind); return kind.map((kind) => new Product(operands, kind)); } public get type(): "product" { return "product"; } public reduce(resolve: Mapper<Numeric>): Expression { const [fst, snd] = this._operands.map((operand) => operand.reduce(resolve) ); if (isValueExpression(fst) && isValueExpression(snd)) { let multipler: number | undefined; let value!: Numeric; if (isNumber(fst.value)) { multipler = fst.value.value; value = snd.value; } else if (isNumber(snd.value)) { multipler = snd.value.value; value = fst.value; } if (multipler !== undefined) { if (isNumber(value)) { return Value.of(Number.of(multipler * value.value)); } if (isPercentage(value)) { return Value.of(Percentage.of(multipler * value.value)); } if (isLength(value)) { return Value.of(Length.of(multipler * value.value, value.unit)); } if (isAngle(value)) { return Value.of(Angle.of(multipler * value.value, value.unit)); } } } return new Product([fst, snd], this._kind); } public toString(): string { const [fst, snd] = this._operands; return `${fst} * ${snd}`; } } export function isProductExpression( expression: Expression ): expression is Product { return expression.type === "product"; } export class Invert extends Operation.Unary { public static of(operand: Expression): Invert { return new Invert([operand], operand.kind.invert()); } public get type(): "invert" { return "invert"; } public get kind(): Kind { return this._operands[0].kind.invert(); } public reduce(resolve: Mapper<Numeric>): Expression { const [operand] = this._operands.map((operand) => operand.reduce(resolve) ); if (isValueExpression(operand)) { const { value } = operand; if (isNumber(value)) { return Value.of(Number.of(1 / value.value)); } } if (isInvertExpression(operand)) { return operand._operands[0]; } return Negate.of(operand); } public toString(): string { const [operand] = this._operands; return `(1 / ${operand})`; } } export function isInvertExpression( expression: Expression ): expression is Invert { return expression.type === "invert"; } let parseSum: Parser<Slice<Token>, Expression, string>; const parseCalc = map( Function.parse("calc", (input) => parseSum(input)), ([, expression]) => expression ); /** * {@link https://drafts.csswg.org/css-values/#typedef-calc-value} */ const parseValue = either<Slice<Token>, Expression, string>( map( either<Slice<Token>, Numeric, string>( Number.parse, Percentage.parse, Length.parse, Angle.parse ), Value.of ), parseCalc, delimited( Token.parseOpenParenthesis, (input) => parseSum(input), Token.parseCloseParenthesis ) ); /** * {@link https://drafts.csswg.org/css-values/#typedef-calc-product} */ const parseProduct = flatMap( pair( parseValue, option( pair( delimited( option(Token.parseWhitespace), either( map(Token.parseDelim("*"), () => false), map(Token.parseDelim("/"), () => true) ) ), parseValue ) ) ), ([left, result]) => { const right = result.map(([invert, right]) => invert ? Invert.of(right) : right ); if (right.isNone()) { return (input) => Result.of([input, left]); } return (input) => Product.of(left, right.get()).map((expression) => [input, expression]); } ); /** * {@link https://drafts.csswg.org/css-values/#typedef-calc-sum} */ parseSum = flatMap( pair( parseProduct, option( pair( delimited( Token.parseWhitespace, either( map(Token.parseDelim("+"), () => false), map(Token.parseDelim("-"), () => true) ) ), parseProduct ) ) ), ([left, result]) => { const right = result.map(([negate, right]) => negate ? Negate.of(right) : right ); if (right.isNone()) { return (input) => Result.of([input, left]); } return (input) => Sum.of(left, right.get()).map((expression) => [input, expression]); } ); export const parse = map(parseCalc, Calculation.of); }
the_stack
import { IDocumentStore } from "../../../src"; import { disposeTestDocumentStore, testContext } from "../../Utils/TestUtil"; import { Company, User } from "../../Assets/Entities"; import { assertThat } from "../../Utils/AssertExtensions"; describe("RavenDB_15080", function () { let store: IDocumentStore; beforeEach(async function () { store = await testContext.getDocumentStore(); }); afterEach(async () => await disposeTestDocumentStore(store)); it("canSplitLowerCasedAndUpperCasedCounterNames", async () => { { const session = store.openSession(); const user = new User(); user.name = "Aviv1"; await session.store(user, "users/1"); const countersFor = session.countersFor("users/1"); for (let i = 0; i < 500; i++) { const str = "abc" + i; countersFor.increment(str); } await session.saveChanges(); } { const session = store.openSession(); const counterFor = session.countersFor("users/1"); for (let i = 0; i < 500; i++) { const str = "Xyz" + i; counterFor.increment(str); } await session.saveChanges(); } }); it("counterOperationsShouldBeCaseInsensitiveToCounterName", async () => { { const session = store.openSession(); const user = new User(); user.name = "Aviv"; await session.store(user, "users/1"); session.countersFor("users/1").increment("abc"); await session.saveChanges(); } { const session = store.openSession(); // should NOT create a new counter session.countersFor("users/1").increment("ABc"); await session.saveChanges(); } { const session = store.openSession(); assertThat(await session.countersFor("users/1").getAll()) .hasSize(1); } { const session = store.openSession(); // get should be case-insensitive to counter name const val = await session.countersFor("users/1").get("AbC"); assertThat(val) .isEqualTo(2); const doc = await session.load<User>("users/1", User); const countersNames = session.advanced.getCountersFor(doc); assertThat(countersNames) .hasSize(1); assertThat(countersNames[0]) .isEqualTo("abc"); // metadata counter-names should preserve their original casing } { const session = store.openSession(); session.countersFor("users/1").increment("XyZ"); await session.saveChanges(); } { const session = store.openSession(); const val = await session.countersFor("users/1") .get("xyz"); assertThat(val) .isEqualTo(1); const doc = await session.load<User>("users/1", User); const counterNames = session.advanced.getCountersFor(doc); assertThat(counterNames) .hasSize(2); // metadata counter-names should preserve their original casing assertThat(counterNames[0]) .isEqualTo("abc"); assertThat(counterNames[1]) .isEqualTo("XyZ"); } { const session = store.openSession(); // delete should be case-insensitive to counter name session.countersFor("users/1").delete("aBC"); await session.saveChanges(); } { const session = store.openSession(); const val = await session.countersFor("users/1").get("abc"); assertThat(val) .isNull(); const doc = await session.load<User>("users/1", User); const counterNames = session.advanced.getCountersFor(doc); assertThat(counterNames) .hasSize(1); assertThat(counterNames[0]) .isEqualTo("XyZ"); } { const session = store.openSession(); session.countersFor("users/1").delete("xyZ"); await session.saveChanges(); } { const session = store.openSession(); const val = await session.countersFor("users/1").get("Xyz"); assertThat(val) .isNull(); const doc = await session.load<User>("users/1", User); const counterNames = session.advanced.getCountersFor(doc); assertThat(counterNames) .isNull(); } }); it("countersShouldBeCaseInsensitive", async () => { // RavenDB-14753 { const session = store.openSession(); const company = new Company(); company.name = "HR"; await session.store(company, "companies/1"); session.countersFor(company).increment("Likes", 999); await session.saveChanges(); } { const session = store.openSession(); const company = await session.load<Company>("companies/1", Company); session.countersFor(company) .delete("lIkEs"); await session.saveChanges(); } { const session = store.openSession(); const company = await session.load<Company>("companies/1", Company); const counters = await session.countersFor(company).getAll(); assertThat(counters) .hasSize(0); } }); it("deletedCounterShouldNotBePresentInMetadataCounters", async () => { // RavenDB-14753 { const session = store.openSession(); const company = new Company(); company.name = "HR"; await session.store(company, "companies/1"); session.countersFor(company).increment("Likes", 999); session.countersFor(company).increment("Cats", 999); await session.saveChanges(); } { const session = store.openSession(); const company = await session.load<Company>("companies/1", Company); session.countersFor(company) .delete("lIkEs"); await session.saveChanges(); } { const session = store.openSession(); const company = await session.load<Company>("companies/1", Company); company.name = "RavenDB"; await session.saveChanges(); } { const session = store.openSession(); const company = await session.load<Company>("companies/1", Company); const counters = session.advanced.getCountersFor(company); assertThat(counters) .hasSize(1); assertThat(counters[0]) .isEqualTo("Cats"); } }); it("getCountersForDocumentShouldReturnNamesInTheirOriginalCasing", async () => { { const session = store.openSession(); await session.store(new User(), "users/1"); const countersFor = session.countersFor("users/1"); countersFor.increment("AviV"); countersFor.increment("Karmel"); countersFor.increment("PAWEL"); await session.saveChanges(); } { const session = store.openSession(); // GetAll should return counter names in their original casing const all = await session.countersFor("users/1").getAll(); assertThat(all) .hasSize(3); const keys = Object.keys(all); assertThat(keys) .contains("AviV") .contains("Karmel") .contains("PAWEL"); } }); it("canDeleteAndReInsertCounter", async () => { { const session = store.openSession(); const company = new Company(); company.name = "HR"; await session.store(company, "companies/1"); session.countersFor(company).increment("Likes", 999); session.countersFor(company).increment("Cats", 999); await session.saveChanges(); } { const session = store.openSession(); const company = await session.load<Company>("companies/1", Company); session.countersFor(company) .delete("Likes"); await session.saveChanges(); } { const session = store.openSession(); const company = await session.load<Company>("companies/1", Company); const counters = session.advanced.getCountersFor(company); assertThat(counters) .hasSize(1) .contains("Cats"); const counter = await session.countersFor(company) .get("Likes"); assertThat(counter) .isNull(); const all = await session.countersFor(company) .getAll(); assertThat(all) .hasSize(1); } { const session = store.openSession(); session.countersFor("companies/1").increment("Likes"); await session.saveChanges(); } { const session = store.openSession(); const company = await session.load<Company>("companies/1", Company); const counters = session.advanced.getCountersFor(company); assertThat(counters) .hasSize(2) .contains("Cats") .contains("Likes"); const counter = await session.countersFor(company) .get("Likes"); assertThat(counter) .isNotNull(); assertThat(counter) .isEqualTo(1); } }); it("countersSessionCacheShouldBeCaseInsensitiveToCounterName", async () => { { const session = store.openSession(); const company = new Company(); company.name = "HR"; await session.store(company, "companies/1"); session.countersFor(company) .increment("Likes", 333); session.countersFor(company) .increment("Cats", 999); await session.saveChanges(); } { const session = store.openSession(); const company = await session.load<Company>("companies/1", Company); // the document is now tracked by the session, // so now counters-cache has access to '@counters' from metadata // searching for the counter's name in '@counters' should be done in a case insensitive manner // counter name should be found in '@counters' => go to server let counter = await session.countersFor(company) .get("liKes"); assertThat(session.advanced.numberOfRequests) .isEqualTo(2); assertThat(counter) .isNotNull(); assertThat(counter) .isEqualTo(333); counter = await session.countersFor(company).get("cats"); assertThat(session.advanced.numberOfRequests) .isEqualTo(3); assertThat(counter) .isNotNull(); assertThat(counter) .isEqualTo(999); counter = await session.countersFor(company).get("caTS"); assertThat(session.advanced.numberOfRequests) .isEqualTo(3); assertThat(counter) .isNotNull(); assertThat(counter) .isEqualTo(999); } }) });
the_stack
import * as Debug from 'debug'; import * as Models from '../models'; import { buildDeviceCapabilities } from './deviceCapability'; import * as validation from './validation'; const debug = Debug('neeo:device:DeviceBuilder'); const MAXIMAL_STRING_LENGTH = validation.MAXIMAL_STRING_LENGTH; const DEFAULT_MANUFACTURER = 'NEEO'; const DEFAULT_TYPE: Models.DeviceType = 'ACCESSOIRE'; const API_VERSION = '1.0'; const PLAYER_BUTTON_NAMES = Models.PlayerWidget.playerButtonNames; const PLAYER_VOLUME = Models.PlayerWidget.playerVolumeDefinition; const PLAYER_COVER_ART = Models.PlayerWidget.coverArtDefinition; const PLAYER_TITLE = Models.PlayerWidget.titleDefinition; const PLAYER_DESCRIPTION = Models.PlayerWidget.descriptionDefinition; const PLAYER_PLAYING = Models.PlayerWidget.playingDefinition; const PLAYER_MUTE = Models.PlayerWidget.muteDefinition; const PLAYER_SHUFFLE = Models.PlayerWidget.shuffleDefinition; const PLAYER_REPEAT = Models.PlayerWidget.repeatDefinition; export class DeviceBuilder implements Models.DeviceBuilder { public readonly buttons: Array<{ param: Models.ButtonDescriptor }>; public readonly deviceidentifier: string; public readonly sensors: Array<{ param: Models.Sensor.Descriptor; controller: Models.Sensor.Controller; }>; public readonly discovery: Array<{ controller: Models.Discovery.Controller; }>; public readonly sliders: Array<{ param: Models.Slider.Descriptor; controller: Models.Slider.Controller; }>; public readonly switches: Array<{ param: Models.Descriptor; controller: Models.Switch.Controller; }>; public readonly textLabels: Array<{ param: Models.TextLabel.Descriptor; controller: { getter: Models.TextLabel.Controller }; }>; public readonly imageUrls: Array<{ param: Models.Image.Descriptor; controller: { getter: Models.Image.Controller }; }>; public readonly directories: Array<{ param: Models.Directory.Descriptor; controller: Models.Directory.Controller; }>; public readonly registration: any[]; public readonly additionalSearchTokens: string[]; public readonly deviceCapabilities: Models.DeviceCapability[]; public readonly devicename: string; public buttonHandler?: Models.ButtonHandler; public hasPowerStateSensor: boolean; public manufacturer: string = DEFAULT_MANUFACTURER; public type = DEFAULT_TYPE; public setup: Models.DeviceSetup; public deviceSubscriptionHandlers?: Models.DeviceSubscriptionHandler.Controller; public favoritesHandler?: Models.FavoritesHandler.Controller; public driverVersion?: number; private icon?: string; private initializeFunction?: Models.InitialiseFunction; private subscriptionFunction?: Models.Subscription.Controller; private specificname?: string; private timing?: Models.DeviceTiming; private validatePlayerWidget?: boolean; constructor(name: string, uniqueString?: string) { if (!validation.stringLength(name, MAXIMAL_STRING_LENGTH)) { throw new Error('DEVICENNAME_TOO_LONG'); } this.deviceidentifier = `apt-${validation.getUniqueName(name, uniqueString)}`; this.devicename = name; this.directories = []; this.setup = {}; this.hasPowerStateSensor = false; this.sensors = []; this.deviceCapabilities = []; this.buttons = []; this.additionalSearchTokens = []; this.discovery = []; this.sliders = []; this.switches = []; this.textLabels = []; this.imageUrls = []; this.directories = []; this.registration = []; } public setManufacturer(manufacturer = DEFAULT_MANUFACTURER) { if (!validation.stringLength(manufacturer, MAXIMAL_STRING_LENGTH)) { throw new Error('MANUFACTURER_NAME_TOO_LONG'); } this.manufacturer = manufacturer; return this; } public setDriverVersion(version: number) { if (!validation.validateDriverVersion(version)) { throw new Error('DRIVER_VERSION_NOT_INTEGER_GREATER_THAN_0'); } this.driverVersion = version; return this; } public setType(type: string = DEFAULT_TYPE) { this.type = validation.getDeviceType(type); return this; } public setIcon(iconName) { this.icon = validation.getIcon(iconName); return this; } public setSpecificName(specificname?: string) { if (specificname && !validation.stringLength(specificname, MAXIMAL_STRING_LENGTH)) { throw new Error('SPECIFIC_NAME_TOO_LONG'); } this.specificname = specificname; return this; } public addAdditionalSearchToken(token: string) { this.additionalSearchTokens.push(token); return this; } public build(): Models.DeviceAdapterModel { const { buttons, buttonHandler, devicename, type, deviceidentifier, favoritesHandler, manufacturer, setup, additionalSearchTokens, deviceCapabilities, specificname, icon, timing, subscriptionFunction, initializeFunction: initialiseFunction, } = this; if (timing && validation.deviceTypeDoesNotSupportTiming(type)) { throw new Error('TIMING_DEFINED_BUT_DEVICETYPE_HAS_NO_SUPPORT'); } if (favoritesHandler && !validation.deviceTypeHasFavoritesSupport(type)) { throw new Error('FAVORITES_HANDLER_DEFINED_BUT_DEVICETYPE_HAS_NO_SUPPORT'); } if (this.validatePlayerWidget && !validation.deviceTypeHasPlayerSupport(type)) { throw new Error('INVALID_DEVICE_TYPE_FOR_PLAYER_WIDGET_' + type); } if (buttons.length && !buttonHandler) { throw new Error('BUTTONS_DEFINED_BUT_NO_BUTTONHANDLER_DEFINED'); } if (setup.registration && !setup.discovery) { throw new Error('REGISTRATION_ENABLED_MISSING_DISCOVERY_STEP'); } const { capabilities, handlers: handler } = buildDeviceCapabilities(this); const dynamicDeviceBuilderEnabled = this.setup.enableDynamicDeviceBuilder === true; if (!dynamicDeviceBuilderEnabled && capabilities.length === 0) { // empty capabilities are allowed only for dynamicDeviceBuilder throw new Error('INVALID_DEVICE_DESCRIPTION_NO_CAPABILITIES'); } if (dynamicDeviceBuilderEnabled && capabilities.length > 0) { // in fact, empty capabilities are required when dynamicDeviceBuilder is enabled throw new Error('DYNAMICDEVICEBUILDER_ENABLED_DEVICES_MUST_NOT_HAVE_CAPABILITIES_DEFINED'); } if (setup.registration) { deviceCapabilities.push('register-user-account'); } if (favoritesHandler) { deviceCapabilities.push('customFavoriteHandler'); } if ( validation.deviceTypeNeedsInputCommand(type) && validation.hasNoInputButtonsDefined(buttons) ) { // tslint:disable-next-line console.warn( '\nWARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!\n' + 'WARNING: no input commands defined! Your device might not work as\n' + 'desired, check the docs.\n' + 'Devicename:' + devicename ); } return { adapterName: deviceidentifier, apiversion: API_VERSION, type, manufacturer, driverVersion: this.driverVersion, setup, devices: [ { name: devicename, tokens: additionalSearchTokens, specificname, icon, }, ], capabilities, handler, deviceCapabilities, timing, subscriptionFunction, initialiseFunction, }; } public enableDiscovery( options: Models.Discovery.Options, controller: Models.Discovery.Controller ) { debug('enable discovery %o', options); const { setup, discovery } = this; validation.checkNotYetDefined(setup.discovery, 'DISCOVERHANDLER'); validation.validateDiscovery(options, controller); const { headerText, description, enableDynamicDeviceBuilder } = options; this.setup = Object.assign(setup, { discovery: true, introheader: headerText, introtext: description, enableDynamicDeviceBuilder: enableDynamicDeviceBuilder === true, }); discovery.push({ controller }); return this; } public supportsTiming() { return !validation.deviceTypeDoesNotSupportTiming(this.type); } public supportsFavorites() { return validation.deviceTypeHasFavoritesSupport(this.type); } public defineTiming(param: Models.TimingSpecifier) { debug('define timing %o', param); validation.validateTiming(param); this.timing = { standbyCommandDelay: param.powerOnDelayMs, sourceSwitchDelay: param.sourceSwitchDelayMs, shutdownDelay: param.shutdownDelayMs, }; return this; } public registerSubscriptionFunction(controller: Models.Subscription.Controller) { debug('get subscription function'); validation.checkNotYetDefined(this.subscriptionFunction, 'SUBSCRIPTIONHANDLER'); validation.validateFunctionController(controller, 'SUBSCRIPTIONHANDLER'); this.subscriptionFunction = controller; return this; } public registerInitialiseFunction(controller: Models.InitialiseFunction) { debug('get initialise function'); validation.checkNotYetDefined(this.initializeFunction, 'INITIALISATIONHANDLER'); validation.validateFunctionController(controller, 'INITIALISATIONHANDLER'); this.initializeFunction = controller; return this; } public registerDeviceSubscriptionHandler( controller: Models.DeviceSubscriptionHandler.Controller ) { debug('enable device subscriptions'); validation.checkNotYetDefined(this.deviceSubscriptionHandlers, 'DEVICESUBSCRIPTIONHANDLERS'); validation.validateController(controller, { requiredFunctions: ['deviceAdded', 'deviceRemoved', 'initializeDeviceList'], handlerName: 'DEVICESUBSCRIPTION', }); this.deviceSubscriptionHandlers = controller; return this; } public registerFavoriteHandlers( controller: Models.FavoritesHandler.Controller ) { debug('enable favorite handlers'); validation.checkNotYetDefined(this.favoritesHandler, 'FAVORITE_HANDLERS'); validation.validateController(controller, { requiredFunctions: ['execute'], handlerName: 'FAVORITE', }); this.favoritesHandler = controller; return this; } public addButton(param: Models.ButtonDescriptor) { debug('add button %o', param); validation.checkNameFor(param); validation.checkLabelFor(param); this.buttons.push({ param }); return this; } public addButtonGroup(groupName: string) { debug('add buttongroup with name', groupName); const buttonGroup = validation.getButtonGroup(groupName); if (Array.isArray(buttonGroup)) { buttonGroup.forEach((name) => this.addButton({ name })); } return this; } public addButtonHandler(controller: Models.ButtonHandler) { debug('add buttonhandler'); validation.checkNotYetDefined(this.buttonHandler, 'BUTTONHANDLER'); validation.validateFunctionController(controller, 'BUTTONHANDLER'); this.buttonHandler = controller; return this; } public enableRegistration( options: Models.Registration.Options, controller: Models.Registration.Controller ) { const { setup, registration } = this; debug('enable registration %o', options); validation.checkNotYetDefined(setup.registration, 'REGISTERHANLDER'); validation.validateController(controller, { requiredFunctions: ['register', 'isRegistered'], handlerName: 'REGISTRATION', }); if (!options) { throw new Error('INVALID_REGISTRATION: Options cannot be undefined'); } validation.validateRegistrationType(options.type); if (!options.headerText || !options.description) { throw new Error('MISSING_REGISTRATION_HEADERTEXT_OR_DESCRIPTION'); } Object.assign(setup, { registration: true, registrationType: options.type, registrationHeader: options.headerText, registrationText: options.description, }); registration.push({ controller }); return this; } public addSlider(param: Models.Slider.Descriptor, controller: Models.Slider.Controller) { debug('add slider %o', param); validation.checkNameFor(param); validation.checkLabelFor(param); validation.validateController(controller, { requiredFunctions: ['setter', 'getter'], handlerName: 'SLIDER', componentName: param.name, }); this.sliders.push({ param, controller }); return this; } public addSensor(param: Models.Sensor.Descriptor, controller: Models.Sensor.Controller) { debug('add sensor %o', param); validation.checkNameFor(param); validation.checkLabelFor(param); validation.validateController(controller, { requiredFunctions: ['getter'], handlerName: 'SENSOR', componentName: param.name, }); this.sensors.push({ param, controller }); return this; } public addPowerStateSensor(controller: Models.Sensor.PowerStateController) { debug('add power sensor'); validation.validateController(controller, { requiredFunctions: ['getter'], handlerName: 'POWERSENSOR', }); const param = { name: 'powerstate', label: 'Powerstate', type: 'power', }; this.sensors.push({ param, controller }); this.hasPowerStateSensor = true; return this; } public addSwitch(param: Models.Descriptor, controller: Models.Switch.Controller) { debug('add switch %o', param); validation.checkNameFor(param); validation.checkLabelFor(param); validation.validateController(controller, { requiredFunctions: ['setter', 'getter'], handlerName: 'SWITCH', componentName: param.name, }); this.switches.push({ param, controller }); return this; } public addTextLabel( param: Models.TextLabel.Descriptor, getter: Models.TextLabel.Controller ) { debug('add textlabel %o', param); validation.checkNameFor(param); validation.checkLabelFor(param); validation.validateFunctionController(getter, `TEXTLABELHANDLER: ${param.name}`); // NOTE: we need a controller getter here this.textLabels.push({ param, controller: { getter } }); return this; } public addImageUrl(param: Models.Image.Descriptor, getter: Models.Image.Controller) { debug('add imageurl %o', param); validation.checkNameFor(param); validation.checkLabelFor(param); validation.validateFunctionController(getter, `IMAGEURLHANDLER: ${param.name}`); this.imageUrls.push({ param, controller: { getter } }); return this; } public addDirectory( param: Models.Directory.Descriptor, controller: Models.Directory.Controller ) { debug('add directory %o', param); validation.checkNameFor(param); validation.checkLabelFor(param, { mandatory: true }); validation.validateController(controller, { requiredFunctions: ['getter', 'action'], handlerName: 'DIRECTORY', componentName: param.name, }); const addedDirectoryRole = param.role; if (addedDirectoryRole) { this.checkDirectoryRole(addedDirectoryRole); } this.directories.push({ param, controller }); return this; } /** * @deprecated */ public addQueueDirectory( params: Models.Directory.Descriptor, controller: Models.Directory.Controller ) { // tslint:disable-next-line console.warn('WARNING: addQueueDirectory() is deprecated in favor of ' + 'addDirectory() and will be removed in future versions.'); const bridgeParams = Object.assign({ role: 'QUEUE' }, params); return this.addDirectory(bridgeParams, controller); } /** * @deprecated */ public addRootDirectory( params: Models.Directory.Descriptor, controller: Models.Directory.Controller ) { // tslint:disable-next-line console.warn('WARNING: addRootDirectory() is deprecated in favor of ' + 'addDirectory() and will be removed in future versions.'); const bridgeParams = Object.assign({ role: 'ROOT' }, params); return this.addDirectory(bridgeParams, controller); } public addCapability(capability: Models.DeviceStaticCapability) { debug('add capability %o', capability); this.deviceCapabilities.push(validation.validateCapability(capability)); return this; } public addPlayerWidget(handler: Models.PlayerWidget.Controller) { debug('adding player widget components'); validation.checkNotYetDefined(this.validatePlayerWidget, 'PLAYER_WIDGET'); validation.validatePlayerWidget(handler); this.addDirectory({ name: handler.rootDirectory.name || 'ROOT_DIRECTORY', label: handler.rootDirectory.label || 'ROOT', role: 'ROOT', }, handler.rootDirectory.controller); const queueDirectory = handler.queueDirectory; if (queueDirectory) { this.addDirectory({ name: queueDirectory.name || 'QUEUE_DIRECTORY', label: queueDirectory.label || 'QUEUE', role: 'QUEUE', }, queueDirectory.controller); } this.addSlider(PLAYER_VOLUME, handler.volumeController); this.addSensor(PLAYER_COVER_ART, handler.coverArtController); this.addSensor(PLAYER_DESCRIPTION, handler.descriptionController); this.addSensor(PLAYER_TITLE, handler.titleController); this.addSwitch(PLAYER_PLAYING, handler.playingController); this.addSwitch(PLAYER_MUTE, handler.muteController); this.addSwitch(PLAYER_SHUFFLE, handler.shuffleController); this.addSwitch(PLAYER_REPEAT, handler.repeatController); PLAYER_BUTTON_NAMES.forEach((name) => { this.addButton({ name }); }); this.validatePlayerWidget = true; return this; } /** * Do not break the SDK. This is a deprecated typo. * @param controller The button handler controller. */ public addButtonHander(controller: Models.ButtonHandler) { this.addButtonHandler(controller); } private checkDirectoryRole(role) { validation.validateDirectoryRole(role); const roleAlreadyDefined = this.directories.find((directory) => directory.param.role === role); if (roleAlreadyDefined) { throw new Error(`INVALID_DIRECTORY_ROLE_ALREADY_DEFINED: ${role}`); } } }
the_stack
// Copyright (c) 2015 Vadim Macagon // MIT License, see LICENSE file for full terms. import { TargetStopReason, IFrameInfo, IBreakpointInfo } from './types'; import { extractBreakpointInfo } from './extractors'; /** * Emitted when a thread group is added by the debugger, it's possible the thread group * hasn't yet been associated with a running program. * * Listener function should have the signature: * ~~~ * (e: [[IThreadGroupAddedEvent]]) => void * ~~~ * @event */ export const EVENT_THREAD_GROUP_ADDED: string = 'thdgrpadd'; /** * Emitted when a thread group is removed by the debugger. * * Listener function should have the signature: * ~~~ * (e: [[IThreadGroupRemovedEvent]]) => void * ~~~ * @event */ export const EVENT_THREAD_GROUP_REMOVED: string = 'thdgrprem'; /** * Emitted when a thread group is associated with a running program, * either because the program was started or the debugger was attached to it. * * Listener function should have the signature: * ~~~ * (e: [[IThreadGroupStartedEvent]]) => void * ~~~ * @event */ export const EVENT_THREAD_GROUP_STARTED: string = 'thdgrpstart'; /** * Emitted when a thread group ceases to be associated with a running program, * either because the program terminated or the debugger was dettached from it. * * Listener function should have the signature: * ~~~ * (e: [[IThreadGroupExitedEvent]]) => void * ~~~ * @event */ export const EVENT_THREAD_GROUP_EXITED: string = 'thdgrpexit'; /** * Emitted when a thread is created. * * Listener function should have the signature: * ~~~ * (e: [[IThreadCreatedEvent]]) => void * ~~~ * @event */ export const EVENT_THREAD_CREATED: string = 'thdcreate'; /** * Emitted when a thread exits. * * Listener function should have the signature: * ~~~ * (e: [[IThreadExitedEvent]]) => void * ~~~ * @event */ export const EVENT_THREAD_EXITED: string = 'thdexit'; /** * Emitted when the debugger changes the current thread selection. * * Listener function should have the signature: * ~~~ * (e: [[IThreadSelectedEvent]]) => void * ~~~ * @event */ export const EVENT_THREAD_SELECTED: string = 'thdselect'; /** * Emitted when a new library is loaded by the program being debugged. * * Listener function should have the signature: * ~~~ * (e: [[ILibLoadedEvent]]) => void * ~~~ * @event */ export const EVENT_LIB_LOADED: string = 'libload'; /** * Emitted when a library is unloaded by the program being debugged. * * Listener function should have the signature: * ~~~ * (e: [[ILibUnloadedEvent]]) => void * ~~~ * @event */ export const EVENT_LIB_UNLOADED: string = 'libunload'; /** * Emitted when some console output from the debugger becomes available, * usually in response to a CLI command. * * Listener function should have the signature: * ~~~ * (output: string) => void * ~~~ * @event */ export const EVENT_DBG_CONSOLE_OUTPUT: string = 'conout'; /** * Emitted when some console output from the target becomes available. * * Listener function should have the signature: * ~~~ * (output: string) => void * ~~~ * @event */ export const EVENT_TARGET_OUTPUT: string = 'targetout'; /** * Emitted when log output from the debugger becomes available. * * Listener function should have the signature: * ~~~ * (output: string) => void * ~~~ * @event */ export const EVENT_DBG_LOG_OUTPUT: string = 'dbgout'; /** * Emitted when the target starts running. * * The `threadId` passed to the listener indicates which specific thread is now running, * a value of **"all"** indicates all threads are running. According to the GDB/MI spec. * no interaction with a running thread is possible after this notification is produced until * it is stopped again. * * Listener function should have the signature: * ~~~ * (threadId: string) => void * ~~~ * @event */ export const EVENT_TARGET_RUNNING: string = 'targetrun'; /** * Emitted when the target stops running. * * Listener function should have the signature: * ~~~ * (e: [[ITargetStoppedEvent]]) => void * ~~~ * @event */ export const EVENT_TARGET_STOPPED: string = 'targetstop'; /** * Emitted when the target stops running because a breakpoint was hit. * * Listener function should have the signature: * ~~~ * (e: [[IBreakpointHitEvent]]) => void * ~~~ * @event */ export const EVENT_BREAKPOINT_HIT: string = 'brkpthit'; /** * Emitted when the target stops due to a stepping operation finishing. * * Listener function should have the signature: * ~~~ * (e: [[IStepFinishedEvent]]) => void * ~~~ * @event */ export const EVENT_STEP_FINISHED: string = 'endstep'; /** * Emitted when the target stops due to a step-out operation finishing. * * NOTE: Currently this event will not be emitted by LLDB-MI, it will only be emitted by GDB-MI, * so for the time being use [[EVENT_STEP_FINISHED]] with LLDB-MI. * * Listener function should have the signature: * ~~~ * (e: [[IStepOutFinishedEvent]]) => void * ~~~ * @event */ export const EVENT_FUNCTION_FINISHED: string = 'endfunc'; /** * Emitted when the target stops running because it received a signal. * * Listener function should have the signature: * ~~~ * (e: [[ISignalReceivedEvent]]) => void * ~~~ * @event */ export const EVENT_SIGNAL_RECEIVED: string = 'signal'; /** * Emitted when the target stops running due to an exception. * * Listener function should have the signature: * ~~~ * (e: [[IExceptionReceivedEvent]]) => void * ~~~ * @event */ export const EVENT_EXCEPTION_RECEIVED: string = 'exception'; /** * Emitted when a breakpoint is modified by the debugger. * * Listener function should have the signature: * ~~~ * (e: [[IBreakpointModifiedEvent]]) => void * ~~~ * @event */ export const EVENT_BREAKPOINT_MODIFIED = 'breakpoint-modified'; export interface IThreadGroupAddedEvent { id: string; } export interface IThreadGroupRemovedEvent { id: string; } export interface IThreadGroupStartedEvent { id: string; pid: string; } export interface IThreadGroupExitedEvent { id: string; exitCode: string; } export interface IThreadCreatedEvent { id: number; groupId: string; } export interface IThreadExitedEvent { id: number; groupId: string; } export interface IThreadSelectedEvent { id: number; } /** Notification sent whenever a library is loaded or unloaded by an inferior. */ export interface ILibEvent { id: string; /** Name of the library file on the target system. */ targetName: string; /** * Name of the library file on the host system. * When debugging locally this should be the same as `targetName`. */ hostName: string; /** * Optional identifier of the thread group within which the library was loaded. */ threadGroup: string; /** * Optional load address. * This field is not part of the GDB MI spec. and is only set by LLDB MI driver. */ loadAddress: string; /** * Optional path to a file containing additional debug information. * This field is not part of the GDB MI spec. and is only set by LLDB MI driver. * The LLDB MI driver gets the value for this field from SBModule::GetSymbolFileSpec(). */ symbolsPath: string; } export interface ILibLoadedEvent extends ILibEvent { } export interface ILibUnloadedEvent extends ILibEvent { } export interface ITargetStoppedEvent { reason: TargetStopReason; /** Identifier of the thread that caused the target to stop. */ threadId: number; /** * Identifiers of the threads that were stopped, * if all threads were stopped this array will be empty. */ stoppedThreads: number[]; /** * Processor core on which the stop event occured. * The debugger may not always provide a value for this field, in which case it will be `undefined`. */ processorCore: string; } export interface IBreakpointHitEvent extends ITargetStoppedEvent { breakpointId: number; frame: IFrameInfo; } export interface IStepFinishedEvent extends ITargetStoppedEvent { frame: IFrameInfo; } export interface IStepOutFinishedEvent extends ITargetStoppedEvent { frame: IFrameInfo; resultVar?: string; returnValue?: string; } export interface ISignalReceivedEvent extends ITargetStoppedEvent { signalCode?: string; signalName?: string; signalMeaning?: string; } export interface IExceptionReceivedEvent extends ITargetStoppedEvent { exception: string; } export interface IBreakpointModifiedEvent { breakpoint: IBreakpointInfo; } export interface IDebugSessionEvent { name: string; data: any; } export function createEventsForExecNotification(notification: string, data: any): IDebugSessionEvent[] { switch (notification) { case 'running': return [{ name: EVENT_TARGET_RUNNING, data: data['thread-id'] }]; case 'stopped': let stopEvent: ITargetStoppedEvent = { reason: parseTargetStopReason(data.reason), threadId: parseInt(data['thread-id'], 10), stoppedThreads: parseStoppedThreadsList(data['stopped-threads']), processorCore: data.core }; let events: IDebugSessionEvent[] = [{ name: EVENT_TARGET_STOPPED, data: stopEvent }]; // emit a more specialized event for notifications that contain additional info switch (stopEvent.reason) { case TargetStopReason.BreakpointHit: let breakpointHitEvent: IBreakpointHitEvent = { reason: stopEvent.reason, threadId: stopEvent.threadId, stoppedThreads: stopEvent.stoppedThreads, processorCore: stopEvent.processorCore, breakpointId: parseInt(data.bkptno, 10), frame: extractFrameInfo(data.frame) }; events.push({ name: EVENT_BREAKPOINT_HIT, data: breakpointHitEvent }); break; case TargetStopReason.EndSteppingRange: let stepFinishedEvent: IStepFinishedEvent = { reason: stopEvent.reason, threadId: stopEvent.threadId, stoppedThreads: stopEvent.stoppedThreads, processorCore: stopEvent.processorCore, frame: extractFrameInfo(data.frame) }; events.push({ name: EVENT_STEP_FINISHED, data: stepFinishedEvent }); break; case TargetStopReason.FunctionFinished: let stepOutEvent: IStepOutFinishedEvent = { reason: stopEvent.reason, threadId: stopEvent.threadId, stoppedThreads: stopEvent.stoppedThreads, processorCore: stopEvent.processorCore, frame: extractFrameInfo(data.frame), resultVar: data['gdb-result-var'], returnValue: data['return-value'] }; events.push({ name: EVENT_FUNCTION_FINISHED, data: stepOutEvent }); break; case TargetStopReason.SignalReceived: let signalEvent: ISignalReceivedEvent = { reason: stopEvent.reason, threadId: stopEvent.threadId, stoppedThreads: stopEvent.stoppedThreads, processorCore: stopEvent.processorCore, signalCode: data.signal, signalName: data['signal-name'], signalMeaning: data['signal-meaning'] }; events.push({ name: EVENT_SIGNAL_RECEIVED, data: signalEvent }); break; case TargetStopReason.ExceptionReceived: let exceptionEvent: IExceptionReceivedEvent = { reason: stopEvent.reason, threadId: stopEvent.threadId, stoppedThreads: stopEvent.stoppedThreads, processorCore: stopEvent.processorCore, exception: data.exception }; events.push({ name: EVENT_EXCEPTION_RECEIVED, data: exceptionEvent }); break; } return events; default: // TODO: log and keep on going return []; } } export function createEventForAsyncNotification(notification: string, data: any): IDebugSessionEvent { switch (notification) { case 'thread-group-added': return { name: EVENT_THREAD_GROUP_ADDED, data: data }; case 'thread-group-removed': return { name: EVENT_THREAD_GROUP_REMOVED, data: data }; case 'thread-group-started': return { name: EVENT_THREAD_GROUP_STARTED, data: data }; case 'thread-group-exited': let groupExitedEvent: IThreadGroupExitedEvent = { id: data.id, exitCode: data['exit-code'] }; return { name: EVENT_THREAD_GROUP_EXITED, data: groupExitedEvent }; case 'thread-created': const threadCreatedEvent: IThreadCreatedEvent = { id: data.id ? parseInt(data.id, 10) : undefined, groupId: data['group-id'] }; return { name: EVENT_THREAD_CREATED, data: threadCreatedEvent }; case 'thread-exited': const threadExitedEvent: IThreadExitedEvent = { id: data.id ? parseInt(data.id, 10) : undefined, groupId: data['group-id'] }; return { name: EVENT_THREAD_EXITED, data: threadExitedEvent }; case 'thread-selected': const threadSelectedEvent: IThreadSelectedEvent = { id: data.id ? parseInt(data.id, 10) : undefined }; return { name: EVENT_THREAD_SELECTED, data: threadSelectedEvent }; case 'library-loaded': let libLoadedEvent: ILibLoadedEvent = { id: data.id, targetName: data['target-name'], hostName: data['host-name'], threadGroup: data['thread-group'], symbolsPath: data['symbols-path'], loadAddress: data.loaded_addr }; return { name: EVENT_LIB_LOADED, data: libLoadedEvent }; case 'library-unloaded': let libUnloadedEvent: ILibUnloadedEvent = { id: data.id, targetName: data['target-name'], hostName: data['host-name'], threadGroup: data['thread-group'], symbolsPath: data['symbols-path'], loadAddress: data.loaded_addr }; return { name: EVENT_LIB_UNLOADED, data: libUnloadedEvent }; case 'breakpoint-modified': return { name: EVENT_BREAKPOINT_MODIFIED, data: <IBreakpointModifiedEvent> { breakpoint: extractBreakpointInfo(data) } }; default: // TODO: log and keep on going return undefined; }; } /** * Creates an object that conforms to the IFrameInfo interface from the output of the * MI Output parser. */ function extractFrameInfo(data: any): IFrameInfo { return { func: data.func, args: data.args, address: data.addr, filename: data.file, fullname: data.fullname, line: data.line ? parseInt(data.line, 10) : undefined, }; } // There are more reasons listed in the GDB/MI spec., the ones here are just the subset that's // actually used by LLDB MI at this time (11-Apr-2015). var targetStopReasonMap = new Map<string, TargetStopReason>() .set('breakpoint-hit', TargetStopReason.BreakpointHit) .set('end-stepping-range', TargetStopReason.EndSteppingRange) .set('function-finished', TargetStopReason.FunctionFinished) .set('exited-normally', TargetStopReason.ExitedNormally) .set('exited-signalled', TargetStopReason.ExitedSignalled) .set('exited', TargetStopReason.Exited) .set('signal-received', TargetStopReason.SignalReceived) .set('exception-received', TargetStopReason.ExceptionReceived); function parseTargetStopReason(reasonString: string): TargetStopReason { var reasonCode = targetStopReasonMap.get(reasonString); if (reasonCode !== undefined) { return reasonCode; } // TODO: log and keep on running return TargetStopReason.Unrecognized; } /** * Parses a list of stopped threads from a GDB/MI 'stopped' async notification. * @return An array of thread identifiers, an empty array is used to indicate that all threads * were stopped. */ function parseStoppedThreadsList(stoppedThreads: string): number[] { if (stoppedThreads === 'all') { return []; } else { // FIXME: GDB/MI spec. fails to specify what the format of the list is, need to experiment // to figure out what is actually produced by the debugger. return [parseInt(stoppedThreads, 10)]; } }
the_stack
const knownHTMLAttribs = [ "accept", "accept-charset", "accesskey", "action", "align", "alt", "async", "autocomplete", "autofocus", "autoplay", "bgcolor", "border", "cellpadding", "cellspacing", "charset", "checked", "cite", "class", "color", "cols", "colspan", "content", "contenteditable", "controls", "coords", "data", "data-*", "datetime", "default", "defer", "dir", "dirname", "disabled", "download", "draggable", "dropzone", "enctype", "for", "form", "formaction", "headers", "height", "hidden", "high", "href", "hreflang", "http-equiv", "id", "ismap", "kind", "label", "lang", "list", "loop", "low", "max", "maxlength", "media", "method", "min", "multiple", "muted", "name", "novalidate", "onabort", "onafterprint", "onbeforeprint", "onbeforeunload", "onblur", "oncanplay", "oncanplaythrough", "onchange", "onclick", "oncontextmenu", "oncopy", "oncuechange", "oncut", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onhashchange", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onoffline", "ononline", "onpagehide", "onpageshow", "onpaste", "onpause", "onplay", "onplaying", "onpopstate", "onprogress", "onratechange", "onreset", "onresize", "onscroll", "onsearch", "onseeked", "onseeking", "onselect", "onstalled", "onstorage", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onunload", "onvolumechange", "onwaiting", "onwheel", "open", "optimum", "pattern", "placeholder", "poster", "preload", "readonly", "rel", "required", "reversed", "rows", "rowspan", "sandbox", "scope", "selected", "shape", "size", "sizes", "span", "spellcheck", "src", "srcdoc", "srclang", "srcset", "start", "step", "style", "tabindex", "target", "title", "translate", "type", "usemap", "value", "width", "wrap", ]; const knownUnits = [ "cm", "mm", "in", "px", "pt", "pc", "em", "ex", "ch", "rem", "vw", "vh", "vmin", "vmax", "%", ]; const knownCharsets = [ "adobe-standard-encoding", "adobe-symbol-encoding", "amiga-1251", "ansi_x3.110-1983", "asmo_449", "big5", "big5-hkscs", "bocu-1", "brf", "bs_4730", "bs_viewdata", "cesu-8", "cp50220", "cp51932", "csa_z243.4-1985-1", "csa_z243.4-1985-2", "csa_z243.4-1985-gr", "csn_369103", "dec-mcs", "din_66003", "dk-us", "ds_2089", "ebcdic-at-de", "ebcdic-at-de-a", "ebcdic-ca-fr", "ebcdic-dk-no", "ebcdic-dk-no-a", "ebcdic-es", "ebcdic-es-a", "ebcdic-es-s", "ebcdic-fi-se", "ebcdic-fi-se-a", "ebcdic-fr", "ebcdic-it", "ebcdic-pt", "ebcdic-uk", "ebcdic-us", "ecma-cyrillic", "es", "es2", "euc-kr", "extended_unix_code_fixed_width_for_japanese", "extended_unix_code_packed_format_for_japanese", "gb18030", "gb2312", "gb_1988-80", "gb_2312-80", "gbk", "gost_19768-74", "greek-ccitt", "greek7", "greek7-old", "hp-desktop", "hp-legal", "hp-math8", "hp-pi-font", "hp-roman8", "hz-gb-2312", "ibm-symbols", "ibm-thai", "ibm00858", "ibm00924", "ibm01140", "ibm01141", "ibm01142", "ibm01143", "ibm01144", "ibm01145", "ibm01146", "ibm01147", "ibm01148", "ibm01149", "ibm037", "ibm038", "ibm1026", "ibm1047", "ibm273", "ibm274", "ibm275", "ibm277", "ibm278", "ibm280", "ibm281", "ibm284", "ibm285", "ibm290", "ibm297", "ibm420", "ibm423", "ibm424", "ibm437", "ibm500", "ibm775", "ibm850", "ibm851", "ibm852", "ibm855", "ibm857", "ibm860", "ibm861", "ibm862", "ibm863", "ibm864", "ibm865", "ibm866", "ibm868", "ibm869", "ibm870", "ibm871", "ibm880", "ibm891", "ibm903", "ibm904", "ibm905", "ibm918", "iec_p27-1", "inis", "inis-8", "inis-cyrillic", "invariant", "iso-10646-j-1", "iso-10646-ucs-2", "iso-10646-ucs-4", "iso-10646-ucs-basic", "iso-10646-unicode-latin1", "iso-10646-utf-1", "iso-11548-1", "iso-2022-cn", "iso-2022-cn-ext", "iso-2022-jp", "iso-2022-jp-2", "iso-2022-kr", "iso-8859-1-windows-3.0-latin-1", "iso-8859-1-windows-3.1-latin-1", "iso-8859-10", "iso-8859-13", "iso-8859-14", "iso-8859-15", "iso-8859-16", "iso-8859-2-windows-latin-2", "iso-8859-9-windows-latin-5", "iso-ir-90", "iso-unicode-ibm-1261", "iso-unicode-ibm-1264", "iso-unicode-ibm-1265", "iso-unicode-ibm-1268", "iso-unicode-ibm-1276", "iso_10367-box", "iso_2033-1983", "iso_5427", "iso_5427:1981", "iso_5428:1980", "iso_646.basic:1983", "iso_646.irv:1983", "iso_6937-2-25", "iso_6937-2-add", "iso_8859-1:1987", "iso_8859-2:1987", "iso_8859-3:1988", "iso_8859-4:1988", "iso_8859-5:1988", "iso_8859-6-e", "iso_8859-6-i", "iso_8859-6:1987", "iso_8859-7:1987", "iso_8859-8-e", "iso_8859-8-i", "iso_8859-8:1988", "iso_8859-9:1989", "iso_8859-supp", "it", "jis_c6220-1969-jp", "jis_c6220-1969-ro", "jis_c6226-1978", "jis_c6226-1983", "jis_c6229-1984-a", "jis_c6229-1984-b", "jis_c6229-1984-b-add", "jis_c6229-1984-hand", "jis_c6229-1984-hand-add", "jis_c6229-1984-kana", "jis_encoding", "jis_x0201", "jis_x0212-1990", "jus_i.b1.002", "jus_i.b1.003-mac", "jus_i.b1.003-serb", "koi7-switched", "koi8-r", "koi8-u", "ks_c_5601-1987", "ksc5636", "kz-1048", "latin-greek", "latin-greek-1", "latin-lap", "macintosh", "microsoft-publishing", "mnem", "mnemonic", "msz_7795.3", "nats-dano", "nats-dano-add", "nats-sefi", "nats-sefi-add", "nc_nc00-10:81", "nf_z_62-010", "nf_z_62-010_(1973)", "ns_4551-1", "ns_4551-2", "osd_ebcdic_df03_irv", "osd_ebcdic_df04_1", "osd_ebcdic_df04_15", "pc8-danish-norwegian", "pc8-turkish", "pt", "pt2", "ptcp154", "scsu", "sen_850200_b", "sen_850200_c", "shift_jis", "t.101-g2", "t.61-7bit", "t.61-8bit", "tis-620", "tscii", "unicode-1-1", "unicode-1-1-utf-7", "unknown-8bit", "us-ascii", "us-dk", "utf-16", "utf-16be", "utf-16le", "utf-32", "utf-32be", "utf-32le", "utf-7", "utf-8", "ventura-international", "ventura-math", "ventura-us", "videotex-suppl", "viqr", "viscii", "windows-1250", "windows-1251", "windows-1252", "windows-1253", "windows-1254", "windows-1255", "windows-1256", "windows-1257", "windows-1258", "windows-31j", "windows-874", ]; // https://www.w3.org/TR/html4/sgml/loosedtd.html#Color // "There are also 16 widely known color names with their sRGB values" const basicColorNames = { aqua: "#00ffff", black: "#000000", blue: "#0000ff", fuchsia: "#ff00ff", gray: "#808080", green: "#008000", lime: "#00ff00", maroon: "#800000", navy: "#000080", olive: "#808000", purple: "#800080", red: "#ff0000", silver: "#c0c0c0", teal: "#008080", white: "#ffffff", yellow: "#ffff00", }; // https://www.w3schools.com/colors/colors_names.asp // https://developer.mozilla.org/en-US/docs/Web/CSS/color_value const extendedColorNames = { aliceblue: "#f0f8ff", antiquewhite: "#faebd7", aqua: "#00ffff", aquamarine: "#7fffd4", azure: "#f0ffff", beige: "#f5f5dc", bisque: "#ffe4c4", black: "#000000", blanchedalmond: "#ffebcd", blue: "#0000ff", blueviolet: "#8a2be2", brown: "#a52a2a", burlywood: "#deb887", cadetblue: "#5f9ea0", chartreuse: "#7fff00", chocolate: "#d2691e", coral: "#ff7f50", cornflowerblue: "#6495ed", cornsilk: "#fff8dc", crimson: "#dc143c", cyan: "#00ffff", darkblue: "#00008b", darkcyan: "#008b8b", darkgoldenrod: "#b8860b", darkgray: "#a9a9a9", darkgrey: "#a9a9a9", darkgreen: "#006400", darkkhaki: "#bdb76b", darkmagenta: "#8b008b", darkolivegreen: "#556b2f", darkorange: "#ff8c00", darkorchid: "#9932cc", darkred: "#8b0000", darksalmon: "#e9967a", darkseagreen: "#8fbc8f", darkslateblue: "#483d8b", darkslategray: "#2f4f4f", darkslategrey: "#2f4f4f", darkturquoise: "#00ced1", darkviolet: "#9400d3", deeppink: "#ff1493", deepskyblue: "#00bfff", dimgray: "#696969", dimgrey: "#696969", dodgerblue: "#1e90ff", firebrick: "#b22222", floralwhite: "#fffaf0", forestgreen: "#228b22", fuchsia: "#ff00ff", gainsboro: "#dcdcdc", ghostwhite: "#f8f8ff", gold: "#ffd700", goldenrod: "#daa520", gray: "#808080", grey: "#808080", green: "#008000", greenyellow: "#adff2f", honeydew: "#f0fff0", hotpink: "#ff69b4", indianred: "#cd5c5c", indigo: "#4b0082", ivory: "#fffff0", khaki: "#f0e68c", lavender: "#e6e6fa", lavenderblush: "#fff0f5", lawngreen: "#7cfc00", lemonchiffon: "#fffacd", lightblue: "#add8e6", lightcoral: "#f08080", lightcyan: "#e0ffff", lightgoldenrodyellow: "#fafad2", lightgray: "#d3d3d3", lightgrey: "#d3d3d3", lightgreen: "#90ee90", lightpink: "#ffb6c1", lightsalmon: "#ffa07a", lightseagreen: "#20b2aa", lightskyblue: "#87cefa", lightslategray: "#778899", lightslategrey: "#778899", lightsteelblue: "#b0c4de", lightyellow: "#ffffe0", lime: "#00ff00", limegreen: "#32cd32", linen: "#faf0e6", magenta: "#ff00ff", maroon: "#800000", mediumaquamarine: "#66cdaa", mediumblue: "#0000cd", mediumorchid: "#ba55d3", mediumpurple: "#9370db", mediumseagreen: "#3cb371", mediumslateblue: "#7b68ee", mediumspringgreen: "#00fa9a", mediumturquoise: "#48d1cc", mediumvioletred: "#c71585", midnightblue: "#191970", mintcream: "#f5fffa", mistyrose: "#ffe4e1", moccasin: "#ffe4b5", navajowhite: "#ffdead", navy: "#000080", oldlace: "#fdf5e6", olive: "#808000", olivedrab: "#6b8e23", orange: "#ffa500", orangered: "#ff4500", orchid: "#da70d6", palegoldenrod: "#eee8aa", palegreen: "#98fb98", paleturquoise: "#afeeee", palevioletred: "#db7093", papayawhip: "#ffefd5", peachpuff: "#ffdab9", peru: "#cd853f", pink: "#ffc0cb", plum: "#dda0dd", powderblue: "#b0e0e6", purple: "#800080", rebeccapurple: "#663399", red: "#ff0000", rosybrown: "#bc8f8f", royalblue: "#4169e1", saddlebrown: "#8b4513", salmon: "#fa8072", sandybrown: "#f4a460", seagreen: "#2e8b57", seashell: "#fff5ee", sienna: "#a0522d", silver: "#c0c0c0", skyblue: "#87ceeb", slateblue: "#6a5acd", slategray: "#708090", slategrey: "#708090", snow: "#fffafa", springgreen: "#00ff7f", steelblue: "#4682b4", tan: "#d2b48c", teal: "#008080", thistle: "#d8bfd8", tomato: "#ff6347", turquoise: "#40e0d0", violet: "#ee82ee", wheat: "#f5deb3", white: "#ffffff", whitesmoke: "#f5f5f5", yellow: "#ffff00", yellowgreen: "#9acd32", }; const sixDigitHexColorRegex = /^#([a-f0-9]{6})$/i; const classNameRegex = /^-?[_a-zA-Z]+[_a-zA-Z0-9-]*$/; export { knownUnits, knownCharsets, classNameRegex, basicColorNames, knownHTMLAttribs, extendedColorNames, sixDigitHexColorRegex, };
the_stack
import { BackingObjectMap, FieldMapping, StepMapping } from '../../views/landing/wizard/shared/field-mapping/FieldMapping'; import { PersistentStore } from '../../views/landing/wizard/shared/PersistentStore'; export interface UserDataEntry { display: string, // what the user should see if this is displayed on a page value: any, // actual value } export interface UserDataIdentifier { wizard: string, // name of the wizard that the data is from step: string, // name of the step that the data is from field: string, // name of field that the data is from } // UserDataWizard should only be used by the confirmation page; all steps should use convenience methods export interface UserDataWizard { wizard: string, steps: Map<string, UserDataStep>, displayOrder?: string[], titles?: Map<string, string>, descriptions?: Map<string, string>, lastUpdate?: number, } // UserDataStep should only be used by the confirmation page; all steps should use convenience methods export interface UserDataStep { displayOrder?: string[], fields: Map<string, UserDataEntry>, labels?: Map<string, string>, } const DATA_CONSIDERED_OLD_AFTER_MINUTES = 30; export class UserDataService { static readonly MASK = '********'; store(identifier: UserDataIdentifier, data: UserDataEntry) { const wizardEntry = this.ensureUserDataIdentifier(identifier); this.setUserDataEntry(wizardEntry, identifier, data); this.storeWizardEntry(wizardEntry); } // storeBackingObject expects to encounter an OBJECT backing the listbox and will use fieldDisplay of that object for the display // and fieldValue for the value. If instead the caller has a simple listbox with strings backing it, call saveInputField instead storeBackingObject(identifier: UserDataIdentifier, backingObject: any, backingObjectMap: BackingObjectMap): boolean { let display = ''; let value = ''; // Note: selectedObj === null is a legitimate case: the user hasn't selected an object yet if (backingObject) { display = backingObject[backingObjectMap.displayField]; value = backingObject[backingObjectMap.valueField]; } this.store(identifier, { display, value }); return true; } storeBoolean(identifier: UserDataIdentifier, value: boolean): boolean { this.store(identifier, { display: value ? 'yes' : 'no', value }); return true; } storeMap(identifier: UserDataIdentifier, map: Map<string, string>) { const display = this.mapToDisplayString(map); // TODO: find a way to store the map directly: const value = map; const value = display; this.store(identifier, { display, value }); } storeStepDisplayOrder(wizard, step: string, displayOrder: string[]) { const wizardEntry = this.ensureWizardEntry(wizard); this.ensureStepEntry(wizardEntry, step); wizardEntry.steps[step].displayOrder = displayOrder; this.storeWizardEntry(wizardEntry); } storeStepLabels(wizard, step: string, labels: Map<string, string>) { const wizardEntry = this.ensureWizardEntry(wizard); this.ensureStepEntry(wizardEntry, step); wizardEntry.steps[step].labels = labels; this.storeWizardEntry(wizardEntry); } storeWizardDescriptions(wizard: string, descriptions: Map<string, string>) { const wizardEntry = this.ensureWizardEntry(wizard); wizardEntry.descriptions = descriptions; this.storeWizardEntry(wizardEntry); } storeWizardDisplayOrder(wizard: string, displayOrder: string[]) { const wizardEntry = this.ensureWizardEntry(wizard); wizardEntry.displayOrder = displayOrder; this.storeWizardEntry(wizardEntry); } storeWizardTitles(wizard: string, titles: Map<string, string>) { const wizardEntry = this.ensureWizardEntry(wizard); wizardEntry.titles = titles; this.storeWizardEntry(wizardEntry); } private retrieve(identifier: UserDataIdentifier): UserDataEntry { const wizardEntry: UserDataWizard = this.getWizardEntry(identifier.wizard); if (!wizardEntry || !wizardEntry.steps || !wizardEntry.steps[identifier.step] || !wizardEntry.steps[identifier.step].fields) { return null; } return wizardEntry.steps[identifier.step].fields[identifier.field]; } private retrieveMap(identifier: UserDataIdentifier): Map<string, string> { const storedEntry = this.retrieve(identifier); if (!storedEntry || !storedEntry.value) { return new Map<string, string>(); } return this.stringToMap(storedEntry.value); } retrieveStoredValue(wizard, step: string, fieldMapping: FieldMapping): any { if (!fieldMapping) { console.error('trying to retrieveStoredValue for ' + wizard + '.' + step + ' but fieldMapping undefined'); return null; } const identifier = {wizard, step, field: fieldMapping.name}; if (fieldMapping.isMap) { return this.retrieveMap(identifier); } const storedEntry = this.retrieve(identifier); if (!storedEntry) { return undefined; } if (fieldMapping.backingObject) { if (!fieldMapping.retriever) { console.error('Trying to restore field ' + fieldMapping.name + ' but no object retriever provided'); return undefined; } return fieldMapping.retriever(storedEntry.value); } return storedEntry.value; } // retrieveWizardEntry() is generally an INTERNAL method, but available to the confirmation page retrieveWizardEntry(wizard: string) { return this.ensureWizardEntry(wizard); } delete(identifier: UserDataIdentifier) { const wizardEntry = this.getWizardEntry(identifier.wizard); if (wizardEntry && wizardEntry.steps[identifier.step] && wizardEntry.steps[identifier.step].fields) { delete wizardEntry.steps[identifier.step].fields[identifier.field]; this.storeWizardEntry(wizardEntry); } } // The ONLY time this method should be called is if the user explicitly says to erase "old" data deleteWizardData(wizard: string) { PersistentStore.removeItem(this.keyWizard(wizard)); } clear(identifier: UserDataIdentifier) { const wizardEntry = this.getWizardEntry(identifier.wizard); if (wizardEntry && wizardEntry.steps[identifier.step] && wizardEntry.steps[identifier.step].fields) { this.setUserDataEntry(wizardEntry, identifier, null); this.storeWizardEntry(wizardEntry); } } fieldsWithStoredData(wizard, step: string, fields: string[]): string[] { return fields.filter(field => this.hasStoredData({wizard, step, field})); } hasStoredData(identifier: UserDataIdentifier): boolean { const userDataEntry = this.retrieve(identifier); // NOTE: we want a value of 'false' to return TRUE (that there IS a value) return userDataEntry && userDataEntry.value !== null && userDataEntry.value !== undefined && userDataEntry.value !== ''; } hasStoredStepData(wizard, step: string) { const wizardEntry = this.retrieveWizardEntry(wizard); if (!wizardEntry) { return false; } const stepEntry = wizardEntry.steps[step]; return stepEntry !== undefined && stepEntry !== null; } // The ONLY times this method should be called outside this class: // (1) the user explicitly says to "restore" their old data, meaning we should consider it current again, and // (2) the user imports a data file updateWizardTimestamp(wizard: string) { const wizardEntry = this.ensureWizardEntry(wizard); wizardEntry.lastUpdate = Date.now(); this.storeWizardEntry(wizardEntry); } isWizardDataOld(wizard: string): boolean { const wizardEntry = this.retrieveWizardEntry(wizard); if (!wizardEntry) { return false; // if there's no data, it can't be old! } if (!wizardEntry.lastUpdate) { return true; // if there's no timestamp, we assume the data is old; the user never saved a full form? } const lastSavedDate = new Date(wizardEntry.lastUpdate); // get difference between dates in milliseconds, convert to minutes const minAgoSaved = ((Date.now() - lastSavedDate.getTime()) / 60000); return minAgoSaved > DATA_CONSIDERED_OLD_AFTER_MINUTES; } // This internal convenience method is meant to isolate the access to the internal structure private setUserDataEntry(wizardEntry: UserDataWizard, identifier: UserDataIdentifier, data: UserDataEntry) { wizardEntry.steps[identifier.step].fields[identifier.field] = data; } // string format is "key:value, key2:value2, key3:value3"; for display purposes only private mapToDisplayString(map: Map<string, string>): string { let labelsStr: string = ''; map.forEach((value, key) => labelsStr += key + ':' + value + ', '); return labelsStr.slice(0, -2); // chop off the last ', ' } private stringToMap(source: string): Map<string, string> { const result = new Map<string, string>(); if (source) { const keyValuePairs = source.split(', ') keyValuePairs.map(label => { const keyAndValue = label.split(':'); result.set(keyAndValue[0], keyAndValue[1]); }); } return result; } private getWizardEntry(wizard: string): UserDataWizard { return PersistentStore.getItem(this.keyWizard(wizard)); } private ensureWizardEntry(wizard: string): UserDataWizard { // get the wizard entry, or create a new one let wizardEntry = this.getWizardEntry(wizard); if (!wizardEntry) { wizardEntry = this.createUserDataWizard(wizard); } return wizardEntry; } private ensureStepEntry(wizardEntry, step: string): UserDataWizard { // if the step entry isn't there, create it if (!wizardEntry.steps[step]) { this.createUserStepEntry(wizardEntry, step); } return wizardEntry; } private ensureUserDataIdentifier(identifier: UserDataIdentifier): UserDataWizard { const wizardEntry = this.ensureWizardEntry(identifier.wizard); this.ensureStepEntry(wizardEntry, identifier.step); return wizardEntry; } private createUserDataWizard(wizard: string): UserDataWizard { return { wizard, steps: new Map<string, UserDataStep>() }; } private createUserStepEntry(wizardEntry: UserDataWizard, step: string) { const newStepEntry: UserDataStep = { fields: new Map<string, UserDataEntry>(), } wizardEntry.steps[step] = newStepEntry; } private keyWizard(wizard: string): string { return wizard + 'Storage'; } private storeWizardEntry(wizardEntry: UserDataWizard) { PersistentStore.setItem(this.keyWizard(wizardEntry.wizard), wizardEntry); } }
the_stack
import { autobind } from 'core-decorators'; import FocusTrap from 'focus-trap-react'; import { List, Set } from 'immutable'; import keyboardJS from 'keyboardjs'; import qs from 'query-string'; import React from 'react'; import { RouteComponentProps, withRouter } from 'react-router'; import { Link } from 'react-router-dom'; import { ICommentModel, ICommentScoreModel, ICommentSummaryScoreModel, ITaggingSensitivityModel, ITagModel, IUserModel, ModelId, } from '../../../../../models'; import { IConfirmationAction, IModerationAction, } from '../../../../../types'; import { Arrow, ArrowIcon, ConfirmationCircle, InfoIcon, ModerateButtons, ReplyIcon, ScoresList, Scrim, SingleComment, ToolTip, } from '../../../../components'; import { REQUIRE_REASON_TO_REJECT } from '../../../../config'; import { COMMENTS_EDITABLE_FLAG, MODERATOR_GUIDELINES_URL, SUBMIT_FEEDBACK_URL, } from '../../../../config'; import { ICommentCacheProps } from '../../../../injectors/commentFetchQueue'; import { commentInjector } from '../../../../injectors/commentInjector'; import { approveComments, deferComments, highlightComments, ICommentActionFunction, rejectComments, resetComments, tagComment, tagCommentSummaryScores, tagCommentWithAnnotation, untagComment, } from '../../../../stores/commentActions'; import { BASE_Z_INDEX, BOTTOM_BORDER_TRANSITION, BOX_DEFAULT_SPACING, BUTTON_LINK_TYPE, BUTTON_RESET, DARK_COLOR, DARK_SECONDARY_TEXT_COLOR, DARK_TERTIARY_TEXT_COLOR, DIVIDER_COLOR, GUTTER_DEFAULT_SPACING, HEADER_HEIGHT, NICE_MIDDLE_BLUE, PALE_COLOR, SCRIM_STYLE, SCRIM_Z_INDEX, SELECT_Z_INDEX, TEXT_OFFSET_DEFAULT_SPACING, VISUALLY_HIDDEN, WHITE_COLOR, } from '../../../../styles'; import { clearReturnSavedCommentRow, partial, setReturnSavedCommentRow, timeout } from '../../../../util'; import { css, stylesheet } from '../../../../utilx'; import { commentDetailsPageLink, commentRepliesDetailsLink, ICommentDetailsPathParams, isArticleContext, NEW_COMMENTS_DEFAULT_TAG, newCommentsPageLink, } from '../../../routes'; import { getReducedScoresAboveThreshold, getScoresAboveThreshold, getSensitivitiesForCategory, } from '../../scoreFilters'; import { Shortcuts } from '../Shortcuts'; const actionMap: { [key: string]: ICommentActionFunction; } = { highlight: highlightComments, approve: approveComments, defer: deferComments, reject: rejectComments, reset: resetComments, }; const COMMENT_WRAPPER_WIDTH = 696; const KEYBOARD_SHORTCUTS_POPUP_ID = 'keyboard-shortcuts'; const SCORES_POPUP_ID = 'scores-popup'; const CONFIRMATION_POPUP_ID = 'confirmation-popup'; const INFO_DROPDOWN_ID = 'info-dropdown'; const APPROVE_SHORTCUT = 'alt + a'; const REJECT_SHORTCUT = 'alt + r'; const DEFER_SHORTCUT = 'alt + d'; const HIGHLIGHT_SHORTCUT = 'alt + h'; const ESCAPE_SHORTCUT = 'escape'; const PREV_SHORTCUT = 'alt + up'; const NEXT_SHORTCUT = 'alt + down'; const STYLES = stylesheet({ wrapper: { height: '100%', }, commentWrapper: { display: 'flex', position: 'relative', boxSizing: 'border-box', padding: '0 142px 0 76px', height: '100%', overflowY: 'scroll', }, comment: { padding: `${TEXT_OFFSET_DEFAULT_SPACING}px 0`, width: '100%', maxWidth: `${COMMENT_WRAPPER_WIDTH}px`, margin: '0 auto', }, sidebar: { position: 'fixed', display: 'flex', top: HEADER_HEIGHT, bottom: 10, right: GUTTER_DEFAULT_SPACING, zIndex: SELECT_Z_INDEX, }, buttons: { alignSelf: 'center', }, pagers: { width: '58px', position: 'absolute', bottom: '0px', right: '0px', }, popup: { ...SCRIM_STYLE.popup, width: '100%', minWidth: '500px', maxHeight: '600px', }, infoTrigger: { position: 'fixed', bottom: '24px', left: '24px', background: 'none', border: '0px', cursor: 'pointer', ':focus': { outline: 0, }, }, infoList: { listStyle: 'none', padding: '5px', width: '200px', }, infoTooltipButton: { ...BUTTON_LINK_TYPE, width: '100%', textAlign: 'left', paddingLeft: `${BOX_DEFAULT_SPACING}px`, paddingRight: `${BOX_DEFAULT_SPACING}px`, background: 'none', border: '0px', color: DARK_COLOR, cursor: 'pointer', }, scrim: { zIndex: SCRIM_Z_INDEX, }, scrim1: { zIndex: BASE_Z_INDEX, }, subHeading: { ...BUTTON_RESET, cursor: 'pointer', display: 'flex', alignItems: 'center', background: PALE_COLOR, height: HEADER_HEIGHT, paddingLeft: GUTTER_DEFAULT_SPACING, paddingRight: GUTTER_DEFAULT_SPACING, position: 'absolute', width: '100%', zIndex: BASE_Z_INDEX, textDecoration: 'none', ':focus': { outline: 0, textDecoration: 'underline', }, }, selectedInfo: { ...BOTTOM_BORDER_TRANSITION, marginLeft: GUTTER_DEFAULT_SPACING, color: DARK_COLOR, }, replyButton: { border: 'none', backgroundColor: 'transparent', color: DARK_COLOR, ':focus': { outline: 0, textDecoration: 'underline', }, }, replyIcon: { marginRight: `${BOX_DEFAULT_SPACING}px`, display: 'inline-block', transform: 'translateY(-4px)', }, loadIcon: { fill: DARK_COLOR, display: 'flex', margin: '50% auto 0 auto', }, replyToContainer: { borderBottom: `2px solid ${DIVIDER_COLOR}`, height: HEADER_HEIGHT, display: 'flex', alignItems: 'center', }, resultsHeader: { alignItems: 'center', backgroundColor: PALE_COLOR, color: NICE_MIDDLE_BLUE, display: 'flex', flexWrap: 'no-wrap', justifyContent: 'space-between', }, resultsHeadline: { marginLeft: '29px', }, resultsLink: { color: NICE_MIDDLE_BLUE, cursor: 'pointer', }, paginationArrow: { display: 'block', ':focus': { outline: 0, textDecoration: 'underline,', }, }, confirmationPopup: { ':focus': { outline: 0, }, }, }); interface IReplyLinkProps extends RouteComponentProps<ICommentDetailsPathParams>, ICommentCacheProps { commentId: ModelId; parent: ICommentModel; } function _ReplyLink(props: IReplyLinkProps) { const comment = props.comment; return ( <div {...css(STYLES.replyToContainer)}> <Link to={commentRepliesDetailsLink({ context: props.match.params.context, contextId: props.match.params.contextId, commentId: comment.id, })} {...css(STYLES.replyButton)} > <div {...css(STYLES.replyIcon)}> <ReplyIcon {...css({fill: DARK_COLOR})} size={24} /> </div> This is a reply to {comment.author && comment.author.name} </Link> </div> ); } const ReplyLink = withRouter(commentInjector(_ReplyLink)); export interface ICommentDetailProps extends RouteComponentProps<ICommentDetailsPathParams> { comment: ICommentModel; availableTags: List<ITagModel>; allScores?: Array<ICommentScoreModel>; taggingSensitivities: List<ITaggingSensitivityModel>; currentCommentIndex?: number; nextCommentId?: string; previousCommentId?: string; isFromBatch?: boolean; loadData?(commentId: string): void; loadScores?(commentId: string): void; getUserById?(id: string | number): IUserModel; currentUser: IUserModel; detailSource?: string; linkBackToList?: string; } export interface ICommentDetailState { taggingSensitivitiesInCategory?: List<ITaggingSensitivityModel>; allScoresAboveThreshold?: Array<ICommentScoreModel>; reducedScoresAboveThreshold?: Array<ICommentScoreModel>; loadedCommentId?: string; isKeyboardModalVisible?: boolean; isConfirmationModalVisible?: boolean; isScoresModalVisible?: boolean; scoresSelectedByTag?: Array<ICommentScoreModel>; thresholdByTag?: ITaggingSensitivityModel; confirmationAction?: IConfirmationAction; isInfoDropdownVisible?: boolean; infoToolTipPosition?: { top: number, left: number, }; upArrowIsFocused?: boolean; downArrowIsFocused?: boolean; infoIconFocused?: boolean; selectedRow?: number; taggingCommentId?: string; } export class CommentDetail extends React.Component<ICommentDetailProps, ICommentDetailState> { state: ICommentDetailState = { isKeyboardModalVisible: false, isConfirmationModalVisible: false, confirmationAction: null, isInfoDropdownVisible: false, isScoresModalVisible: false, scoresSelectedByTag: null, thresholdByTag: null, infoToolTipPosition: { top: 0, left: 0, }, upArrowIsFocused: false, downArrowIsFocused: false, infoIconFocused: false, taggingCommentId: null, }; buttonRef: HTMLElement = null; componentDidMount() { this.attachEvents(); } componentWillUnmount() { this.detachEvents(); } static getDerivedStateFromProps(nextProps: ICommentDetailProps, prevState: ICommentDetailState) { const categoryId = (nextProps.comment && nextProps.comment.categoryId) || 'na'; const sensitivities = getSensitivitiesForCategory(categoryId, nextProps.taggingSensitivities); const allScoresAboveThreshold = getScoresAboveThreshold(sensitivities, nextProps.allScores); const reducedScoresAboveThreshold = getReducedScoresAboveThreshold(sensitivities, nextProps.allScores); if (prevState.loadedCommentId !== nextProps.match.params.commentId) { nextProps.loadData(nextProps.match.params.commentId); } return { taggingSensitivitiesInCategory: sensitivities, allScoresAboveThreshold, reducedScoresAboveThreshold, loadedCommentId: nextProps.match.params.commentId, }; } @autobind onFocusUpArrow() { this.setState({ upArrowIsFocused: true }); } @autobind onBlurUpArrow() { this.setState({ upArrowIsFocused: false }); } @autobind onFocusDownArrow() { this.setState({ downArrowIsFocused: true }); } @autobind onBlurDownArrow() { this.setState({ downArrowIsFocused: false }); } @autobind onFocusInfoIcon() { this.setState({ infoIconFocused: true }); } @autobind onBlurInfoIcon() { this.setState({ infoIconFocused: false }); } @autobind saveButtonRef(ref: HTMLButtonElement) { this.buttonRef = ref; } @autobind saveReturnRow(commentId: string): void { setReturnSavedCommentRow(commentId); } @autobind async handleAssignTagsSubmit(commentId: ModelId, selectedTagIds: Set<ModelId>) { selectedTagIds.forEach((tagId) => { tagCommentSummaryScores([commentId], tagId); }); this.moderateComment('reject'); this.setState({ taggingCommentId: null, }); } render() { const { comment, availableTags, allScores, currentCommentIndex, nextCommentId, previousCommentId, loadScores, getUserById, detailSource, linkBackToList, currentUser, match: {params}, } = this.props; const { allScoresAboveThreshold, reducedScoresAboveThreshold, isKeyboardModalVisible, isConfirmationModalVisible, isScoresModalVisible, scoresSelectedByTag, thresholdByTag, confirmationAction, isInfoDropdownVisible, infoToolTipPosition, upArrowIsFocused, downArrowIsFocused, infoIconFocused, } = this.state; if (!comment) { return null; } const activeButtons = this.getActiveButtons(this.props.comment); const batchURL = newCommentsPageLink({ context: params.context, contextId: params.contextId, tag: NEW_COMMENTS_DEFAULT_TAG, }); return ( <div {...css({ height: '100%' })}> <div> { detailSource && (typeof currentCommentIndex === 'number') ? ( <Link to={linkBackToList} {...css(STYLES.subHeading)}> <ArrowIcon direction="left" {...css({fill: DARK_COLOR, margin: 'auto 0'})} size={24} /> <p {...css(STYLES.selectedInfo)}> {detailSource.replace('%i', (currentCommentIndex + 1).toString())} </p> </Link> ) : ( <Link to={batchURL} {...css(STYLES.subHeading)}> <ArrowIcon direction="left" {...css({fill: DARK_COLOR, margin: 'auto 0'})} size={24} /> <p {...css(STYLES.selectedInfo)}> {`Back to ${isArticleContext(params) ? 'article' : 'category'}`} </p> </Link> )} </div> <div {...css(STYLES.wrapper)}> <div {...css(STYLES.sidebar)}> <div {...css(STYLES.buttons)}> <ModerateButtons vertical activeButtons={activeButtons} onClick={this.moderateComment} requireReasonForReject={comment.isAccepted === false ? false : REQUIRE_REASON_TO_REJECT} comment={comment} handleAssignTagsSubmit={this.handleAssignTagsSubmit} /> </div> { (previousCommentId || nextCommentId) && ( <div {...css(STYLES.pagers)}> { previousCommentId ? ( <Link {...css(STYLES.paginationArrow)} to={this.generatePagingLink(previousCommentId)} onFocus={this.onFocusUpArrow} onBlur={this.onBlurUpArrow} onClick={partial(this.saveReturnRow, previousCommentId)} > <Arrow direction={'up'} label={'up arrow'} size={58} color={upArrowIsFocused ? NICE_MIDDLE_BLUE : DARK_TERTIARY_TEXT_COLOR} icon={<ArrowIcon {...css({ fill: upArrowIsFocused ? NICE_MIDDLE_BLUE : DARK_TERTIARY_TEXT_COLOR })} size={24} />} /> <span {...css(VISUALLY_HIDDEN)}>Previous Comment</span> </Link> ) : ( <Arrow isDisabled direction={'up'} label={'up arrow'} size={58} color={DARK_TERTIARY_TEXT_COLOR} icon={<ArrowIcon {...css({ fill: DARK_TERTIARY_TEXT_COLOR })} size={24} />} /> )} { nextCommentId ? ( <Link {...css(STYLES.paginationArrow)} to={this.generatePagingLink(nextCommentId)} onFocus={this.onFocusDownArrow} onBlur={this.onBlurDownArrow} onClick={partial(this.saveReturnRow, nextCommentId)} > <Arrow direction={'down'} label={'down arrow'} size={58} color={upArrowIsFocused ? NICE_MIDDLE_BLUE : DARK_TERTIARY_TEXT_COLOR} icon={<ArrowIcon {...css({ fill: downArrowIsFocused ? NICE_MIDDLE_BLUE : DARK_TERTIARY_TEXT_COLOR })} size={24} />} /> <span {...css(VISUALLY_HIDDEN)}>Next Comment</span> </Link> ) : ( <Arrow isDisabled direction={'down'} label={'down arrow'} size={58} color={DARK_TERTIARY_TEXT_COLOR} icon={<ArrowIcon {...css({fill: DARK_TERTIARY_TEXT_COLOR})} size={24} />} /> )} </div> )} </div> <div {...css(STYLES.commentWrapper)}> <div {...css(STYLES.comment)}> { comment.replyId && ( <ReplyLink parent={comment} commentId={comment.replyId}/> )} <SingleComment comment={comment} allScores={allScores} allScoresAboveThreshold={allScoresAboveThreshold} reducedScoresAboveThreshold={reducedScoresAboveThreshold} availableTags={availableTags} loadScores={loadScores} getUserById={getUserById} onScoreClick={this.handleScoreClick} onTagButtonClick={this.onTagButtonClick} onCommentTagClick={this.onCommentTagClick} onAnnotateTagButtonClick={this.onAnnotateTagButtonClick} currentUser={currentUser} commentEditingEnabled={COMMENTS_EDITABLE_FLAG} /> </div> </div> <Scrim key="keyboardScrim" scrimStyles={{...STYLES.scrim, ...SCRIM_STYLE.scrim}} isVisible={isKeyboardModalVisible} onBackgroundClick={this.onKeyboardClose} > <FocusTrap focusTrapOptions={{ clickOutsideDeactivates: true, }} > <div key="keyboardContainer" id={KEYBOARD_SHORTCUTS_POPUP_ID} {...css(STYLES.popup)}> {/* keyboard shortcuts */} <Shortcuts onClose={this.onKeyboardClose}/> </div> </FocusTrap> </Scrim> <Scrim key="confirmationScrim" scrimStyles={{...STYLES.scrim, ...SCRIM_STYLE.scrim}} isVisible={isConfirmationModalVisible} onBackgroundClick={this.closeToast} > <div id={CONFIRMATION_POPUP_ID} tabIndex={0} {...css(STYLES.confirmationPopup)}> {/* Confirmation popup */} <ConfirmationCircle backgroundColor={DARK_COLOR} action={confirmationAction} size={120} iconSize={40} /> </div> </Scrim> {/* ToolTip and Scrim */} <Scrim key="tooltipScrim" scrimStyles={STYLES.scrim1} isVisible={isInfoDropdownVisible} onBackgroundClick={this.onDropdownClose} id={INFO_DROPDOWN_ID} > <ToolTip hasDropShadow backgroundColor={WHITE_COLOR} arrowPosition="leftBottom" size={16} isVisible={isInfoDropdownVisible} position={infoToolTipPosition} zIndex={SCRIM_Z_INDEX} > <ul {...css(STYLES.infoList)}> <li> <button {...css(STYLES.infoTooltipButton)} onClick={this.onKeyboardOpen} > Keyboard Shortcuts </button> </li> {MODERATOR_GUIDELINES_URL && ( <li> <a {...css(STYLES.infoTooltipButton)} href={MODERATOR_GUIDELINES_URL} target="_blank" > Moderator Guidelines </a> </li> )} {SUBMIT_FEEDBACK_URL && ( <li> <a {...css(STYLES.infoTooltipButton)} href={SUBMIT_FEEDBACK_URL} target="_blank" > Submit Feedback </a> </li> )} </ul> </ToolTip> </Scrim> <button tabIndex={0} ref={this.saveButtonRef} {...css(STYLES.infoTrigger)} onClick={this.onDropdownOpen} onFocus={this.onFocusInfoIcon} onBlur={this.onBlurInfoIcon} > <InfoIcon {...css({fill: infoIconFocused ? NICE_MIDDLE_BLUE : DARK_SECONDARY_TEXT_COLOR})} /> <span {...css(VISUALLY_HIDDEN)}>Tag Information</span> </button> </div> <Scrim key="scoresScrim" scrimStyles={{...STYLES.scrim, ...SCRIM_STYLE.scrim}} isVisible={isScoresModalVisible} onBackgroundClick={this.onScoresModalClose} > <FocusTrap focusTrapOptions={{ clickOutsideDeactivates: true, }} > <div key="scoresContainer" id={SCORES_POPUP_ID} {...css( STYLES.popup, { width: `${COMMENT_WRAPPER_WIDTH}px` }, )} > {/* All scores popup */} <ScoresList comment={comment} scores={scoresSelectedByTag} threshold={thresholdByTag} onClose={this.onScoresModalClose} /> </div> </FocusTrap> </Scrim> </div> ); } generatePagingLink(commentId: string) { const pagingIdentifier: string = qs.parse(this.props.location.search).pagingIdentifier as string; const params = this.props.match.params; const urlParams = { context: params.context, contextId: params.contextId, commentId, }; const query = pagingIdentifier && {pagingIdentifier}; return commentDetailsPageLink(urlParams, query); } @autobind calculateInfoTrigger(ref: any) { if (!ref) { return; } const infoIconRect = ref.getBoundingClientRect(); this.setState({ infoToolTipPosition: { // get height of tooltip, use that to offset top: (infoIconRect.bottom - 24), left: infoIconRect.right, }, }); } @autobind onResize() { this.calculateInfoTrigger(this.buttonRef); } @autobind onKeyboardOpen() { this.setState({ isKeyboardModalVisible: true }); } @autobind onKeyboardClose() { this.setState({ isKeyboardModalVisible: false }); } @autobind onDropdownOpen() { this.setState({ isInfoDropdownVisible: true }); this.calculateInfoTrigger(this.buttonRef); } @autobind onDropdownClose() { this.setState({ isInfoDropdownVisible: false }); } @autobind onScoresModalClose() { this.setState({ isScoresModalVisible: false }); } @autobind attachEvents() { keyboardJS.bind(APPROVE_SHORTCUT, this.approveComment); keyboardJS.bind(REJECT_SHORTCUT, this.rejectComment); keyboardJS.bind(DEFER_SHORTCUT, this.deferComment); keyboardJS.bind(HIGHLIGHT_SHORTCUT, this.highlightComment); keyboardJS.bind(ESCAPE_SHORTCUT, this.onPressEscape); keyboardJS.bind(PREV_SHORTCUT, this.goToPrevComment); keyboardJS.bind(NEXT_SHORTCUT, this.goToNextComment); window.addEventListener('resize', this.onResize); } @autobind detachEvents() { keyboardJS.unbind(APPROVE_SHORTCUT, this.approveComment); keyboardJS.unbind(REJECT_SHORTCUT, this.rejectComment); keyboardJS.unbind(DEFER_SHORTCUT, this.deferComment); keyboardJS.unbind(HIGHLIGHT_SHORTCUT, this.highlightComment); keyboardJS.unbind(ESCAPE_SHORTCUT, this.onPressEscape); keyboardJS.unbind(PREV_SHORTCUT, this.goToPrevComment); keyboardJS.unbind(NEXT_SHORTCUT, this.goToNextComment); window.removeEventListener('resize', this.onResize); } @autobind onBackClick() { window.history.back(); } @autobind async moderateComment(action: IModerationAction) { const activeButtons = this.getActiveButtons(this.props.comment); const shouldResetAction = activeButtons.includes(action); const commentAction: IConfirmationAction = shouldResetAction ? 'reset' : action; this.setState({ isConfirmationModalVisible: true, confirmationAction: commentAction, }); await actionMap[commentAction]([this.props.comment.id]); await timeout(2000); if (this.props.loadScores) { await this.props.loadScores(this.props.comment.id); } this.closeToast(); // clear saved for batch view, since this one has now been moderated. clearReturnSavedCommentRow(); if (this.props.isFromBatch) { this.goToNextComment(); } } @autobind approveComment() { return this.moderateComment('approve'); } @autobind rejectComment() { return this.moderateComment('reject'); } @autobind deferComment() { return this.moderateComment('defer'); } @autobind highlightComment() { return this.moderateComment('highlight'); } @autobind goToPrevComment() { const { previousCommentId } = this.props; if (!previousCommentId) { return; } this.saveReturnRow(previousCommentId); this.props.history.push(this.generatePagingLink(previousCommentId)); } @autobind goToNextComment() { const { nextCommentId } = this.props; if (!nextCommentId) { return; } this.saveReturnRow(nextCommentId); this.props.history.push(this.generatePagingLink(nextCommentId)); } @autobind async onTagButtonClick(tagId: string) { await tagComment(this.props.comment.id, tagId); await this.props.loadScores(this.props.comment.id); this.closeToast(); } @autobind async onAnnotateTagButtonClick(tag: string, start: number, end: number): Promise<any> { await tagCommentWithAnnotation(this.props.comment.id, tag, start, end); await this.props.loadScores(this.props.comment.id); this.closeToast(); } @autobind async onCommentTagClick(commentScore: ICommentScoreModel) { await untagComment(this.props.comment.id, commentScore.id); this.closeToast(); } @autobind closeToast() { this.setState({isConfirmationModalVisible: false}); } getActiveButtons(comment: ICommentModel): List<IModerationAction> { if (!comment) { return null; } let activeButtons = List(); if (comment.isAccepted === true) { activeButtons = List(['approve']); } if (comment.isAccepted === false) { activeButtons = List(['reject']); } if (comment.isHighlighted) { activeButtons = activeButtons.push('highlight'); } if (comment.isDeferred) { activeButtons = List(['defer']); } return activeButtons as List<IModerationAction>; } @autobind handleScoreClick(scoreClicked: ICommentSummaryScoreModel) { const thresholdByTag = this.state.taggingSensitivitiesInCategory.find( (ts) => ts.tagId === scoreClicked.tagId || ts.categoryId === null); const scoresSelectedByTag = this.props.allScores.filter( (score) => score.tagId === scoreClicked.tagId, ).sort((a, b) => b.score - a.score); this.setState({ isScoresModalVisible: true, scoresSelectedByTag, thresholdByTag, }); } @autobind onPressEscape() { if (this.state.isKeyboardModalVisible) { this.onKeyboardClose(); } if (this.state.isInfoDropdownVisible) { this.onDropdownClose(); } if (this.state.isScoresModalVisible) { this.onScoresModalClose(); } } }
the_stack
import es from '../../db/elasticsearch'; import { publishMainStream, publishNotesStream } from '../stream'; import { deliver } from '../../queue'; import renderNote from '../../remote/activitypub/renderer/note'; import renderCreate from '../../remote/activitypub/renderer/create'; import renderAnnounce from '../../remote/activitypub/renderer/announce'; import { renderActivity } from '../../remote/activitypub/renderer'; import watch from './watch'; import { parse } from '../../mfm/parse'; import { resolveUser } from '../../remote/resolve-user'; import config from '../../config'; import { updateHashtag } from '../update-hashtag'; import { concat } from '../../prelude/array'; import insertNoteUnread from './unread'; import { registerOrFetchInstanceDoc } from '../register-or-fetch-instance-doc'; import extractMentions from '../../misc/extract-mentions'; import extractEmojis from '../../misc/extract-emojis'; import extractHashtags from '../../misc/extract-hashtags'; import { Note } from '../../models/entities/note'; import { Mutings, Users, NoteWatchings, Followings, Notes, Instances, UserProfiles } from '../../models'; import { DriveFile } from '../../models/entities/drive-file'; import { App } from '../../models/entities/app'; import { Not, getConnection } from 'typeorm'; import { User, ILocalUser, IRemoteUser } from '../../models/entities/user'; import { genId } from '../../misc/gen-id'; import { notesChart, perUserNotesChart, activeUsersChart, instanceChart } from '../chart'; import { Poll, IPoll } from '../../models/entities/poll'; import { createNotification } from '../create-notification'; import { isDuplicateKeyValueError } from '../../misc/is-duplicate-key-value-error'; import { ensure } from '../../prelude/ensure'; type NotificationType = 'reply' | 'renote' | 'quote' | 'mention'; class NotificationManager { private notifier: User; private note: Note; private queue: { target: ILocalUser['id']; reason: NotificationType; }[]; constructor(notifier: User, note: Note) { this.notifier = notifier; this.note = note; this.queue = []; } public push(notifiee: ILocalUser['id'], reason: NotificationType) { // 自分自身へは通知しない if (this.notifier.id === notifiee) return; const exist = this.queue.find(x => x.target === notifiee); if (exist) { // 「メンションされているかつ返信されている」場合は、メンションとしての通知ではなく返信としての通知にする if (reason != 'mention') { exist.reason = reason; } } else { this.queue.push({ reason: reason, target: notifiee }); } } public async deliver() { for (const x of this.queue) { // ミュート情報を取得 const mentioneeMutes = await Mutings.find({ muterId: x.target }); const mentioneesMutedUserIds = mentioneeMutes.map(m => m.muteeId); // 通知される側のユーザーが通知する側のユーザーをミュートしていない限りは通知する if (!mentioneesMutedUserIds.includes(this.notifier.id)) { createNotification(x.target, this.notifier.id, x.reason, { noteId: this.note.id }); } } } } type Option = { createdAt?: Date | null; name?: string | null; text?: string | null; reply?: Note | null; renote?: Note | null; files?: DriveFile[] | null; geo?: any | null; poll?: IPoll | null; viaMobile?: boolean | null; localOnly?: boolean | null; cw?: string | null; visibility?: string; visibleUsers?: User[] | null; apMentions?: User[] | null; apHashtags?: string[] | null; apEmojis?: string[] | null; questionUri?: string | null; uri?: string | null; app?: App | null; }; export default async (user: User, data: Option, silent = false) => new Promise<Note>(async (res, rej) => { if (data.createdAt == null) data.createdAt = new Date(); if (data.visibility == null) data.visibility = 'public'; if (data.viaMobile == null) data.viaMobile = false; if (data.localOnly == null) data.localOnly = false; // サイレンス if (user.isSilenced && data.visibility == 'public') { data.visibility = 'home'; } // Renote対象が「ホームまたは全体」以外の公開範囲ならreject if (data.renote && data.renote.visibility != 'public' && data.renote.visibility != 'home') { return rej('Renote target is not public or home'); } // Renote対象がpublicではないならhomeにする if (data.renote && data.renote.visibility != 'public' && data.visibility == 'public') { data.visibility = 'home'; } // 返信対象がpublicではないならhomeにする if (data.reply && data.reply.visibility != 'public' && data.visibility == 'public') { data.visibility = 'home'; } // ローカルのみをRenoteしたらローカルのみにする if (data.renote && data.renote.localOnly) { data.localOnly = true; } // ローカルのみにリプライしたらローカルのみにする if (data.reply && data.reply.localOnly) { data.localOnly = true; } if (data.text) { data.text = data.text.trim(); } let tags = data.apHashtags; let emojis = data.apEmojis; let mentionedUsers = data.apMentions; // Parse MFM if needed if (!tags || !emojis || !mentionedUsers) { const tokens = data.text ? parse(data.text)! : []; const cwTokens = data.cw ? parse(data.cw)! : []; const choiceTokens = data.poll && data.poll.choices ? concat(data.poll.choices.map(choice => parse(choice)!)) : []; const combinedTokens = tokens.concat(cwTokens).concat(choiceTokens); tags = data.apHashtags || extractHashtags(combinedTokens); emojis = data.apEmojis || extractEmojis(combinedTokens); mentionedUsers = data.apMentions || await extractMentionedUsers(user, combinedTokens); } tags = tags.filter(tag => tag.length <= 100); if (data.reply && (user.id !== data.reply.userId) && !mentionedUsers.some(u => u.id === data.reply!.userId)) { mentionedUsers.push(await Users.findOne(data.reply.userId).then(ensure)); } if (data.visibility == 'specified') { if (data.visibleUsers == null) throw new Error('invalid param'); for (const u of data.visibleUsers) { if (!mentionedUsers.some(x => x.id === u.id)) { mentionedUsers.push(u); } } if (data.reply && !data.visibleUsers.some(x => x.id === data.reply!.userId)) { data.visibleUsers.push(await Users.findOne(data.reply.userId).then(ensure)); } } const note = await insertNote(user, data, tags, emojis, mentionedUsers); res(note); // 統計を更新 notesChart.update(note, true); perUserNotesChart.update(user, note, true); // Register host if (Users.isRemoteUser(user)) { registerOrFetchInstanceDoc(user.host).then(i => { Instances.increment({ id: i.id }, 'notesCount', 1); instanceChart.updateNote(i.host, note, true); }); } // ハッシュタグ更新 for (const tag of tags) updateHashtag(user, tag); // Increment notes count (user) incNotesCountOfUser(user); if (data.reply) { saveReply(data.reply, note); } if (data.renote) { incRenoteCount(data.renote); } if (!silent) { // ローカルユーザーのチャートはタイムライン取得時に更新しているのでリモートユーザーの場合だけでよい if (Users.isRemoteUser(user)) activeUsersChart.update(user); // 未読通知を作成 if (data.visibility == 'specified') { if (data.visibleUsers == null) throw new Error('invalid param'); for (const u of data.visibleUsers) { insertNoteUnread(u, note, true); } } else { for (const u of mentionedUsers) { insertNoteUnread(u, note, false); } } // Pack the note const noteObj = await Notes.pack(note); if (user.notesCount === 0) { (noteObj as any).isFirstNote = true; } publishNotesStream(noteObj); const nm = new NotificationManager(user, note); const nmRelatedPromises = []; createMentionedEvents(mentionedUsers, note, nm); const noteActivity = await renderNoteOrRenoteActivity(data, note); if (Users.isLocalUser(user)) { deliverNoteToMentionedRemoteUsers(mentionedUsers, user, noteActivity); } const profile = await UserProfiles.findOne(user.id).then(ensure); // If has in reply to note if (data.reply) { // Fetch watchers nmRelatedPromises.push(notifyToWatchersOfReplyee(data.reply, user, nm)); // この投稿をWatchする if (Users.isLocalUser(user) && profile.autoWatch) { watch(user.id, data.reply); } // 通知 if (data.reply.userHost === null) { nm.push(data.reply.userId, 'reply'); publishMainStream(data.reply.userId, 'reply', noteObj); } } // If it is renote if (data.renote) { const type = data.text ? 'quote' : 'renote'; // Notify if (data.renote.userHost === null) { nm.push(data.renote.userId, type); } // Fetch watchers nmRelatedPromises.push(notifyToWatchersOfRenotee(data.renote, user, nm, type)); // この投稿をWatchする if (Users.isLocalUser(user) && profile.autoWatch) { watch(user.id, data.renote); } // Publish event if ((user.id !== data.renote.userId) && data.renote.userHost === null) { publishMainStream(data.renote.userId, 'renote', noteObj); } } publish(user, note, data.reply, data.renote, noteActivity); Promise.all(nmRelatedPromises).then(() => { nm.deliver(); }); } // Register to search database index(note); }); async function renderNoteOrRenoteActivity(data: Option, note: Note) { if (data.localOnly) return null; const content = data.renote && data.text == null && data.poll == null && (data.files == null || data.files.length == 0) ? renderAnnounce(data.renote.uri ? data.renote.uri : `${config.url}/notes/${data.renote.id}`, note) : renderCreate(await renderNote(note, false), note); return renderActivity(content); } function incRenoteCount(renote: Note) { Notes.increment({ id: renote.id }, 'renoteCount', 1); Notes.increment({ id: renote.id }, 'score', 1); } async function publish(user: User, note: Note, reply: Note | null | undefined, renote: Note | null | undefined, noteActivity: any) { if (Users.isLocalUser(user)) { // 投稿がリプライかつ投稿者がローカルユーザーかつリプライ先の投稿の投稿者がリモートユーザーなら配送 if (reply && reply.userHost !== null) { Users.findOne(reply.userId).then(ensure).then(u => { deliver(user, noteActivity, u.inbox); }); } // 投稿がRenoteかつ投稿者がローカルユーザーかつRenote元の投稿の投稿者がリモートユーザーなら配送 if (renote && renote.userHost !== null) { Users.findOne(renote.userId).then(ensure).then(u => { deliver(user, noteActivity, u.inbox); }); } } if (['public', 'home', 'followers'].includes(note.visibility)) { // フォロワーに配信 publishToFollowers(note, user, noteActivity); } } async function insertNote(user: User, data: Option, tags: string[], emojis: string[], mentionedUsers: User[]) { const insert = new Note({ id: genId(data.createdAt!), createdAt: data.createdAt!, fileIds: data.files ? data.files.map(file => file.id) : [], replyId: data.reply ? data.reply.id : null, renoteId: data.renote ? data.renote.id : null, name: data.name, text: data.text, hasPoll: data.poll != null, cw: data.cw == null ? null : data.cw, tags: tags.map(tag => tag.toLowerCase()), emojis, userId: user.id, viaMobile: data.viaMobile!, localOnly: data.localOnly!, geo: data.geo || null, appId: data.app ? data.app.id : null, visibility: data.visibility as any, visibleUserIds: data.visibility == 'specified' ? data.visibleUsers ? data.visibleUsers.map(u => u.id) : [] : [], attachedFileTypes: data.files ? data.files.map(file => file.type) : [], // 以下非正規化データ replyUserId: data.reply ? data.reply.userId : null, replyUserHost: data.reply ? data.reply.userHost : null, renoteUserId: data.renote ? data.renote.userId : null, renoteUserHost: data.renote ? data.renote.userHost : null, userHost: user.host, }); if (data.uri != null) insert.uri = data.uri; // Append mentions data if (mentionedUsers.length > 0) { insert.mentions = mentionedUsers.map(u => u.id); insert.mentionedRemoteUsers = JSON.stringify(mentionedUsers.filter(u => Users.isRemoteUser(u)).map(u => ({ uri: (u as IRemoteUser).uri, username: u.username, host: u.host }))); } // 投稿を作成 try { let note: Note; if (insert.hasPoll) { // Start transaction await getConnection().transaction(async transactionalEntityManager => { note = await transactionalEntityManager.save(insert); const poll = new Poll({ noteId: note.id, choices: data.poll!.choices, expiresAt: data.poll!.expiresAt, multiple: data.poll!.multiple, votes: new Array(data.poll!.choices.length).fill(0), noteVisibility: note.visibility, userId: user.id, userHost: user.host }); await transactionalEntityManager.save(poll); }); } else { note = await Notes.save(insert); } return note!; } catch (e) { // duplicate key error if (isDuplicateKeyValueError(e)) { const err = new Error('Duplicated note'); err.name = 'duplicated'; throw err; } console.error(e); throw new Error('something happened'); } } function index(note: Note) { if (note.text == null || config.elasticsearch == null) return; es!.index({ index: 'misskey_note', id: note.id.toString(), body: { text: note.text.toLowerCase(), userId: note.userId, userHost: note.userHost } }); } async function notifyToWatchersOfRenotee(renote: Note, user: User, nm: NotificationManager, type: NotificationType) { const watchers = await NoteWatchings.find({ noteId: renote.id, userId: Not(user.id) }); for (const watcher of watchers) { nm.push(watcher.userId, type); } } async function notifyToWatchersOfReplyee(reply: Note, user: User, nm: NotificationManager) { const watchers = await NoteWatchings.find({ noteId: reply.id, userId: Not(user.id) }); for (const watcher of watchers) { nm.push(watcher.userId, 'reply'); } } async function publishToFollowers(note: Note, user: User, noteActivity: any) { const followers = await Followings.find({ followeeId: note.userId }); const queue: string[] = []; for (const following of followers) { if (Followings.isRemoteFollower(following)) { // フォロワーがリモートユーザーかつ投稿者がローカルユーザーなら投稿を配信 if (Users.isLocalUser(user)) { const inbox = following.followerSharedInbox || following.followerInbox; if (!queue.includes(inbox)) queue.push(inbox); } } } for (const inbox of queue) { deliver(user as any, noteActivity, inbox); } } function deliverNoteToMentionedRemoteUsers(mentionedUsers: User[], user: ILocalUser, noteActivity: any) { for (const u of mentionedUsers.filter(u => Users.isRemoteUser(u))) { deliver(user, noteActivity, (u as IRemoteUser).inbox); } } async function createMentionedEvents(mentionedUsers: User[], note: Note, nm: NotificationManager) { for (const u of mentionedUsers.filter(u => Users.isLocalUser(u))) { const detailPackedNote = await Notes.pack(note, u, { detail: true }); publishMainStream(u.id, 'mention', detailPackedNote); // Create notification nm.push(u.id, 'mention'); } } function saveReply(reply: Note, note: Note) { Notes.increment({ id: reply.id }, 'repliesCount', 1); } function incNotesCountOfUser(user: User) { Users.increment({ id: user.id }, 'notesCount', 1); Users.update({ id: user.id }, { updatedAt: new Date() }); } async function extractMentionedUsers(user: User, tokens: ReturnType<typeof parse>): Promise<User[]> { if (tokens == null) return []; const mentions = extractMentions(tokens); let mentionedUsers = (await Promise.all(mentions.map(m => resolveUser(m.username, m.host || user.host).catch(() => null) ))).filter(x => x != null) as User[]; // Drop duplicate users mentionedUsers = mentionedUsers.filter((u, i, self) => i === self.findIndex(u2 => u.id === u2.id) ); return mentionedUsers; }
the_stack
import { computed, observable } from "../../node_modules/mobx/lib/mobx.module.js" import { ChronoGraph } from "../../src/chrono/Graph.js" import { CalculatedValueGen, CalculatedValueSync, Identifier } from "../../src/chrono/Identifier.js" import { Base } from "../../src/class/Base.js" import { AnyConstructor, ClassUnion, Mixin, MixinAny } from "../../src/class/Mixin.js" import { Entity, field } from "../../src/replica/Entity.js" import { Replica } from "../../src/replica/Replica.js" //--------------------------------------------------------------------------------------------------------------------- export type GraphGenerationResult = { graph : ChronoGraph, boxes : Identifier[], counter : number } //--------------------------------------------------------------------------------------------------------------------- export const deepGraphGen = (atomNum : number = 1000) : GraphGenerationResult => { const graph : ChronoGraph = ChronoGraph.new() let boxes = [] const res = { graph, boxes, counter : 0 } for (let i = 0; i < atomNum; i++) { if (i <= 3) { boxes.push(graph.variableNamed(i, 1)) } else if (i <= 10) { boxes.push(graph.identifierNamed(i, function* (YIELD) { res.counter++ const input : number[] = [ yield boxes[0], yield boxes[1], yield boxes[2], yield boxes[3] ] return input.reduce((sum, op) => sum + op, 0) }, i)) } else if (i % 2 == 0) { boxes.push(graph.identifierNamed(i, function* (YIELD) { res.counter++ const input : number[] = [ yield boxes[this - 1], yield boxes[this - 2], yield boxes[this - 3], yield boxes[this - 4] ] return input.reduce((sum, op) => (sum + op) % 10000, 0) }, i)) } else { boxes.push(graph.identifierNamed(i, function* (YIELD) { res.counter++ const input : number[] = [ yield boxes[this - 1], yield boxes[this - 2], yield boxes[this - 3], yield boxes[this - 4] ] return input.reduce((sum, op) => (sum - op) % 10000, 0) }, i)) } } return res } //--------------------------------------------------------------------------------------------------------------------- export const deepGraphGenShared = (atomNum : number = 1000) : GraphGenerationResult => { const graph : ChronoGraph = ChronoGraph.new() let boxes = [] const res = { graph, boxes, counter : 0 } class MyIden1 extends CalculatedValueGen { * calculation (YIELD) { res.counter++ const input : number[] = [ yield boxes[0], yield boxes[1], yield boxes[2], yield boxes[3] ] return input.reduce((sum, op) => sum + op, 0) } } class MyIden2 extends CalculatedValueGen { * calculation (this : number, YIELD) { res.counter++ const input : number[] = [ yield boxes[this - 1], yield boxes[this - 2], yield boxes[this - 3], yield boxes[this - 4] ] return input.reduce((sum, op) => (sum + op) % 10000, 0) } } class MyIden3 extends CalculatedValueGen { * calculation (this : number, YIELD) { res.counter++ const input : number[] = [ yield boxes[this - 1], yield boxes[this - 2], yield boxes[this - 3], yield boxes[this - 4] ] return input.reduce((sum, op) => (sum - op) % 10000, 0) } } for (let i = 0; i < atomNum; i++) { if (i <= 3) { boxes.push(graph.variableNamed(i, 1)) } else if (i <= 10) { const iden1 = MyIden1.new({ name : i, context : i }) graph.addIdentifier(iden1) boxes.push(iden1) } else if (i % 2 == 0) { const iden2 = MyIden2.new({ name : i, context : i }) graph.addIdentifier(iden2) boxes.push(iden2) } else { const iden3 = MyIden3.new({ name : i, context : i }) graph.addIdentifier(iden3) boxes.push(iden3) } } return res } //--------------------------------------------------------------------------------------------------------------------- export const deepGraphSync = (atomNum : number = 1000) : GraphGenerationResult => { const graph : ChronoGraph = ChronoGraph.new() let boxes = [] const res = { graph, boxes, counter : 0 } for (let i = 0; i < atomNum; i++) { if (i <= 3) { boxes.push(graph.variableNamed(i, 1)) } else if (i <= 10) { boxes.push(graph.addIdentifier(CalculatedValueSync.new({ calculation : function (YIELD) { res.counter++ const input : number[] = [ YIELD(boxes[0]), YIELD(boxes[1]), YIELD(boxes[2]), YIELD(boxes[3]) ] return input.reduce((sum, op) => sum + op, 0) }, context : i }))) } else if (i % 2 == 0) { boxes.push(graph.addIdentifier(CalculatedValueSync.new({ calculation : function (YIELD) { res.counter++ const input : number[] = [ YIELD(boxes[this - 1]), YIELD(boxes[this - 2]), YIELD(boxes[this - 3]), YIELD(boxes[this - 4]) ] return input.reduce((sum, op) => (sum + op) % 10000, 0) }, context : i }))) } else { boxes.push(graph.addIdentifier(CalculatedValueSync.new({ calculation : function (YIELD) { res.counter++ const input : number[] = [ YIELD(boxes[this - 1]), YIELD(boxes[this - 2]), YIELD(boxes[this - 3]), YIELD(boxes[this - 4]) ] return input.reduce((sum, op) => (sum - op) % 10000, 0) }, context : i }))) } } return res } //--------------------------------------------------------------------------------------------------------------------- export type MobxBox = { get : () => number, set : (v : number) => any } export type MobxGraphGenerationResult = { boxes : MobxBox[], counter : number } export const mobxGraph = (atomNum : number = 1000) : MobxGraphGenerationResult => { let boxes = [] const res = { boxes, counter : 0 } for (let i = 0; i < atomNum; i++) { if (i <= 3) { boxes.push(observable.box(1)) } else if (i <= 10) { boxes.push(computed(function () { res.counter++ const input = [ boxes[0].get(), boxes[1].get(), boxes[2].get(), boxes[3].get(), ] return input.reduce((sum, op) => sum + op, 0) }, { keepAlive : true, context : i })) } else if (i % 2 == 0) { boxes.push(computed(function () { res.counter++ const input = [ boxes[this - 1].get(), boxes[this - 2].get(), boxes[this - 3].get(), boxes[this - 4].get(), ] return input.reduce((sum, op) => (sum + op) % 10000, 0) }, { keepAlive : true, context : i })) } else { boxes.push(computed(function () { res.counter++ const input = [ boxes[this - 1].get(), boxes[this - 2].get(), boxes[this - 3].get(), boxes[this - 4].get(), ] return input.reduce((sum, op) => (sum - op) % 10000, 0) }, { keepAlive : true, context : i })) } } return res } //--------------------------------------------------------------------------------------------------------------------- export type ReplicaGenerationResult = { replica : Replica, entities : Entity[] } //--------------------------------------------------------------------------------------------------------------------- export class Mixin1 extends Mixin( [ Entity ], (base : AnyConstructor<Entity, typeof Entity>) => { class Mixin1 extends base { @field() field11 : string = 'string' @field() field12 : number = 0 @field() field13 : boolean = false @field() field14 : any[] = [] @field() field15 : object = {} } return Mixin1 }){} //--------------------------------------------------------------------------------------------------------------------- export class Mixin2 extends Mixin( [ Entity ], (base : AnyConstructor<Entity, typeof Entity>) => { class Mixin2 extends base { @field() field21 : string = 'string' @field() field22 : number = 0 @field() field23 : boolean = false @field() field24 : any[] = [] @field() field25 : object = {} } return Mixin2 }){} //--------------------------------------------------------------------------------------------------------------------- export class Mixin3 extends Mixin( [ Entity ], (base : AnyConstructor<Entity, typeof Entity>) => { class Mixin3 extends base { @field() field31 : string = 'string' @field() field32 : number = 0 @field() field33 : boolean = false @field() field34 : any[] = [] @field() field35 : object = {} } return Mixin3 }){} //--------------------------------------------------------------------------------------------------------------------- export class Mixin4 extends Mixin( [ Entity ], (base : AnyConstructor<Entity, typeof Entity>) => { class Mixin4 extends base { @field() field41 : string = 'string' @field() field42 : number = 0 @field() field43 : boolean = false @field() field44 : any[] = [] @field() field45 : object = {} } return Mixin4 }){} //--------------------------------------------------------------------------------------------------------------------- export class Mixin5 extends Mixin( [ Entity ], (base : ClassUnion<typeof Entity>) => { class Mixin5 extends base { @field() field51 : string = 'string' @field() field52 : number = 0 @field() field53 : boolean = false @field() field54 : any[] = [] @field() field55 : object = {} } return Mixin5 }){} class TestEntity5 extends MixinAny( [ Mixin5, Mixin4, Mixin3, Mixin2, Mixin1, Entity, Base ], (base : AnyConstructor<Mixin5 & Mixin4 & Mixin3 & Mixin2 & Mixin1 & Entity & Base, typeof Mixin5 & typeof Mixin4 & typeof Mixin3 & typeof Mixin2 & typeof Mixin1 & typeof Entity & typeof Base>) => base ){} class TestEntity1 extends Mixin( [ Mixin1, Entity, Base ], (base : AnyConstructor<Mixin1 & Entity & Base, typeof Mixin1 & typeof Entity & typeof Base>) => base ) {} //--------------------------------------------------------------------------------------------------------------------- export const replicaGen = (entitiesNum : number = 1000) : ReplicaGenerationResult => { const replica : Replica = Replica.new() let entities : Entity[] = [] const res = { replica, entities } for (let i = 0; i < entitiesNum; i++) { const instance = TestEntity5.new() entities.push(instance) replica.addEntity(instance) } // console.profile('adding') // // // const map = new Map() // // for (let i = 0; i < entitiesNum; i++) { // const instance = entities[ i ] // // replica.addEntity(instance) // // // instance.$entity.forEachField((field, name) => { // // map.set(instance.$[ name ], instance) // // }) // } // // // console.log("Map size: ", map.size) // // // // // console.log("Entries size: ", replica.activeTransaction.entries.size) // // console.profileEnd('adding') return res } //--------------------------------------------------------------------------------------------------------------------- // in this graph the first 4 identifiers are static variables and all others are the sum of them // changing the box[ 0 ] will trigger recalculation of all boxes > 3 // but the quarks for boxes 1, 2, 3 will be shadowing // repeating the set for box 0 will produce a lot of shadowing quarks (but should not leak memory anyway) export const mostlyShadowingGraph = (atomNum : number = 1000) : GraphGenerationResult => { const graph : ChronoGraph = ChronoGraph.new() const boxes : Identifier[] = [] const res : GraphGenerationResult = { graph, boxes, counter : 0 } const staticIdentsCount = 4 class MyIden1 extends CalculatedValueGen { * calculation (YIELD) { let sum = 0 for (let i = 0; i < staticIdentsCount; i++) sum += yield boxes[ i ] return sum } } for (let i = 0; i < atomNum; i++) { if (i < staticIdentsCount) { boxes.push(graph.variableNamed(i, 1)) } else { const iden = MyIden1.new({ name : i, context : i }) boxes.push(graph.addIdentifier(iden)) } } return res }
the_stack
import { CameraRecordingConfiguration, H264Level, H264Profile } from "homebridge"; import { ProtectCamera, RtspEntry } from "./protect-camera"; import { FfmpegProcess } from "./protect-ffmpeg"; import { ProtectCameraConfig } from "unifi-protect"; import events from "events"; // FFmpeg HomeKit Streaming Video recording process management. export class FfmpegRecordingProcess extends FfmpegProcess { private recordingBuffer: { data: Buffer, header: Buffer, length: number, type: string }[]; // Create a new FFmpeg process instance. constructor(protectCamera: ProtectCamera, recordingConfig: CameraRecordingConfiguration, rtspEntry: RtspEntry, isAudioActive: boolean) { // Initialize our parent. super(protectCamera); // Initialize our recording buffer. this.recordingBuffer = []; // Determine which H.264 profile HomeKit is expecting from us. const requestedProfile = (recordingConfig.videoCodec.parameters.profile === H264Profile.HIGH) ? "high" : (recordingConfig.videoCodec.parameters.profile === H264Profile.MAIN) ? "main" : "baseline"; const requestedLevel = (recordingConfig.videoCodec.parameters.level === H264Level.LEVEL4_0) ? "4.0" : (recordingConfig.videoCodec.parameters.level === H264Level.LEVEL3_2) ? "3.2" : "3.1"; // -hide_banner: Suppress printing the startup banner in FFmpeg. this.commandLineArgs = [ "-hide_banner" ]; if(this.nvr?.optionEnabled(protectCamera.accessory.context.device as ProtectCameraConfig, "Video.HKSV.TimeshiftBuffer")) { // Configure our video parameters for our input: // // -fflags flags Set the format flags to discard any corrupt packets rather than exit, and ensure that packets are written out immediately. // -r fps Set the input frame rate for the video stream. // -f mp4 Tell ffmpeg that it should expect an MP4-encoded input stream. // -i pipe:0 Use standard input to get video data. this.commandLineArgs.push( "-fflags", "+discardcorrupt", "-r", rtspEntry.channel.fps.toString(), "-f", "mp4", "-i", "pipe:0" ); } else { // We're not using the timeshift buffer, so let's use the RTSP stream as the input to HKSV. // // -hide_banner Suppress printing the startup banner in FFmpeg. // -probesize 16384 How many bytes should be analyzed for stream information. We default to to analyze time should be spent analyzing // the input stream, in microseconds. We default to 1536. // -max_delay 500000 Set an upper limit on how much time FFmpeg can take in demuxing packets. // -r fps Set the input frame rate for the video stream. // -rtsp_transport tcp Tell the RTSP stream handler that we're looking for a TCP connection. // -i this.rtspEntry.url RTSPS URL to get our input stream from. this.commandLineArgs.push( "-probesize", "16384", "-max_delay", "500000", "-r", rtspEntry.channel.fps.toString(), "-rtsp_transport", "tcp", "-i", rtspEntry.url ); } // -map 0:v:0 Selects the first available video track from the stream. Protect actually maps audio // and video tracks in opposite locations from where FFmpeg typically expects them. This // setting is a more general solution than naming the track locations directly in case // Protect changes this in the future. // Yes, we included these above as well: they need to be included for every I/O stream to // maximize effectiveness it seems. // -max_muxing_queue_size 9999 Workaround for a bug in pre-20221 versions of FFmpeg. This will ensure that FFmpeg maintains a // a large enough queue to wait for an output packet to be available. Inputs aren't the issue in our // situation. // -vcodec libx264 Copy the stream withour reencoding it. // -pix_fmt yuvj420p Use the yuvj420p pixel format, which is what Protect uses. // -profile:v level Use the H.264 profile HKSV is requesting when encoding. // -level:v level Use the H.264 profile level HKSV is requesting when encoding. // -preset veryfast Use the veryfast encoding preset in libx264, which provides a good balance of encoding // speed and quality. // -b:v bitrate The average bitrate to use for this stream as requested by HKSV. // -bufsize size This is the decoder buffer size, which drives the variability / quality of the output bitrate. // -maxrate bitrate The maximum bitrate tolerance, used with -bufsize. We set this to max_bit_rate to effectively // create a constant bitrate. // -force_key_frames condition Inject an I-frame at the interval that HKSV requests. This is calculated using a conditional expression. // -fflags flags Set format flags to generate a presentation timestamp if it's missing and discard any corrupt packets rather than exit. // -reset_timestamps Reset timestamps at the beginning of each segment. // -movflags flags In the generated fMP4 stream: start a new fragment at each keyframe, write a blank MOOV box, and // avoid writing absolute offsets this.commandLineArgs.push( "-map", "0:v:0", "-max_muxing_queue_size", "9999", "-vcodec", this.protectCamera.stream.videoEncoder || "libx264", "-pix_fmt", "yuvj420p", "-profile:v", requestedProfile, "-level:v", requestedLevel, "-preset", "veryfast", "-b:v", recordingConfig.videoCodec.parameters.bitRate.toString() + "k", "-bufsize", (2 * recordingConfig.videoCodec.parameters.bitRate).toString() + "k", "-maxrate", recordingConfig.videoCodec.parameters.bitRate.toString() + "k", "-force_key_frames", "expr:gte(t, n_forced * " + (recordingConfig.videoCodec.parameters.iFrameInterval / 1000).toString() + ")", "-fflags", "+genpts+discardcorrupt", "-reset_timestamps", "1", "-movflags", "frag_keyframe+empty_moov+default_base_moof" ); if(isAudioActive) { // Configure the audio portion of the command line. Options we use are: // // -map 0:a:0 Selects the first available audio track from the stream. Protect actually maps audio // and video tracks in opposite locations from where FFmpeg typically expects them. This // setting is a more general solution than naming the track locations directly in case // Protect changes this in the future. // -acodec copy Copy the stream withour reencoding it. this.commandLineArgs.push( "-map", "0:a:0", "-acodec", "copy" ); } // Configure our video parameters for outputting our final stream: // // -f mp4 Tell ffmpeg that it should create an MP4-encoded output stream. // pipe:1 Output the stream to standard output. this.commandLineArgs.push("-f", "mp4", "pipe:1"); // Additional logging, but only if we're debugging. if(protectCamera.platform.verboseFfmpeg) { this.commandLineArgs.unshift("-loglevel", "level+verbose"); } // Start the FFmpeg session. this.start(); } // Prepare and start our FFmpeg process. protected configureProcess(): void { let dataListener: (buffer: Buffer) => void; // Call our parent to get started. super.configureProcess(); // Initialize our variables that we need to process incoming FFmpeg packets. let header = Buffer.alloc(0); let bufferRemaining = Buffer.alloc(0); let dataLength = 0; let type = ""; // Process FFmpeg output and parse out the fMP4 stream it's generating for HomeKit Secure Video. this.process?.stdout?.on("data", dataListener = (buffer: Buffer): void => { // If we have anything left from the last buffer we processed, prepend it to this buffer. if(bufferRemaining.length > 0) { buffer = Buffer.concat([bufferRemaining, buffer]); bufferRemaining = Buffer.alloc(0); } let offset = 0; // FFmpeg is outputting an fMP4 stream that's suitable for HomeKit Secure Video. However, we can't just // pass this stream directly back to HomeKit since we're using a generator-based API to send packets back to // HKSV. Here, we take on the task of parsing the fMP4 stream that's being generated and split it up into the // MP4 boxes that HAP-NodeJS is ultimately expecting. for(;;) { let data; // The MP4 container format is well-documented and designed around the concept of boxes. A box (or atom as they // used to be called), is at the center of an MP4 container. It's composed of an 8-byte header, followed by the data payload // it carries. // No existing header, let's start a new box. if(!header.length) { // Grab the header. The first four bytes represents the length of the entire box. Second four bytes represent the box type. header = buffer.slice(0, 8); // Now we retrieve the length of the box and subtract the length of the header to get the length of the data portion of the box. dataLength = header.readUInt32BE(0) - 8; // Get the type of the box. This is always a string and has a funky history to it that makes for an interesting read! type = header.slice(4).toString(); // Finally, we get the data portion of the box. data = buffer.slice(8, dataLength + 8); offset = 8; } else { // Grab the data from our buffer. data = buffer.slice(0, dataLength); offset = 0; } // If we don't have enough data in this buffer, save what we have for the next buffer we see and append it there. if(data.length < (dataLength - offset)) { bufferRemaining = data; break; } // Add it to our queue to be eventually pushed out through our generator function. this.recordingBuffer.push({ data: data, header: header, length: dataLength, type: type }); this.emit("mp4box"); // Prepare to start a new box for the next buffer that we will be processing. data = Buffer.alloc(0); header = Buffer.alloc(0); type = ""; // We've parsed an entire box, and there's no more data in this buffer to parse. if(buffer.length === (offset + dataLength)) { dataLength = 0; break; } // If there's anything left in the buffer, move us to the new box and let's keep iterating. buffer = buffer.slice(offset + dataLength); dataLength = 0; } }); // Make sure we cleanup our listeners when we're done. this.process?.once("exit", () => { this.process?.stdout?.removeListener("data", dataListener); }); } // Stop our FFmpeg process and cleanup after ourselves. protected stopProcess(): void { // Call our parent to get started. super.stopProcess(); // Ensure that we clear out of our segment generator by guaranteeing an exit path. this.isEnded = true; this.emit("ffmpegStarted"); this.emit("mp4box"); } // Generate complete segments from an FFmpeg output stream that HomeKit Secure Video can process. public async *segmentGenerator(): AsyncGenerator<Buffer> { let segment: Buffer[] = []; // Loop forever, generating either FTYP/MOOV box pairs or MOOF/MDAT box pairs for HomeKit Secure Video. for(;;) { // FFmpeg has finished it's output - we're done. if(this.isEnded) { return; } // If the buffer is empty, wait for our FFmpeg process to produce more boxes. if(!this.recordingBuffer.length) { // eslint-disable-next-line no-await-in-loop await events.once(this, "mp4box"); } // Grab the next fMP4 box from our buffer. const box = this.recordingBuffer.shift(); // No fMP4 box, let's keep trying. if(!box) { continue; } // Queue up this fMP4 box to send back to HomeKit. segment.push(box.header, box.data); // What we want to send are two types of complete segments, made up of multiple MP4 boxes: // // - a complete MOOV box, usually with an accompanying FTYP box, that's sent at the very // beginning of any valid fMP4 stream. HomeKit Secure Video looks for this before anything // else. // // - a complete MOOF/MDAT pair. MOOF describes XXX and MDAT describes the actual audio and video // data related to that segment. // // Once we see these, we combine all the segments in our queue to send back to HomeKit. if((box.type === "moov") || (box.type === "mdat")) { yield Buffer.concat(segment); segment = []; } } } }
the_stack
import * as fs from 'fs'; import * as path from 'path'; import * as Doppio from '../doppiojvm'; import JVMThread = Doppio.VM.Threading.JVMThread; import ReferenceClassData = Doppio.VM.ClassFile.ReferenceClassData; import logging = Doppio.Debug.Logging; import util = Doppio.VM.Util; import ThreadStatus = Doppio.VM.Enums.ThreadStatus; import Long = Doppio.VM.Long; import assert = Doppio.Debug.Assert; import * as JVMTypes from '../../includes/JVMTypes'; import FDState = Doppio.VM.FDState; import {setImmediate} from 'browserfs'; function throwNodeError(thread: JVMThread, err: NodeJS.ErrnoException): void { let type = "Ljava/io/IOException;"; if (err.code === "ENOENT") { type = 'Ljava/io/FileNotFoundException;'; } thread.throwNewException(type, err.message); } export default function (): any { /** * Provide buffering for the underlying input function, returning at most * n_bytes of data. */ function async_input(n_bytes: number, resume: (data: Buffer) => void): void { // Try to read n_bytes from stdin's buffer. var read = function (nBytes: number): NodeBuffer { // XXX: Returns a Buffer, but DefinitelyTyped says string|Buffer. var bytes = <Buffer> process.stdin.read(nBytes); if (bytes === null) { // We might have asked for too many bytes. Retrieve the entire stream // buffer. bytes = <Buffer> process.stdin.read(); } // \0 => EOF. if (bytes !== null && bytes.length === 1 && bytes[0] === 0) { bytes = new Buffer(0); } return bytes; }, bytes: NodeBuffer = read(n_bytes); if (bytes === null) { // No input available. Wait for further input. process.stdin.once('readable', function (data: NodeBuffer) { var bytes = read(n_bytes); if (bytes === null) { bytes = new Buffer(0); } resume(bytes); }); } else { // Reset stack depth and resume with the given data. setImmediate(function () { resume(bytes); }); } } function statFile(fname: string, cb: (stat: fs.Stats) => void): void { fs.stat(fname, (err, stat) => { if (err != null) { cb(null); } else { cb(stat); } }); } class java_io_Console { public static 'encoding()Ljava/lang/String;'(thread: JVMThread): JVMTypes.java_lang_String { return null; } public static 'echo(Z)Z'(thread: JVMThread, echoOn: boolean): boolean { var echoOff: boolean = !echoOn; (<any> process.stdin).setRawMode(echoOff); return echoOff; } public static 'istty()Z'(thread: JVMThread): boolean { return (<any> process.stdout).isTTY; } } class java_io_FileDescriptor { public static 'sync()V'(thread: JVMThread, javaThis: JVMTypes.java_io_FileDescriptor): void { thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.'); } public static 'initIDs()V'(thread: JVMThread): void { thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.'); } } class java_io_FileInputStream { public static 'open0(Ljava/lang/String;)V'(thread: JVMThread, javaThis: JVMTypes.java_io_FileInputStream, filename: JVMTypes.java_lang_String): void { var filepath = filename.toString(); // TODO: actually look at the mode thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.open(filepath, 'r', function (e, fd) { if (e != null) { if (e.code === 'ENOENT') { thread.throwNewException('Ljava/io/FileNotFoundException;', "" + filepath + " (No such file or directory)"); } else { thread.throwNewException('Ljava/lang/InternalError', 'Internal JVM error: ' + e); } } else { var fdObj = javaThis['java/io/FileInputStream/fd']; fdObj['java/io/FileDescriptor/fd'] = fd; FDState.open(fd, 0); thread.asyncReturn(); } }); } public static 'read0()I'(thread: JVMThread, javaThis: JVMTypes.java_io_FileInputStream): void { var fdObj = javaThis["java/io/FileInputStream/fd"], fd = fdObj["java/io/FileDescriptor/fd"]; if (-1 === fd) { thread.throwNewException("Ljava/io/IOException;", "Bad file descriptor"); } else if (0 !== fd) { // this is a real file that we've already opened thread.setStatus(ThreadStatus.ASYNC_WAITING); var buf = new Buffer(1); fs.read(fd, buf, 0, 1, FDState.getPos(fd), (err, bytes_read) => { if (err) { return throwNodeError(thread, err); } FDState.incrementPos(fd, 1); thread.asyncReturn(0 === bytes_read ? -1 : buf[0]); }); } else { // reading from System.in, do it async thread.setStatus(ThreadStatus.ASYNC_WAITING); async_input(1, (byte: NodeBuffer) => { thread.asyncReturn(0 === byte.length ? -1 : byte[0]); }); } } public static 'readBytes([BII)I'(thread: JVMThread, javaThis: JVMTypes.java_io_FileInputStream, byteArr: JVMTypes.JVMArray<number>, offset: number, nBytes: number): number { var buf: Buffer, pos: number, fdObj = javaThis["java/io/FileInputStream/fd"], fd = fdObj["java/io/FileDescriptor/fd"]; if (offset + nBytes > byteArr.array.length) { thread.throwNewException('Ljava/lang/IndexOutOfBoundsException;', ""); return; } if (nBytes === 0) { return 0; } else if (-1 === fd) { thread.throwNewException("Ljava/io/IOException;", "Bad file descriptor"); } else if (0 !== fd) { // this is a real file that we've already opened pos = FDState.getPos(fd) buf = new Buffer(nBytes); thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.read(fd, buf, 0, nBytes, pos, (err, bytesRead) => { if (null != err) { throwNodeError(thread, err); } else { // not clear why, but sometimes node doesn't move the // file pointer, so we do it here ourselves. FDState.incrementPos(fd, bytesRead); for (let i = 0; i < bytesRead; i++) { byteArr.array[offset + i] = buf.readInt8(i); } thread.asyncReturn(0 === bytesRead ? -1 : bytesRead); } }); } else { // reading from System.in, do it async thread.setStatus(ThreadStatus.ASYNC_WAITING); async_input(nBytes, (bytes: NodeBuffer) => { var b: number, idx: number; for (idx = 0; idx < bytes.length; idx++) { b = bytes.readInt8(idx); byteArr.array[offset + idx] = b; } thread.asyncReturn(bytes.length === 0 ? -1 : bytes.length); }); } } public static 'skip(J)J'(thread: JVMThread, javaThis: JVMTypes.java_io_FileInputStream, nBytes: Long): void { var fdObj = javaThis["java/io/FileInputStream/fd"]; var fd = fdObj["java/io/FileDescriptor/fd"]; if (-1 === fd) { thread.throwNewException("Ljava/io/IOException;", "Bad file descriptor"); } else if (0 !== fd) { thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.fstat(fd, (err, stats) => { if (err) { return throwNodeError(thread, err); } var bytesLeft = stats.size - FDState.getPos(fd), toSkip = Math.min(nBytes.toNumber(), bytesLeft); FDState.incrementPos(fd, toSkip); thread.asyncReturn(Long.fromNumber(toSkip), null); }); } else { // reading from System.in, do it async thread.setStatus(ThreadStatus.ASYNC_WAITING); async_input(nBytes.toNumber(), (bytes) => { // we don't care about what the input actually was thread.asyncReturn(Long.fromNumber(bytes.length), null); }); } } public static 'available()I'(thread: JVMThread, javaThis: JVMTypes.java_io_FileInputStream): number { var fdObj = javaThis["java/io/FileInputStream/fd"], fd = fdObj["java/io/FileDescriptor/fd"]; if (fd === -1) { thread.throwNewException("Ljava/io/IOException;", "Bad file descriptor"); } else if (fd === 0) { // no buffering for stdin (if fd is 0) return 0; } else { thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.fstat(fd, (err, stats) => { if (err) { return throwNodeError(thread, err); } thread.asyncReturn(stats.size - FDState.getPos(fd)); }); } } public static 'initIDs()V'(thread: JVMThread): void { thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.'); } public static 'close0()V'(thread: JVMThread, javaThis: JVMTypes.java_io_FileInputStream): void { var fdObj = javaThis['java/io/FileInputStream/fd'], fd = fdObj['java/io/FileDescriptor/fd']; thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.close(fd, (err?: NodeJS.ErrnoException) => { if (err) { throwNodeError(thread, err); } else { fdObj['java/io/FileDescriptor/fd'] = -1; FDState.close(fd); thread.asyncReturn(); } }); } } class java_io_FileOutputStream { /** * Opens a file, with the specified name, for overwriting or appending. * @param name name of file to be opened * @param append whether the file is to be opened in append mode */ public static 'open0(Ljava/lang/String;Z)V'(thread: JVMThread, javaThis: JVMTypes.java_io_FileOutputStream, name: JVMTypes.java_lang_String, append: number): void { thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.open(name.toString(), append ? 'a' : 'w', (err, fd) => { if (err) { return throwNodeError(thread, err); } var fdObj = javaThis['java/io/FileOutputStream/fd']; fdObj['java/io/FileDescriptor/fd'] = fd; fs.fstat(fd, (err, stats) => { FDState.setPos(fd, stats.size); thread.asyncReturn(); }); }); } /** * Writes the specified byte to this file output stream. * * @param b the byte to be written. * @param append {@code true} if the write operation first * advances the position to the end of file */ public static 'write(IZ)V'(thread: JVMThread, javaThis: JVMTypes.java_io_FileOutputStream, b: number, append: number): void { // HACK: Avoid reimplementing below for single byte case. java_io_FileOutputStream['writeBytes([BIIZ)V'](thread, javaThis, <any> {array: [b]}, 0, 1, append); } /** * Writes a sub array as a sequence of bytes. * @param b the data to be written * @param off the start offset in the data * @param len the number of bytes that are written * @param append {@code true} to first advance the position to the * end of file * @exception IOException If an I/O error has occurred. */ public static 'writeBytes([BIIZ)V'(thread: JVMThread, javaThis: JVMTypes.java_io_FileOutputStream, bytes: JVMTypes.JVMArray<number>, offset: number, len: number, append: number): void { var buf: Buffer = new Buffer(bytes.array), fdObj = javaThis['java/io/FileOutputStream/fd'], fd = fdObj['java/io/FileDescriptor/fd']; if (fd === -1) { thread.throwNewException('Ljava/io/IOException;', "Bad file descriptor"); } else if (fd !== 1 && fd !== 2) { // normal file thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.write(fd, buf, offset, len, FDState.getPos(fd), (err, numBytes) => { if (err) { return throwNodeError(thread, err); } FDState.incrementPos(fd, numBytes); thread.asyncReturn(); }); } else { // The string is in UTF-8 format. But now we need to convert them to UTF-16 to print 'em out. :( var output: string = buf.toString("utf8", offset, offset + len); if (fd === 1) { process.stdout.write(output); } else if (fd === 2) { process.stderr.write(output); } // For the browser implementation -- the DOM doesn't get repainted // unless we give the event loop a chance to spin. thread.setStatus(ThreadStatus.ASYNC_WAITING); setImmediate(() => { thread.asyncReturn(); }); } } public static 'close0()V'(thread: JVMThread, javaThis: JVMTypes.java_io_FileOutputStream): void { var fdObj = javaThis['java/io/FileOutputStream/fd'], fd = fdObj['java/io/FileDescriptor/fd']; thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.close(fd, (err?: NodeJS.ErrnoException) => { if (err) { return throwNodeError(thread, err); } else { fdObj['java/io/FileDescriptor/fd'] = -1; FDState.close(fd); thread.asyncReturn(); } }); } public static 'initIDs()V'(thread: JVMThread): void { thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.'); } } class java_io_ObjectInputStream { public static 'bytesToFloats([BI[FII)V'(thread: JVMThread, arg0: JVMTypes.JVMArray<number>, arg1: number, arg2: JVMTypes.JVMArray<number>, arg3: number, arg4: number): void { thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.'); } public static 'bytesToDoubles([BI[DII)V'(thread: JVMThread, arg0: JVMTypes.JVMArray<number>, arg1: number, arg2: JVMTypes.JVMArray<number>, arg3: number, arg4: number): void { thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.'); } } class java_io_ObjectOutputStream { public static 'floatsToBytes([FI[BII)V'(thread: JVMThread, arg0: JVMTypes.JVMArray<number>, arg1: number, arg2: JVMTypes.JVMArray<number>, arg3: number, arg4: number): void { thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.'); } public static 'doublesToBytes([DI[BII)V'(thread: JVMThread, arg0: JVMTypes.JVMArray<number>, arg1: number, arg2: JVMTypes.JVMArray<number>, arg3: number, arg4: number): void { thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.'); } } class java_io_ObjectStreamClass { public static 'initNative()V'(thread: JVMThread): void { // NOP } public static 'hasStaticInitializer(Ljava/lang/Class;)Z'(thread: JVMThread, jco: JVMTypes.java_lang_Class): boolean { // check if cls has a <clinit> method return jco.$cls.getMethod('<clinit>()V') !== null; } } class java_io_RandomAccessFile { public static 'open0(Ljava/lang/String;I)V'(thread: JVMThread, javaThis: JVMTypes.java_io_RandomAccessFile, filename: JVMTypes.java_lang_String, mode: number): void { var filepath = filename.toString(), rafStatics = <typeof JVMTypes.java_io_RandomAccessFile> (<ReferenceClassData<JVMTypes.java_io_RandomAccessFile>> javaThis.getClass()).getConstructor(thread), modeStr: string; switch (mode) { case rafStatics["java/io/RandomAccessFile/O_RDONLY"]: modeStr = 'r'; break; case rafStatics["java/io/RandomAccessFile/O_RDWR"]: modeStr = 'r+'; break; case rafStatics["java/io/RandomAccessFile/O_SYNC"]: case rafStatics["java/io/RandomAccessFile/O_DSYNC"]: modeStr = 'rs+'; break; } thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.open(filepath, modeStr, (e, fd) => { if (e) { return throwNodeError(thread, e); } else { var fdObj = javaThis['java/io/RandomAccessFile/fd']; fdObj['java/io/FileDescriptor/fd'] = fd; FDState.open(fd, 0); thread.asyncReturn(); } }); } /** * Reads a byte of data from this file. The byte is returned as an * integer in the range 0 to 255 ({@code 0x00-0x0ff}). This * method blocks if no input is yet available. * <p> * Although {@code RandomAccessFile} is not a subclass of * {@code InputStream}, this method behaves in exactly the same * way as the {@link InputStream#read()} method of * {@code InputStream}. * * @return the next byte of data, or {@code -1} if the end of the * file has been reached. * @exception IOException if an I/O error occurs. Not thrown if * end-of-file has been reached. */ public static 'read0()I'(thread: JVMThread, javaThis: JVMTypes.java_io_RandomAccessFile): void { var fdObj = javaThis["java/io/RandomAccessFile/fd"], fd = fdObj["java/io/FileDescriptor/fd"], buf = new Buffer(1); thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.read(fd, buf, 0, 1, FDState.getPos(fd), function (err, bytesRead) { if (err) { return throwNodeError(thread, err); } else { FDState.incrementPos(fd, bytesRead); // Read as uint, since return value is unsigned. thread.asyncReturn(bytesRead === 0 ? -1 : buf[0]); } }); } public static 'readBytes([BII)I'(thread: JVMThread, javaThis: JVMTypes.java_io_RandomAccessFile, byte_arr: JVMTypes.JVMArray<number>, offset: number, len: number): void { var fdObj = javaThis["java/io/RandomAccessFile/fd"], fd = fdObj["java/io/FileDescriptor/fd"], buf = new Buffer(len); thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.read(fd, buf, 0, len, FDState.getPos(fd), function (err, bytesRead) { if (err) { return throwNodeError(thread, err); } else { for (let i = 0; i < bytesRead; i++) { byte_arr.array[offset + i] = buf.readInt8(i); } FDState.incrementPos(fd, bytesRead); thread.asyncReturn(0 === bytesRead && 0 !== len ? -1 : bytesRead); } }); } public static 'write0(I)V'(thread: JVMThread, javaThis: JVMTypes.java_io_RandomAccessFile, value: number): void { let fdObj = javaThis["java/io/RandomAccessFile/fd"]; let fd = fdObj["java/io/FileDescriptor/fd"]; let data = new Buffer(1); data.writeInt8(value, 0); thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.write(fd, data, 0, 1, FDState.getPos(fd), (err, numBytes) => { if (err) { return throwNodeError(thread, err); } FDState.incrementPos(fd, numBytes); thread.asyncReturn(); }); } public static 'writeBytes([BII)V'(thread: JVMThread, javaThis: JVMTypes.java_io_RandomAccessFile, byteArr: JVMTypes.JVMArray<number>, offset: number, len: number): void { var fdObj = javaThis["java/io/RandomAccessFile/fd"], fd = fdObj["java/io/FileDescriptor/fd"], buf = new Buffer(byteArr.array); thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.write(fd, buf, offset, len, FDState.getPos(fd), (err, numBytes) => { if (err) { return throwNodeError(thread, err); } FDState.incrementPos(fd, numBytes); thread.asyncReturn(); }); } public static 'getFilePointer()J'(thread: JVMThread, javaThis: JVMTypes.java_io_RandomAccessFile): Long { return Long.fromNumber(FDState.getPos(javaThis['java/io/RandomAccessFile/fd']['java/io/FileDescriptor/fd'])); } public static 'seek0(J)V'(thread: JVMThread, javaThis: JVMTypes.java_io_RandomAccessFile, pos: Long): void { FDState.setPos(javaThis['java/io/RandomAccessFile/fd']['java/io/FileDescriptor/fd'], pos.toNumber()); } public static 'length()J'(thread: JVMThread, javaThis: JVMTypes.java_io_RandomAccessFile): void { var fdObj = javaThis['java/io/RandomAccessFile/fd'], fd = fdObj['java/io/FileDescriptor/fd']; thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.fstat(fd, (err, stats) => { if (err) { return throwNodeError(thread, err); } thread.asyncReturn(Long.fromNumber(stats.size), null); }); } public static 'setLength(J)V'(thread: JVMThread, javaThis: JVMTypes.java_io_RandomAccessFile, arg0: Long): void { thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.'); } public static 'initIDs()V'(thread: JVMThread): void { thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.'); } public static 'close0()V'(thread: JVMThread, javaThis: JVMTypes.java_io_RandomAccessFile): void { var fdObj = javaThis['java/io/RandomAccessFile/fd'], fd = fdObj['java/io/FileDescriptor/fd']; thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.close(fd, (err?: NodeJS.ErrnoException) => { if (err) { return throwNodeError(thread, err); } else { fdObj['java/io/FileDescriptor/fd'] = -1; FDState.close(fd); thread.asyncReturn(); } }); } } class java_io_UnixFileSystem { public static 'canonicalize0(Ljava/lang/String;)Ljava/lang/String;'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, jvmPathStr: JVMTypes.java_lang_String): JVMTypes.java_lang_String { var jsStr = jvmPathStr.toString(); return util.initString(thread.getBsCl(), path.resolve(path.normalize(jsStr))); } public static 'getBooleanAttributes0(Ljava/io/File;)I'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, file: JVMTypes.java_io_File): void { var filepath = file['java/io/File/path'], fileSystem = <typeof JVMTypes.java_io_FileSystem> (<ReferenceClassData<JVMTypes.java_io_FileSystem>> thread.getBsCl().getInitializedClass(thread, 'Ljava/io/FileSystem;')).getConstructor(thread); thread.setStatus(ThreadStatus.ASYNC_WAITING); statFile(filepath.toString(), (stats) => { // Returns 0 if file does not exist, or any other error occurs. var rv: number = 0; if (stats !== null) { rv |= fileSystem['java/io/FileSystem/BA_EXISTS']; if (stats.isFile()) { rv |= fileSystem['java/io/FileSystem/BA_REGULAR']; } else if (stats.isDirectory()) { rv |= fileSystem['java/io/FileSystem/BA_DIRECTORY']; } } thread.asyncReturn(rv); }); } public static 'checkAccess(Ljava/io/File;I)Z'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, file: JVMTypes.java_io_File, access: number): void { var filepath = file['java/io/File/path']; thread.setStatus(ThreadStatus.ASYNC_WAITING); statFile(filepath.toString(), (stats) => { if (stats == null) { thread.asyncReturn(0); } else { // XXX: Assuming we're owner/group/other. :) // Shift access so it's present in owner/group/other. // Then, AND with the actual mode, and check if the result is above 0. // That indicates that the access bit we're looking for was set on // one of owner/group/other. var mask = access | (access << 3) | (access << 6); thread.asyncReturn((stats.mode & mask) > 0 ? 1 : 0); } }); } public static 'getLastModifiedTime(Ljava/io/File;)J'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, file: JVMTypes.java_io_File): void { var filepath = file['java/io/File/path']; thread.setStatus(ThreadStatus.ASYNC_WAITING); statFile(filepath.toString(), function (stats) { if (stats == null) { thread.asyncReturn(Long.ZERO, null); } else { thread.asyncReturn(Long.fromNumber(stats.mtime.getTime()), null); } }); } public static 'getLength(Ljava/io/File;)J'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, file: JVMTypes.java_io_File): void { var filepath = file['java/io/File/path']; thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.stat(filepath.toString(), (err, stat) => { thread.asyncReturn(err != null ? Long.ZERO : Long.fromNumber(stat.size), null); }); } public static 'setPermission(Ljava/io/File;IZZ)Z'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, file: JVMTypes.java_io_File, access: number, enable: number, owneronly: number): void { // Access is equal to one of the following static fields: // * FileSystem.ACCESS_READ (0x04) // * FileSystem.ACCESS_WRITE (0x02) // * FileSystem.ACCESS_EXECUTE (0x01) // These are conveniently identical to their Unix equivalents, which // we have to convert to for Node. // XXX: Currently assuming that the above assumption holds across JCLs. var filepath = file['java/io/File/path'].toString(); if (owneronly) { // Shift it 6 bits over into the 'owner' region of the access mode. access <<= 6; } else { // Clone it into the 'owner' and 'group' regions. access |= (access << 6) | (access << 3); } if (!enable) { // Do an invert and we'll AND rather than OR. access = ~access; } // Returns true on success, false on failure. thread.setStatus(ThreadStatus.ASYNC_WAITING); // Fetch existing permissions on file. statFile(filepath, (stats: fs.Stats) => { if (stats == null) { thread.asyncReturn(0); } else { var existing_access = stats.mode; // Apply mask. access = enable ? existing_access | access : existing_access & access; // Set new permissions. fs.chmod(filepath, access, (err?: NodeJS.ErrnoException) => { thread.asyncReturn(err != null ? 0 : 1); }); } }); } public static 'createFileExclusively(Ljava/lang/String;)Z'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, path: JVMTypes.java_lang_String): void { var filepath = path.toString(); thread.setStatus(ThreadStatus.ASYNC_WAITING); statFile(filepath, (stat) => { if (stat != null) { thread.asyncReturn(0); } else { fs.open(filepath, 'w', (err, fd) => { if (err != null) { thread.throwNewException('Ljava/io/IOException;', err.message); } else { fs.close(fd, (err?: NodeJS.ErrnoException) => { if (err != null) { thread.throwNewException('Ljava/io/IOException;', err.message); } else { thread.asyncReturn(1); } }); } }); } }); } public static 'delete0(Ljava/io/File;)Z'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, file: JVMTypes.java_io_File): void { // Delete the file or directory denoted by the given abstract // pathname, returning true if and only if the operation succeeds. // If file is a directory, it must be empty. var filepath = file['java/io/File/path'].toString(); thread.setStatus(ThreadStatus.ASYNC_WAITING); statFile(filepath, (stats) => { if (stats == null) { thread.asyncReturn(0); } else if (stats.isDirectory()) { fs.readdir(filepath, (err, files) => { if (files.length > 0) { thread.asyncReturn(0); } else { fs.rmdir(filepath, (err?: NodeJS.ErrnoException) => { thread.asyncReturn(1); }); } }); } else { fs.unlink(filepath, (err?: NodeJS.ErrnoException) => { thread.asyncReturn(1); }); } }); } public static 'list(Ljava/io/File;)[Ljava/lang/String;'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, file: JVMTypes.java_io_File): void { var filepath = file['java/io/File/path'], bsCl = thread.getBsCl(); thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.readdir(filepath.toString(), (err, files) => { if (err != null) { thread.asyncReturn(null); } else { thread.asyncReturn(util.newArrayFromData<JVMTypes.java_lang_String>(thread, thread.getBsCl(), '[Ljava/lang/String;', files.map((file: string) => util.initString(thread.getBsCl(), file)))); } }); } public static 'createDirectory(Ljava/io/File;)Z'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, file: JVMTypes.java_io_File): void { var filepath = file['java/io/File/path'].toString(); // Already exists. thread.setStatus(ThreadStatus.ASYNC_WAITING); statFile(filepath, (stat) => { if (stat != null) { thread.asyncReturn(0); } else { fs.mkdir(filepath, (err?: NodeJS.ErrnoException) => { thread.asyncReturn(err != null ? 0 : 1); }); } }); } public static 'rename0(Ljava/io/File;Ljava/io/File;)Z'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, file1: JVMTypes.java_io_File, file2: JVMTypes.java_io_File): void { var file1path = file1['java/io/File/path'].toString(), file2path = file2['java/io/File/path'].toString(); thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.rename(file1path, file2path, (err?: NodeJS.ErrnoException) => { thread.asyncReturn(err != null ? 0 : 1); }); } public static 'setLastModifiedTime(Ljava/io/File;J)Z'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, file: JVMTypes.java_io_File, time: Long): void { var mtime = time.toNumber(), atime = (new Date).getTime(), filepath = file['java/io/File/path'].toString(); thread.setStatus(ThreadStatus.ASYNC_WAITING); fs.utimes(filepath, atime, mtime, (err?: NodeJS.ErrnoException) => { thread.asyncReturn(1); }); } public static 'setReadOnly(Ljava/io/File;)Z'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, file: JVMTypes.java_io_File): void { // We'll be unsetting write permissions. // Leading 0o indicates octal. var filepath = file['java/io/File/path'].toString(), mask = ~0x92; thread.setStatus(ThreadStatus.ASYNC_WAITING); statFile(filepath, (stats) => { if (stats == null) { thread.asyncReturn(0); } else { fs.chmod(filepath, stats.mode & mask, (err?: NodeJS.ErrnoException) => { thread.asyncReturn(err != null ? 0 : 1); }); } }); } public static 'getSpace(Ljava/io/File;I)J'(thread: JVMThread, javaThis: JVMTypes.java_io_UnixFileSystem, file: JVMTypes.java_io_File, arg1: number): Long { thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.'); // Satisfy TypeScript return type. return null; } public static 'initIDs()V'(thread: JVMThread): void { thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.'); } } return { 'java/io/Console': java_io_Console, 'java/io/FileDescriptor': java_io_FileDescriptor, 'java/io/FileInputStream': java_io_FileInputStream, 'java/io/FileOutputStream': java_io_FileOutputStream, 'java/io/ObjectInputStream': java_io_ObjectInputStream, 'java/io/ObjectOutputStream': java_io_ObjectOutputStream, 'java/io/ObjectStreamClass': java_io_ObjectStreamClass, 'java/io/RandomAccessFile': java_io_RandomAccessFile, 'java/io/UnixFileSystem': java_io_UnixFileSystem }; };
the_stack
import { Column, ColumnBody, SearchableColumnHeader } from '.'; import { boolean, number } from '@storybook/addon-knobs'; import React from 'react'; import { action } from '@storybook/addon-actions'; const obj = { title: 'ColumnMapper', component: Column, includeStories: [], // or don't load this file at all }; export default obj; export const example = () => ( <Column totalColumns={number('Total number of columns', 1)} visible={boolean('Is visible', true)} > <SearchableColumnHeader title={'Header'} onSearch={action('onSearch')} /> <ColumnBody> <p>I can scroll.</p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi at deserunt dolor eos est impedit ipsa, laboriosam laborum nisi officia officiis quis reiciendis repellendus reprehenderit sapiente sint sunt totam vitae! </p> </ColumnBody> </Column> );
the_stack
import * as _ from 'underscore'; import { Posts } from '../lib/collections/posts/collection'; import { Sequences } from '../lib/collections/sequences/collection'; import { Collections } from '../lib/collections/collections/collection'; import { ensureIndex } from '../lib/collectionUtils'; import { accessFilterSingle, accessFilterMultiple } from '../lib/utils/schemaUtils'; import { setUserPartiallyReadSequences } from './partiallyReadSequences'; import { addGraphQLMutation, addGraphQLQuery, addGraphQLResolvers, addGraphQLSchema } from './vulcan-lib'; import { WeightedList } from './weightedList'; import type { RecommendationsAlgorithm } from '../lib/collections/users/recommendationSettings'; import { forumTypeSetting } from '../lib/instanceSettings'; const isEAForum = forumTypeSetting.get() === 'EAForum' const MINIMUM_BASE_SCORE = 50 // The set of fields on Posts which are used for deciding which posts to // recommend. Fields other than these will be projected out before downloading // from the database. const scoreRelevantFields = {baseScore:1, curatedDate:1, frontpageDate:1, defaultRecommendation: 1}; // Returns part of a mongodb aggregate pipeline, which will join against the // ReadStatuses collection and filter out any posts which have been read by the // current user. Returns as an array, so you can spread this into a pipeline // with ...pipelineFilterUnread(currentUser). If currentUser is null, returns // an empty array (no aggregation pipeline stages), so all posts are included. const pipelineFilterUnread = ({currentUser}: { currentUser: DbUser|null }) => { if (!currentUser) return []; return [ { $lookup: { from: "readstatuses", let: { documentId: "$_id", }, pipeline: [ { $match: { userId: currentUser._id, } }, { $match: { $expr: { $and: [ {$eq: ["$postId", "$$documentId"]}, ] } } }, { $limit: 1}, ], as: "views", } }, { $match: { "views": {$size:0} } }, ]; } // Given an algorithm with a set of inclusion criteria, return a mongoDB // selector that only allows the included posts // // You can think of what it's doing is taking the inclusion criteria, figuring // out what's *not* included, and then writing an inclusion selector that // excludes what's not desired. // // Wait, I hear you say. This isn't elegant at all. Like, surely there's a way // to define a table of possible exclusion criteria and you can // deterministically combine them without writing out each individual case // combinatorially. . ... Yeah .... Sometimes life is hard. const getInclusionSelector = (algorithm: RecommendationsAlgorithm) => { if (algorithm.coronavirus) { return { ["tagRelevance.tNsqhzTibgGJKPEWB"]: {$gte: 1}, question: true } } if (algorithm.reviewReviews) { if (isEAForum) { return { postedAt: {$lt: new Date(`${(algorithm.reviewReviews as number) + 1}-01-01`)}, positiveReviewVoteCount: {$gte: 1}, // EA-forum look here } } return { postedAt: { $gt: new Date(`${algorithm.reviewReviews}-01-01`), $lt: new Date(`${(algorithm.reviewReviews as number) + 1}-01-01`) }, positiveReviewVoteCount: {$gte: 1}, } } if (algorithm.reviewNominations) { if (isEAForum) { return {postedAt: {$lt: new Date(`${(algorithm.reviewNominations as number) + 1}-01-01`)}} } return { isEvent: false, postedAt: {$gt: new Date(`${algorithm.reviewNominations}-01-01`), $lt: new Date(`${(algorithm.reviewNominations as number) + 1}-01-01`)}, meta: false } } if (algorithm.reviewFinal) { return { postedAt: {$gt: new Date(`${algorithm.reviewFinal}-01-01`), $lt: new Date(`${(algorithm.reviewFinal as number) + 1}-01-01`)}, reviewCount: {$gte: 1}, finalReviewVoteScoreHighKarma: {$gte: 10} } } if (algorithm.includePersonal) { if (algorithm.includeMeta) { return {} } return {meta: false} } if (algorithm.includeMeta) { return {$or: [{frontpageDate: {$exists: true}}, {meta: true}]} } return {$and: [{frontpageDate: {$exists: true}}, {meta: false}]} } // A filter (mongodb selector) for which posts should be considered at all as // recommendations. const recommendablePostFilter = (algorithm: RecommendationsAlgorithm) => { const recommendationFilter = { // Gets the selector from the default Posts view, which includes things like // excluding drafts and deleted posts ...Posts.getParameters({}).selector, // Only consider recommending posts if they hit the minimum base score. This has a big // effect on the size of the recommendable-post set, which needs to not be // too big for performance reasons. baseScore: {$gt: algorithm.minimumBaseScore || MINIMUM_BASE_SCORE}, ...getInclusionSelector(algorithm), // Enforce the disableRecommendation flag disableRecommendation: {$ne: true}, } if (algorithm.excludeDefaultRecommendations) { return recommendationFilter } else { return {$or: [recommendationFilter, { defaultRecommendation: true}]} } } ensureIndex(Posts, {defaultRecommendation: 1}) // Return the set of all posts that are eligible for being recommended, with // scoreRelevantFields included (but other fields projected away). If // onlyUnread is true and currentUser is nonnull, posts that the user has // already read are filtered out. const allRecommendablePosts = async ({currentUser, algorithm}: { currentUser: DbUser|null, algorithm: RecommendationsAlgorithm, }): Promise<Array<DbPost>> => { return await Posts.aggregate([ // Filter to recommendable posts { $match: { ...recommendablePostFilter(algorithm), } }, // If onlyUnread, filter to just unread posts ...(algorithm.onlyUnread ? pipelineFilterUnread({currentUser}) : []), // Project out fields other than _id and scoreRelevantFields { $project: {_id:1, ...scoreRelevantFields} }, ]).toArray(); } // Returns the top-rated posts (rated by scoreFn) to recommend to a user. // count: The maximum number of posts to return. May return fewer, if there // aren't enough recommendable unread posts in the database. // currentUser: The user who is requesting the recommendations, or null if // logged out. // algorithm: Used for inclusion criteria // scoreFn: Function which takes a post (with at least scoreRelevantFields // included), and returns a number. The posts with the highest scoreFn // return value will be the ones returned. const topPosts = async ({count, currentUser, algorithm, scoreFn}: { count: number, currentUser: DbUser|null, algorithm: RecommendationsAlgorithm, scoreFn: (post: DbPost)=>number, }) => { const recommendablePostsMetadata = await allRecommendablePosts({currentUser, algorithm}); const defaultRecommendations = algorithm.excludeDefaultRecommendations ? [] : recommendablePostsMetadata.filter(p=> !!p.defaultRecommendation) const sortedTopRecommendations = _.sortBy(recommendablePostsMetadata, post => -scoreFn(post)) const unreadTopPosts = _.first([ ...defaultRecommendations, ...sortedTopRecommendations ], count) const unreadTopPostIds = _.map(unreadTopPosts, p=>p._id) return await Posts.find( { _id: {$in: unreadTopPostIds} }, { sort: {defaultRecommendation: -1, baseScore: -1} } ).fetch(); } // Returns a random weighted sampling of highly-rated posts (weighted by // sampleWeightFn) to recommend to a user. // // count: The maximum number of posts to return. May return fewer, if there // aren't enough recommendable unread posts in the database. // currentUser: The user who is requesting the recommendations, or null if // logged out. // algorithm: Used for inclusion criteria // sampleWeightFn: Function which takes a post (with at least // scoreRelevantFields included), and returns a number. Higher numbers are // more likely to be recommended. const samplePosts = async ({count, currentUser, algorithm, sampleWeightFn}: { count: number, currentUser: DbUser|null, algorithm: RecommendationsAlgorithm, sampleWeightFn: (post: DbPost)=>number, }) => { const recommendablePostsMetadata = await allRecommendablePosts({currentUser, algorithm}); const numPostsToReturn = Math.max(0, Math.min(recommendablePostsMetadata.length, count)) const defaultRecommendations = algorithm.excludeDefaultRecommendations ? [] : recommendablePostsMetadata.filter(p=> !!p.defaultRecommendation).map(p=>p._id) const sampledPosts = new WeightedList( _.map(recommendablePostsMetadata, post => [post._id, sampleWeightFn(post)]) ).pop(Math.max(numPostsToReturn - defaultRecommendations.length, 0)) const recommendedPosts = _.first([...defaultRecommendations, ...sampledPosts], numPostsToReturn) return await Posts.find( { _id: {$in: recommendedPosts} }, { sort: {defaultRecommendation: -1} } ).fetch(); } const getModifierName = (post: DbPost) => { if (post.curatedDate) return 'curatedModifier' if (post.frontpageDate) return 'frontpageModifier' return 'personalBlogpostModifier' } const getRecommendedPosts = async ({count, algorithm, currentUser}: { count: number, algorithm: RecommendationsAlgorithm, currentUser: DbUser|null }) => { const scoreFn = (post: DbPost) => { const sectionModifier = algorithm[getModifierName(post)]||0; const weight = sectionModifier + Math.pow(post.baseScore - algorithm.scoreOffset, algorithm.scoreExponent) return Math.max(0, weight); } // Cases here should match recommendationAlgorithms in RecommendationsAlgorithmPicker.jsx switch(algorithm.method) { case "top": { return await topPosts({ count, currentUser, algorithm, scoreFn }); } case "sample": { return await samplePosts({ count, currentUser, algorithm, sampleWeightFn: scoreFn, }); } default: { throw new Error(`Unrecognized recommendation algorithm: ${algorithm.method}`); } } }; const getDefaultResumeSequence = (): Array<{collectionId: string, nextPostId: string}> => { return [ { // HPMOR collectionId: "ywQvGBSojSQZTMpLh", nextPostId: "vNHf7dx5QZA4SLSZb", }, { // Codex collectionId: "2izXHCrmJ684AnZ5X", nextPostId: "gFMH3Cqw4XxwL69iy", }, { // R:A-Z collectionId: "oneQyj4pw77ynzwAF", nextPostId: "2ftJ38y9SRBCBsCzy", }, ] } const getResumeSequences = async (currentUser: DbUser|null, context: ResolverContext) => { const sequences = currentUser ? currentUser.partiallyReadSequences : getDefaultResumeSequence() if (!sequences) return []; const results = await Promise.all(_.map(sequences, async (partiallyReadSequence: any) => { const { sequenceId, collectionId, nextPostId, numRead, numTotal, lastReadTime } = partiallyReadSequence; const [sequence, collection, nextPost] = await Promise.all([ sequenceId ? context.loaders.Sequences.load(sequenceId) : null, collectionId ? context.loaders.Collections.load(collectionId) : null, context.loaders.Posts.load(nextPostId), ]); return { sequence: await accessFilterSingle(currentUser, Sequences, sequence, context), collection: await accessFilterSingle(currentUser, Collections, collection, context), nextPost: await accessFilterSingle(currentUser, Posts, nextPost, context), numRead: numRead, numTotal: numTotal, lastReadTime: lastReadTime, } } )); // Filter out results where nextPost is null. (Specifically, this filters out // the default sequences on dev databases, which would otherwise cause a crash // down the line.) return _.filter(results, result=>!!result.nextPost); } addGraphQLResolvers({ Query: { async ContinueReading(root: void, args: void, context: ResolverContext) { const { currentUser } = context; return await getResumeSequences(currentUser, context); }, async Recommendations(root: void, {count,algorithm}: {count: number, algorithm: RecommendationsAlgorithm}, context: ResolverContext) { const { currentUser } = context; const recommendedPosts = await getRecommendedPosts({count, algorithm, currentUser}) const accessFilteredPosts = await accessFilterMultiple(currentUser, Posts, recommendedPosts, context); if (recommendedPosts.length !== accessFilteredPosts.length) { // eslint-disable-next-line no-console console.error("Recommendation engine returned a post which permissions filtered out as inaccessible"); } return accessFilteredPosts; } }, Mutation: { async dismissRecommendation(root: void, {postId}: {postId: string}, context: ResolverContext) { const { currentUser } = context; if (!currentUser) return false; if (_.some(currentUser.partiallyReadSequences, (s:any)=>s.nextPostId===postId)) { const newPartiallyRead = _.filter(currentUser.partiallyReadSequences, (s:any)=>s.nextPostId !== postId); await setUserPartiallyReadSequences(currentUser._id, newPartiallyRead); return true; } return false; } }, }); addGraphQLSchema(` type RecommendResumeSequence { sequence: Sequence collection: Collection nextPost: Post! numRead: Int numTotal: Int lastReadTime: Date } `); addGraphQLQuery("ContinueReading: [RecommendResumeSequence!]"); addGraphQLQuery("Recommendations(count: Int, algorithm: JSON): [Post!]"); addGraphQLMutation("dismissRecommendation(postId: String): Boolean");
the_stack
import fs from "fs"; import { sodium } from "../../src/Crypto"; import { numToUint8Array, numFromUint8Array, getPadding, toBase64 } from "../../src/Helpers"; /** * Buzhash implements cyclic polymomial rolling hash function. * It is a custom developed keyed variant with protections against plain text * recovery from chunk lengths. * * Reading: * * http://www.serve.net/buz/Notes.1st.year/HTML/C6/rand.012.html * http://www.serve.net/buz/hash.adt/java.002.html * https://en.wikipedia.org/wiki/Rolling_hash#Cyclic_polynomial * * Buzhash is used to split data into content-dependent chunks. * * To make it difficult to guess plain text by watching split points, * we apply the following measures using a secret key: * * - Substitution table is pseudorandomly permuted. * - Initial 32-bit state is derived from key. * - Window size slightly varies depending on key. * * To further enhance protection, it's a good idea to pad chunks * before encrypting them to hide their original length. * * Some parts taken from: https://gist.github.com/dchest/50d52015939a5772497815dcd33a7983 */ export class Buzhash { private _initialState: number; private _state: number; private _windowSize: number; private _table: Uint32Array; constructor(windowSize: number, seed: Uint8Array) { if (seed.length !== 32) { throw new Error("Buzhash: key must be 32 bytes"); } // We reqire the seed to be 16 bytes internally seed = seed.subarray(0, 16); this._table = generateTable(seed); // Set the initial state to a pseudorandom value. this._initialState = scramble(seed, 0xFFFFFF01); // Pseudorandomly vary window size by ~1/4. const wmin = windowSize - Math.floor(windowSize / 4); const wmax = windowSize + Math.ceil(windowSize / 4); const rnd = scramble(seed, 0xFFFFFF02); windowSize = rnd % (wmax - wmin + 1) + wmin; // ignoring mod bias // XXX If we ever change this, we need to make sure to change the last line of update to: // this._state ^= rotr(this._table[removeChar], this._windowSize & 0x1f); // Make window size divisible by 32. windowSize = Math.ceil(windowSize / 32) * 32; this._windowSize = windowSize; this.reset(); } reset(): this { this._state = this._initialState; return this; } /* * Start the process by going through the buf and taking the first windowSize chars. * Returns the position to start from after */ start(buf: Uint8Array): number { const len = Math.min(buf.length, this._windowSize); for (let i = 0 ; i < len ; i++) { this._state = rotr(this._state, 1) ^ this._table[buf[i]]; } return len; } update(buf: Uint8Array, pos: number) { const removeChar = buf[pos - this._windowSize]; const addChar = buf[pos]; this._state = rotr(this._state, 1) ^ this._table[addChar]; // Remove the char from the start of the window: this._state ^= this._table[removeChar]; } digest(): number { return this._state; } /** * Returns true if splitting is needed, that is when the current digest * reaches the given number of the same consecutive low bits. */ split(mask: number): boolean { return (this.digest() & mask) === 0; } clean() { this._initialState = 0; this._windowSize = 0; this.reset(); wipe(this._table); } } /** * Generates a 256-number table of pseudorandom 32-bit unsigned integers such * that every bit position in the table has exactly 128 zeros and 128 ones. */ function generateTable(seed: Uint8Array): Uint32Array { const bits = new Uint8Array(256); const table = new Uint32Array(256); let ctr = 1; // Fill bits table with alternating 0 and 1. for (let i = 0; i < 256; i++) { bits[i] = i & 1; } // Generate table. for (let i = 0; i < 32; i++) { // Permute bits table. let pi = 0; while (pi < 256) { // Generate 4 pseudorandom bytes. let rnd = scramble(seed, ctr++); // Take each pseudorandom byte as index // and swap bit table value at this index. for (let k = 0; k < 4; k++) { const pj = rnd & 0xff; const tmp = bits[pi]; bits[pi] = bits[pj]; bits[pj] = tmp; rnd >>= 8; pi++; } } // Set bit in each integer in the table // according to the value in bits table. for (let j = 0; j < 256; j++) { table[j] = (table[j] << 1) | bits[j]; } } wipe(bits); return table; } function wipe(bytes: Uint8Array | Uint32Array) { if (bytes instanceof Uint8Array) { sodium.memzero(bytes); } else { bytes.fill(0); } } function scramble(key: Uint8Array, v: number): number { const hash = sodium.crypto_shorthash(numToUint8Array(v), key); return numFromUint8Array(hash.subarray(0, 4)); } function rotr(v: number, shift: number): number { shift = shift & 0x1f; // mod 32 return ((v << shift) | (v >>> (32 - shift))) >>> 0; } export class MovingSum { private _initialState: number; private _state: number; private _windowSize: number; constructor(_windowSize: number, seed: Uint8Array) { if (seed.length !== 32) { throw new Error("Buzhash: key must be 32 bytes"); } // We reqire the seed to be 16 bytes internally seed = seed.subarray(0, 16); this._windowSize = 8196; this._initialState = scramble(seed, 0xFFFFFF01); this.reset(); } reset(): this { this._state = this._initialState; return this; } /* * Start the process by going through the buf and taking the first windowSize chars. * Returns the position to start from after */ start(buf: Uint8Array): number { const len = Math.min(buf.length, this._windowSize); for (let i = 0 ; i < len ; i++) { this._state += buf[i]; } return len; } update(buf: Uint8Array, pos: number) { const removeChar = buf[pos - this._windowSize]; const addChar = buf[pos]; this._state = this._state + addChar - removeChar; } /** * Returns true if splitting is needed, that is when the current digest * reaches the given number of the same consecutive low bits. */ split(mask: number): boolean { return (this._state & mask) === 0; } clean() { this._initialState = 0; this._windowSize = 0; this.reset(); } } export class Rollsum { private s1: number; private s2: number; private window: Uint8Array; private wofs: number; private windowSize: number; private charOffset: number; constructor(_windowSize: number, seed: Uint8Array) { if (seed.length !== 32) { throw new Error("Buzhash: key must be 32 bytes"); } this.windowSize = 64; this.charOffset = 31; this.window = new Uint8Array(this.windowSize); this.reset(); } reset(): this { this.window.fill(0); this.s1 = this.windowSize * this.charOffset; this.s2 = this.windowSize * (this.windowSize - 1) * this.charOffset; this.wofs = 0; return this; } /* * Start the process by going through the buf and taking the first windowSize chars. * Returns the position to start from after */ start(_buf: Uint8Array): number { return 0; } update(buf: Uint8Array, pos: number) { const ch = buf[pos]; this.rollsumAdd(this.window[this.wofs], ch); this.window[this.wofs] = (ch); this.wofs = (this.wofs + 1) % this.windowSize; } private rollsumAdd(drop: number, add: number) { this.s1 = (this.s1 + add - drop) >>> 0; this.s2 = (this.s2 + this.s1 - (this.windowSize * (drop + this.charOffset))) >>> 0; } digest(): number { return ((this.s1 << 16) | (this.s2 & 0xffff)) >>> 0; } /** * Returns true if splitting is needed, that is when the current digest * reaches the given number of the same consecutive low bits. */ split(mask: number): boolean { return ((this.s2 & (mask)) === mask); } clean() { this.reset(); } } async function main(filename: string) { await sodium.ready; const seed = (new Uint8Array(32)).fill(12); const buf = fs.readFileSync(filename); const mask = (1 << 12) - 1; const minChunk = 1 << 14; const maxChunk = 1 << 21; function chunkify(buzhash: Buzhash | MovingSum | Rollsum, buf: Uint8Array, cb: (chunkStart: number, pos: number) => void) { buzhash.reset(); let pos = buzhash.start(buf); let chunkStart = 0; while (pos < buf.length) { buzhash.update(buf, pos); if (pos - chunkStart >= minChunk) { if ((pos - chunkStart >= maxChunk) || (buzhash.split(mask))) { cb(chunkStart, pos); buzhash.reset(); chunkStart = pos; } } pos++; } if (pos > chunkStart) { cb(chunkStart, pos); } } for (const buzhash of [new Buzhash(4096, seed), new MovingSum(8192, seed), new Rollsum(64, seed)]) { let paddedSize = 0; const chunks = {}; chunkify(buzhash, buf, (chunkStart, pos) => { const hash = toBase64(sodium.crypto_hash(buf.subarray(chunkStart, pos))); chunks[hash] = (chunks[hash] ?? 0) + 1; const chunkPadding = getPadding(pos - chunkStart); paddedSize += chunkPadding; console.log(chunkStart.toLocaleString(), (pos - chunkStart).toLocaleString(), chunkPadding.toLocaleString()); }); // Remove a chunk around the start of the file: const biteStart = 10000; const biteSize = 210; const newBuf = new Uint8Array(buf.length - biteSize); newBuf.set(buf.subarray(0, biteStart)); newBuf.set(buf.subarray(biteStart + biteSize), biteStart); newBuf[39000] = 0; newBuf[39001] = 1; newBuf[39002] = 2; newBuf[39003] = 3; newBuf[39004] = 4; const chunks2 = {}; chunkify(buzhash, newBuf, (chunkStart, pos) => { const hash = toBase64(sodium.crypto_hash(newBuf.subarray(chunkStart, pos))); chunks2[hash] = (chunks2[hash] ?? 0) + 1; const chunkPadding = getPadding(pos - chunkStart); console.log(chunkStart.toLocaleString(), (pos - chunkStart).toLocaleString(), chunkPadding.toLocaleString()); }); let reused = 0; let replaced = 0; for (const chunk of Object.keys(chunks)) { if (chunks2[chunk]) { reused++; } else { replaced++; } } console.log(`${buzhash.constructor.name}: Reused ${reused} out of ${reused + replaced} (${reused / (reused + replaced) * 100}%). Average size: ${(buf.length / (reused + replaced)).toLocaleString()}. Padded vs orig: ${paddedSize / buf.length * 100}`); } } if (process.argv.length !== 3) { console.warn("Missing filename (first param)"); } else { main(process.argv[2]); }
the_stack
import type { CeramicApi, StreamMetadata } from '@ceramicnetwork/common' import { CommitID, StreamID, StreamRef } from '@ceramicnetwork/streamid' import { TileDocument } from '@ceramicnetwork/stream-tile' import { CIP11_DEFINITION_SCHEMA_URL } from '@glazed/constants' import type { Definition } from '@glazed/did-datastore-model' import { model as encodedDataStoreModel } from '@glazed/did-datastore-model' import type { EncodedManagedModel, ManagedEntry, ManagedID, ManagedModel, ManagedSchema, ModelData, PublishedModel, Schema, } from '@glazed/types' import type { DagJWSResult } from 'dids' import { decodeModel, encodeModel } from './encoding' import { createModelDoc, publishCommits } from './publishing' import { extractSchemaReferences } from './schema' type ManagedReferenced = { definitions: Set<ManagedID> schemas: Set<ManagedID> tiles: Set<ManagedID> } type CreateContentType = { definition: Definition schema: Schema tile: Record<string, unknown> } type UsePublishedIDType = { definition: StreamID | string schema: StreamRef | string tile: StreamID | string } function getManagedIDAndVersion(id: StreamRef | string): [ManagedID, string | null] { const streamID = typeof id === 'string' ? StreamRef.from(id) : id return [streamID.baseID.toString(), CommitID.isInstance(streamID) ? streamID.toString() : null] } function getManagedID(id: StreamRef | string): ManagedID { const streamID = typeof id === 'string' ? StreamRef.from(id) : id return streamID.baseID.toString() } function isSupportedDID(did: string): boolean { return did.startsWith('did:key') } function docHasSupportedDID(doc: TileDocument<any>): boolean { return isSupportedDID(doc.metadata.controllers[0]) } const dataStoreModel = decodeModel(encodedDataStoreModel) export async function publishDataStoreSchemas(ceramic: CeramicApi): Promise<void> { await Promise.all( Object.values(dataStoreModel.schemas).map(async (schema) => { return await publishCommits(ceramic, schema.commits) }) ) } // Publish a managed model to the given Ceramic node export async function publishModel( ceramic: CeramicApi, model: ManagedModel ): Promise<PublishedModel> { const [schemas] = await Promise.all([ Promise.all( Object.values(model.schemas).map(async (schema) => { const stream = await publishCommits(ceramic, schema.commits) return [schema.alias, stream.commitId.toUrl()] }) ), publishDataStoreSchemas(ceramic), ]) const [definitions, tiles] = await Promise.all([ await Promise.all( Object.values(model.definitions).map(async (entry) => { const stream = await publishCommits(ceramic, entry.commits) return [entry.alias, stream.id.toString()] }) ), await Promise.all( Object.values(model.tiles).map(async (entry) => { const stream = await publishCommits(ceramic, entry.commits) return [entry.alias, stream.id.toString()] }) ), ]) return { definitions: Object.fromEntries(definitions), schemas: Object.fromEntries(schemas), tiles: Object.fromEntries(tiles), } } // Publish a JSON-encoded managed model to the given Ceramic node export async function publishEncodedModel( ceramic: CeramicApi, model: EncodedManagedModel ): Promise<PublishedModel> { return await publishModel(ceramic, decodeModel(model)) } /** * ```sh * import { ModelManager } from '@glazed/devtools' * ``` */ export class ModelManager { public static fromJSON(ceramic: CeramicApi, encoded: EncodedManagedModel): ModelManager { return new ModelManager(ceramic, decodeModel(encoded)) } #aliases: ModelData<string> = { definitions: {}, schemas: {}, tiles: {}, } #ceramic: CeramicApi #model: ManagedModel = { definitions: {}, schemas: {}, tiles: {}, } #referenced: Record<ManagedID, ManagedReferenced> = {} #streams: Record<ManagedID, Promise<TileDocument>> = {} constructor(ceramic: CeramicApi, model?: ManagedModel) { this.#ceramic = ceramic if (model != null) { this.addModel(model) } } // Getters get model(): ManagedModel { return this.#model } get schemas(): Array<string> { return Object.keys(this.#aliases.schemas).sort() } get definitions(): Array<string> { return Object.keys(this.#aliases.definitions).sort() } get tiles(): Array<string> { return Object.keys(this.#aliases.tiles).sort() } // Imports addModel(model: ManagedModel): void { Object.assign(this.#model.definitions, model.definitions) Object.assign(this.#model.schemas, model.schemas) Object.assign(this.#model.tiles, model.tiles) for (const [id, schema] of Object.entries(model.schemas)) { this.#aliases.schemas[schema.alias] = id for (const refIDs of Object.values(schema.dependencies)) { for (const refID of refIDs) { if (this.#referenced[refID] == null) { this.#referenced[refID] = { definitions: new Set<ManagedID>(), schemas: new Set<ManagedID>(), tiles: new Set<ManagedID>(), } } this.#referenced[refID].schemas.add(id) } } } for (const [id, definition] of Object.entries(model.definitions)) { this.#aliases.definitions[definition.alias] = id if (this.#referenced[definition.schema] == null) { this.#referenced[definition.schema] = { definitions: new Set<ManagedID>(), schemas: new Set<ManagedID>(), tiles: new Set<ManagedID>(), } } this.#referenced[definition.schema].definitions.add(id) } for (const [id, tile] of Object.entries(model.tiles)) { this.#aliases.tiles[tile.alias] = id if (this.#referenced[tile.schema] == null) { this.#referenced[tile.schema] = { definitions: new Set<ManagedID>(), schemas: new Set<ManagedID>(), tiles: new Set<ManagedID>(), } } this.#referenced[tile.schema].tiles.add(id) } } addJSONModel(encoded: EncodedManagedModel): void { this.addModel(decodeModel(encoded)) } // Loaders async loadStream(streamID: StreamRef | string): Promise<TileDocument> { const id = typeof streamID === 'string' ? streamID : streamID.baseID.toString() if (this.#streams[id] == null) { this.#streams[id] = this._loadAndValidateStream(id) } return await this.#streams[id] } /** @internal */ async _loadAndValidateStream(id: string): Promise<TileDocument> { const stream = await TileDocument.load<Record<string, any>>(this.#ceramic, id) if (stream.anchorCommitIds.length !== 0) { throw new Error(`Invalid stream ${id}: contains anchor commit`) } // Shortcut logic for single commit if (stream.allCommitIds.length === 1 && docHasSupportedDID(stream)) { return stream } const commits = await Promise.all( stream.allCommitIds.map(async (commitID) => { return await TileDocument.load(this.#ceramic, commitID) }) ) const unsupported = commits.find((commit) => !docHasSupportedDID(commit)) if (unsupported != null) { throw new Error(`Invalid stream ${id}: contains a commit authored by an unsupported DID`) } return stream } async loadCommits(id: ManagedID): Promise<Array<DagJWSResult>> { const commits = await this.#ceramic.loadStreamCommits(id) return commits.map((r) => r.value as DagJWSResult) } async loadSchema(id: StreamRef | string, alias?: string): Promise<ManagedID> { const [managedID, commitID] = getManagedIDAndVersion(id) if (commitID === null) { throw new Error(`Expected CommitID to load schema: ${managedID}`) } const existing = this.#model.schemas[managedID] if (existing != null) { if (existing.version !== commitID) { throw new Error(`Another version for this schema is already set: ${existing.version}`) } if (alias != null && existing.alias !== alias) { throw new Error(`Another alias for this schema is already set: ${existing.alias}`) } return managedID } const [stream, commits] = await Promise.all([ this.loadStream(commitID), this.loadCommits(managedID), ]) const content = (stream.content ?? {}) as Schema const name = alias ?? content.title if (name == null) { throw new Error('Schema must have a title property or an alias must be provided') } const dependencies = await this.loadSchemaDependencies(content) this.#model.schemas[managedID] = { alias: name, commits, dependencies, version: commitID } this.#aliases.schemas[name] = managedID return managedID } async loadSchemaDependencies(schema: Schema): Promise<Record<string, Array<string>>> { const references = extractSchemaReferences(schema) const ids = new Set<string>() for (const refs of Object.values(references)) { for (const ref of refs) { ids.add(ref) } } const loaded = await Promise.all( Array.from(ids).map(async (id) => [id, await this.loadSchema(id)]) ) const idToManaged: Record<string, string> = Object.fromEntries(loaded) return Object.entries(references).reduce((acc, [path, deps]) => { acc[path] = deps.map((id) => idToManaged[id]) return acc }, {} as Record<string, Array<string>>) } // High-level async create<T extends keyof CreateContentType, Content = CreateContentType[T]>( type: T, alias: string, content: Content, meta?: Partial<StreamMetadata> ): Promise<ManagedID> { switch (type) { case 'schema': return await this.createSchema(alias, content as any) case 'definition': return await this.createDefinition(alias, content as any) case 'tile': return await this.createTile(alias, content as any, meta) default: throw new Error(`Unsupported type: ${type as string}`) } } async usePublished<T extends keyof UsePublishedIDType, ID = UsePublishedIDType[T]>( type: T, alias: string, id: ID ): Promise<ManagedID> { switch (type) { case 'schema': return await this.usePublishedSchema(alias, id as any) case 'definition': return await this.usePublishedDefinition(alias, id as any) case 'tile': return await this.usePublishedTile(alias, id as any) default: throw new Error(`Unsupported type: ${type as string}`) } } // Schemas getSchemaID(alias: string): ManagedID | null { return this.#aliases.schemas[alias] ?? null } hasSchemaAlias(alias: string): boolean { return this.getSchemaID(alias) != null } getSchema(id: ManagedID): ManagedSchema | null { return this.#model.schemas[id] ?? null } getSchemaURL(id: ManagedID): string | null { const schema = this.#model.schemas[id] return schema ? CommitID.fromString(schema.version).toUrl() : null } getSchemaByAlias(alias: string): ManagedSchema | null { const id = this.getSchemaID(alias) return id ? this.getSchema(id) : null } async createSchema(alias: string, schema: Schema): Promise<ManagedID> { if (this.#ceramic.did == null || !this.#ceramic.did.authenticated) { throw new Error('Ceramic instance must be authenticated') } if (!isSupportedDID(this.#ceramic.did.id)) { throw new Error( `Invalid DID ${ this.#ceramic.did.id } to create stream for model, only "did:key" is supported` ) } if (this.hasSchemaAlias(alias)) { throw new Error(`Schema ${alias} already exists`) } const [stream, dependencies] = await Promise.all([ createModelDoc(this.#ceramic, schema), this.loadSchemaDependencies(schema), ]) const id = stream.id.toString() this.#model.schemas[id] = { alias, commits: await this.loadCommits(id), dependencies, version: stream.commitId.toString(), } this.#aliases.schemas[alias] = id return id } async usePublishedSchema(alias: string, id: StreamRef | string): Promise<ManagedID> { if (alias == null) { throw new Error('Schema alias must be provided') } return await this.loadSchema(id, alias) } // Definitions getDefinitionID(alias: string): ManagedID | null { return this.#aliases.definitions[alias] ?? null } hasDefinitionAlias(alias: string): boolean { return this.getDefinitionID(alias) != null } getDefinition(id: ManagedID): ManagedEntry | null { return this.#model.definitions[id] ?? null } async createDefinition(alias: string, definition: Definition): Promise<ManagedID> { if (this.#ceramic.did == null || !this.#ceramic.did.authenticated) { throw new Error('Ceramic instance must be authenticated') } if (!isSupportedDID(this.#ceramic.did.id)) { throw new Error( `Invalid DID ${ this.#ceramic.did.id } to create stream for model, only "did:key" is supported` ) } if (this.hasDefinitionAlias(alias)) { throw new Error(`Definition ${alias} already exists`) } await publishDataStoreSchemas(this.#ceramic) const [stream, schemaID] = await Promise.all([ createModelDoc(this.#ceramic, definition, { schema: CIP11_DEFINITION_SCHEMA_URL }), this.loadSchema(definition.schema), ]) const id = stream.id.toString() this.#model.definitions[id] = { alias, commits: await this.loadCommits(id), schema: schemaID, version: stream.commitId.toString(), } this.#aliases.definitions[alias] = id return id } async usePublishedDefinition(alias: string, id: StreamID | string): Promise<ManagedID> { if (this.hasDefinitionAlias(alias)) { throw new Error(`Definition ${alias} already exists`) } const definitionID = getManagedID(id) const [stream, commits] = await Promise.all([ this.loadStream(id), this.loadCommits(definitionID), ]) this.#model.definitions[definitionID] = { alias, commits, schema: await this.loadSchema((stream.content as Definition).schema), version: stream.commitId.toString(), } this.#aliases.definitions[alias] = definitionID return definitionID } // Tiles getTileID(alias: string): ManagedID | null { return this.#aliases.tiles[alias] ?? null } hasTileAlias(alias: string): boolean { return this.getTileID(alias) != null } getTile(id: ManagedID): ManagedEntry | null { return this.#model.tiles[id] ?? null } async createTile<T extends Record<string, unknown>>( alias: string, contents: T, meta: Partial<StreamMetadata> = {} ): Promise<ManagedID> { if (this.#ceramic.did == null || !this.#ceramic.did.authenticated) { throw new Error('Ceramic instance must be authenticated') } if (!isSupportedDID(this.#ceramic.did.id)) { throw new Error('Unsupported DID to create stream for model') } if (this.hasTileAlias(alias)) { throw new Error(`Tile ${alias} already exists`) } if (meta.schema == null) { throw new Error(`Missing schema to create tile ${alias}`) } const [stream, schemaID] = await Promise.all([ createModelDoc(this.#ceramic, contents, meta), this.loadSchema(meta.schema), ]) const id = stream.id.toString() this.#model.tiles[id] = { alias, commits: await this.loadCommits(id), schema: schemaID, version: stream.commitId.toString(), } this.#aliases.tiles[alias] = id return id } async usePublishedTile(alias: string, id: StreamID | string): Promise<ManagedID> { if (this.hasTileAlias(alias)) { throw new Error(`Tile ${alias} already exists`) } const tileID = getManagedID(id) const [stream, commits] = await Promise.all([this.loadStream(id), this.loadCommits(tileID)]) if (stream.metadata.schema == null) { throw new Error('Loaded tile has no schema defined') } this.#model.tiles[tileID] = { alias, commits, schema: await this.loadSchema(stream.metadata.schema), version: stream.commitId.toString(), } this.#aliases.tiles[alias] = tileID return tileID } // Exports async toPublished(): Promise<PublishedModel> { return await publishModel(this.#ceramic, this.#model) } toJSON(): EncodedManagedModel { return encodeModel(this.#model) } }
the_stack
import PlayerComponent from '../interfaces/component'; import EventsList from '../interfaces/events-list'; import Player from '../player'; import { EVENT_OPTIONS, IS_ANDROID, IS_IOS } from '../utils/constants'; import { hasClass, isAudio, offset, removeElement } from '../utils/general'; import { formatTime } from '../utils/time'; /** * Progress bar element. * * @description This class creates a progress bar to track how much time media has been played, * downloaded and its current time, using `semantic markup`, such as input range and progress elements. * @see https://codepen.io/mi-lee/post/an-overview-of-html5-semantics * @see https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/cross_browser_video_player#Progress * @see https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/buffering_seeking_time_ranges * @class Progress * @implements PlayerComponent */ class Progress implements PlayerComponent { /** * Instance of OpenPlayer. * * @private * @type Player * @memberof Progress */ #player: Player; /** * Container for progress bar elements (buffered, played and slider input). * * @private * @type HTMLDivElement * @memberof Progress */ #progress: HTMLDivElement; /** * Element that allows changing media's current position (time). * * @private * @type HTMLInputElement * @memberof Progress */ #slider: HTMLInputElement; /** * Element that displays the media's downloaded amount. * * @private * @type HTMLProgressElement * @memberof Progress */ #buffer: HTMLProgressElement; /** * Element that displays the media's played time. * * @private * @type HTMLProgressElement * @memberof Progress */ #played: HTMLProgressElement; /** * Element that displays the current media time when hovering in the progress bar. * * @private * @type HTMLSpanElement * @memberof Progress */ #tooltip: HTMLSpanElement; /** * Events that will be triggered in Progress element: * - container (to display tooltip when hovering in the progress bar) * - global (to hide tooltip once user moves out of the progress bar) * - media (to capture different states of the current time and duration in the time rail) * - slider (events to be triggered when clicking or sliding time rail) * * @private * @type EventsList * @memberof Progress */ #events: EventsList = { container: {}, controls: {}, global: {}, media: {}, slider: {}, }; /** * Flag that pauses and then plays media properly (if media was played) when * clicking in the progress bar. * * @private * @type {boolean} * @memberof Progress */ #forcePause: boolean; /** * Default labels from player's config * * @private * @type object * @memberof Progress */ #labels: any; /** * Position of the button to be indicated as part of its class name * * @private * @type {string} * @memberof Progress */ #position: string; /** * Layer where the control item will be placed * * @private * @type {string} * @memberof Captions */ #layer: string; /** * Create an instance of Progress. * * @param {Player} player * @returns {Progress} * @memberof Progress */ constructor(player: Player, position: string, layer: string) { this.#player = player; this.#labels = player.getOptions().labels; this.#forcePause = false; this.#position = position; this.#layer = layer; this._keydownEvent = this._keydownEvent.bind(this); return this; } /** * * @inheritDoc * @memberof Progress */ public create(): void { this.#progress = document.createElement('div'); this.#progress.className = `op-controls__progress op-control__${this.#position}`; this.#progress.tabIndex = 0; this.#progress.setAttribute('aria-label', this.#labels.progressSlider); this.#progress.setAttribute('aria-valuemin', '0'); this.#slider = document.createElement('input'); this.#slider.type = 'range'; this.#slider.className = 'op-controls__progress--seek'; this.#slider.tabIndex = -1; this.#slider.setAttribute('min', '0'); this.#slider.setAttribute('max', '0'); this.#slider.setAttribute('step', '0.1'); this.#slider.value = '0'; this.#slider.setAttribute('aria-label', this.#labels.progressRail); this.#slider.setAttribute('role', 'slider'); this.#buffer = document.createElement('progress'); this.#buffer.className = 'op-controls__progress--buffer'; this.#buffer.setAttribute('max', '100'); this.#buffer.value = 0; this.#played = document.createElement('progress'); this.#played.className = 'op-controls__progress--played'; this.#played.setAttribute('max', '100'); this.#played.setAttribute('role', 'presentation'); this.#played.value = 0; this.#progress.appendChild(this.#slider); this.#progress.appendChild(this.#played); this.#progress.appendChild(this.#buffer); if (!IS_IOS && !IS_ANDROID) { this.#tooltip = document.createElement('span'); this.#tooltip.className = 'op-controls__tooltip'; this.#tooltip.tabIndex = -1; this.#tooltip.innerHTML = '00:00'; this.#progress.appendChild(this.#tooltip); } const setInitialProgress = () => { if (this.#slider.classList.contains('error')) { this.#slider.classList.remove('error'); } const el = this.#player.activeElement(); if (el.duration !== Infinity && !this.#player.getElement().getAttribute('op-live__enabled') && !this.#player.getElement().getAttribute('op-dvr__enabled')) { this.#slider.setAttribute('max', `${el.duration}`); const current = this.#player.isMedia() ? el.currentTime : (el.duration - el.currentTime); this.#slider.value = current.toString(); this.#progress.setAttribute('aria-valuemax', el.duration.toString()); } else if (this.#player.getElement().getAttribute('op-dvr__enabled')) { this.#slider.setAttribute('max', '1'); this.#slider.value = '1'; this.#slider.style.backgroundSize = '100% 100%'; this.#played.value = 1; this.#progress.setAttribute('aria-valuemax', '1'); this.#progress.setAttribute('aria-hidden', 'false'); } else if (!this.#player.getOptions().live.showProgress) { this.#progress.setAttribute('aria-hidden', 'true'); } }; let lastCurrentTime = 0; const defaultDuration = this.#player.getOptions().progress.duration || 0; const isAudioEl = isAudio(this.#player.getElement()); this.#events.media.loadedmetadata = setInitialProgress.bind(this); this.#events.controls.controlschanged = setInitialProgress.bind(this); this.#events.media.progress = (e: Event) => { const el = (e.target as HTMLMediaElement); if (el.duration !== Infinity && !this.#player.getElement().getAttribute('op-live__enabled')) { if (el.duration > 0) { for (let i = 0, total = el.buffered.length; i < total; i++) { if (el.buffered.start(el.buffered.length - 1 - i) < el.currentTime) { this.#buffer.value = (el.buffered.end(el.buffered.length - 1 - i) / el.duration) * 100; break; } } } } else if (!this.#player.getElement().getAttribute('op-dvr__enabled') && this.#progress.getAttribute('aria-hidden') === 'false' && !this.#player.getOptions().live.showProgress) { this.#progress.setAttribute('aria-hidden', 'true'); } }; this.#events.media.waiting = () => { if (isAudioEl && !this.#slider.classList.contains('loading')) { this.#slider.classList.add('loading'); } if (isAudioEl && this.#slider.classList.contains('error')) { this.#slider.classList.remove('error'); } }; this.#events.media.playererror = () => { if (isAudioEl && !this.#slider.classList.contains('error')) { this.#slider.classList.add('error'); } if (isAudioEl && this.#slider.classList.contains('loading')) { this.#slider.classList.remove('loading'); } }; this.#events.media.pause = () => { const el = this.#player.activeElement(); if (el.duration !== Infinity && !this.#player.getElement().getAttribute('op-live__enabled')) { const current = el.currentTime; this.#progress.setAttribute('aria-valuenow', current.toString()); this.#progress.setAttribute('aria-valuetext', formatTime(current)); } }; this.#events.media.play = () => { if (isAudioEl && this.#slider.classList.contains('loading')) { this.#slider.classList.remove('loading'); } if (isAudioEl && this.#slider.classList.contains('error')) { this.#slider.classList.remove('error'); } if (this.#player.activeElement().duration !== Infinity && !this.#player.getElement().getAttribute('op-live__enabled')) { this.#progress.removeAttribute('aria-valuenow'); this.#progress.removeAttribute('aria-valuetext'); } }; this.#events.media.playing = () => { if (isAudioEl && this.#slider.classList.contains('loading')) { this.#slider.classList.remove('loading'); } if (isAudioEl && this.#slider.classList.contains('error')) { this.#slider.classList.remove('error'); } }; this.#events.media.timeupdate = () => { const el = this.#player.activeElement(); if (el.duration !== Infinity && (!this.#player.getElement().getAttribute('op-live__enabled') || this.#player.getElement().getAttribute('op-dvr__enabled'))) { if (!this.#slider.getAttribute('max') || this.#slider.getAttribute('max') === '0' || parseFloat(this.#slider.getAttribute('max') || '-1') !== el.duration) { this.#slider.setAttribute('max', `${el.duration}`); this.#progress.setAttribute('aria-hidden', 'false'); } // Adjust current time between Media and Ads; with the latter, it is convenient to add an extra // second to ensure it will reach the end of the rail const duration = ((el.duration - el.currentTime) + 1 >= 100 ? 100 : (el.duration - el.currentTime) + 1); const current = this.#player.isMedia() ? el.currentTime : duration; const min = parseFloat(this.#slider.min); const max = parseFloat(this.#slider.max); this.#slider.value = current.toString(); this.#slider.style.backgroundSize = `${((current - min) * 100) / (max - min)}% 100%`; this.#played.value = el.duration <= 0 || isNaN(el.duration) || !isFinite(el.duration) ? defaultDuration : ((current / el.duration) * 100); if (this.#player.getElement().getAttribute('op-dvr__enabled') && Math.floor(this.#played.value) >= 99) { lastCurrentTime = el.currentTime; this.#progress.setAttribute('aria-hidden', 'false'); } } else if (!this.#player.getElement().getAttribute('op-dvr__enabled') && this.#progress.getAttribute('aria-hidden') === 'false' && !this.#player.getOptions().live.showProgress) { this.#progress.setAttribute('aria-hidden', 'true'); } }; this.#events.media.durationchange = () => { const el = this.#player.activeElement(); const current = this.#player.isMedia() ? el.currentTime : (el.duration - el.currentTime); this.#slider.setAttribute('max', `${el.duration}`); this.#progress.setAttribute('aria-valuemax', el.duration.toString()); this.#played.value = el.duration <= 0 || isNaN(el.duration) || !isFinite(el.duration) ? defaultDuration : ((current / el.duration) * 100); }; this.#events.media.ended = () => { this.#slider.style.backgroundSize = '0% 100%'; this.#slider.setAttribute('max', '0'); this.#buffer.value = 0; this.#played.value = 0; }; /** * * @private */ const updateSlider = (e: any) => { if (hasClass(this.#slider, 'op-progress--pressed')) { return; } const target = (e.target as HTMLInputElement); this.#slider.classList.add('.op-progress--pressed'); const el = this.#player.activeElement(); const min = parseFloat(target.min); const max = parseFloat(target.max); const val = parseFloat(target.value); this.#slider.style.backgroundSize = `${((val - min) * 100) / (max - min)}% 100%`; this.#played.value = el.duration <= 0 || isNaN(el.duration) || !isFinite(el.duration) ? defaultDuration : ((val / el.duration) * 100); if (this.#player.getElement().getAttribute('op-dvr__enabled')) { el.currentTime = (Math.round(this.#played.value) >= 99) ? lastCurrentTime : val; } else { el.currentTime = val; } this.#slider.classList.remove('.op-progress--pressed'); }; /** * * @private */ const forcePause = (e: KeyboardEvent) => { const el = this.#player.activeElement(); // If current progress is not related to an Ad, manipulate current time if ((e.which === 1 || e.which === 0) && this.#player.isMedia()) { if (!el.paused) { el.pause(); this.#forcePause = true; } } }; /** * * @private */ const releasePause = () => { const el = this.#player.activeElement(); if (this.#forcePause === true && this.#player.isMedia()) { if (el.paused) { el.play(); this.#forcePause = false; } } }; /** * When tapping on mobile, it will update the time and force pause * * @private * @param {any} e Event to calculate new time when user taps on time rail */ const mobileForcePause = (e: any) => { const el = this.#player.activeElement(); if (el.duration !== Infinity) { // Android devices (and maybe others) don't consider `originalEvent`. Check for the // existence of them; otherwise, use the event's `changedTouches` element. const changedTouches = e.originalEvent ? e.originalEvent.changedTouches : e.changedTouches; const x = changedTouches ? changedTouches[0].pageX : e.pageX; const pos = x - offset(this.#progress).left; const percentage = (pos / this.#progress.offsetWidth); const time = percentage * el.duration; this.#slider.value = time.toString(); updateSlider(e); forcePause(e); } }; this.#events.slider.input = updateSlider.bind(this); this.#events.slider.change = updateSlider.bind(this); this.#events.slider.mousedown = forcePause.bind(this); this.#events.slider.mouseup = releasePause.bind(this); this.#events.slider.touchstart = mobileForcePause.bind(this); this.#events.slider.touchend = releasePause.bind(this); if (!IS_IOS && !IS_ANDROID) { this.#events.container.mousemove = (e: any) => { const el = this.#player.activeElement(); if (el.duration !== Infinity && !this.#player.isAd()) { const x = (e.originalEvent && e.originalEvent.changedTouches) ? e.originalEvent.changedTouches[0].pageX : e.pageX; let pos = x - offset(this.#progress).left; const half = this.#tooltip.offsetWidth / 2; const percentage = (pos / this.#progress.offsetWidth); const time = percentage * el.duration; const mediaContainer = this.#player.getContainer(); const limit = mediaContainer.offsetWidth - this.#tooltip.offsetWidth; if (pos <= 0 || x - offset(mediaContainer).left <= half) { pos = 0; } else if (x - offset(mediaContainer).left >= limit) { pos = limit - offset(this.#slider).left - 10; } else { pos -= half; } if (percentage >= 0 && percentage <= 1) { this.#tooltip.classList.add('op-controls__tooltip--visible'); } else { this.#tooltip.classList.remove('op-controls__tooltip--visible'); } this.#tooltip.style.left = `${pos}px`; this.#tooltip.innerHTML = isNaN(time) ? '00:00' : formatTime(time); } }; this.#events.global.mousemove = (e: MouseEvent) => { if (!(e.target as HTMLElement).closest('.op-controls__progress') || this.#player.isAd()) { this.#tooltip.classList.remove('op-controls__tooltip--visible'); } }; } Object.keys(this.#events.media).forEach(event => { this.#player.getElement().addEventListener(event, this.#events.media[event], EVENT_OPTIONS); }); Object.keys(this.#events.slider).forEach(event => { this.#slider.addEventListener(event, this.#events.slider[event], EVENT_OPTIONS); }); this.#progress.addEventListener('keydown', this.#player.getEvents().keydown, EVENT_OPTIONS); this.#progress.addEventListener('mousemove', this.#events.container.mousemove, EVENT_OPTIONS); document.addEventListener('mousemove', this.#events.global.mousemove, EVENT_OPTIONS); this.#player.getContainer().addEventListener('keydown', this._keydownEvent, EVENT_OPTIONS); this.#player.getControls().getContainer().addEventListener('controlschanged', this.#events.controls.controlschanged, EVENT_OPTIONS); this.#player.getControls().getLayer(this.#layer).appendChild(this.#progress); } /** * * @inheritDoc * @memberof Progress */ public destroy(): void { Object.keys(this.#events).forEach(event => { this.#player.getElement().removeEventListener(event, this.#events[event]); }); Object.keys(this.#events.slider).forEach(event => { this.#slider.removeEventListener(event, this.#events.slider[event]); }); this.#progress.removeEventListener('keydown', this.#player.getEvents().keydown); this.#progress.removeEventListener('mousemove', this.#events.container.mousemove); document.removeEventListener('mousemove', this.#events.global.mousemove); this.#player.getContainer().removeEventListener('keydown', this._keydownEvent); this.#player.getControls().getContainer().removeEventListener('controlschanged', this.#events.controls.controlschanged); removeElement(this.#buffer); removeElement(this.#played); removeElement(this.#slider); if (!IS_IOS && !IS_ANDROID) { removeElement(this.#tooltip); } removeElement(this.#progress); } /** * Use the 0-9 keys to manipulate current media time to set media to the 0% to 90% of duration. * * @private * @param {KeyboardEvent} e * @memberof Progress */ private _keydownEvent(e: KeyboardEvent) { const el = this.#player.activeElement(); const isAd = this.#player.isAd(); const key = e.which || e.keyCode || 0; if (!isAd && key >= 48 && key <= 57 && el.duration !== Infinity) { let step = 0; for (let i = 48, limit = 57; i <= limit; i++) { if (i < key) { step++; } } el.currentTime = el.duration * (0.1 * step); e.preventDefault(); e.stopPropagation(); } } } export default Progress;
the_stack
import { BuildData, ObserveForStatus } from "@adpt/core"; import { DockerSplitRegistryInfo } from "../docker"; import { DaemonSetSpec } from "./DaemonSet"; import { DeploymentSpec } from "./Deployment"; import { PodSpec } from "./Pod"; import { ServiceSpec } from "./Service"; /** * Kubernetes Kind * * @public */ export type Kind = string; /** @public */ export interface CRSpec { [key: string]: any; } /** @public */ export type Spec = DaemonSetSpec | DeploymentSpec | PodSpec | ServiceSpec | CRSpec; /** @public */ export interface Metadata { namespace?: string; labels?: { [key: string]: string }; annotations?: { [key: string]: string }; } /** @public */ export type ResourceProps = { key: string } & ( ResourceClusterRole | ResourceClusterRoleBinding | ResourceDaemonSet | ResourcePod | ResourceService | ResourceServiceAccount | ResourceConfigMap | ResourceSecret | ResourceCR ); /** @public */ export type ResourcePropsWithConfig = ResourceProps & { config: ClusterInfo }; /** @public */ export interface ResourceInfo { kind: Kind; statusQuery?: (props: ResourceProps, observe: ObserveForStatus, buildData: BuildData) => unknown | Promise<unknown>; specsEqual(actual: Spec, element: Spec): boolean; } /** * Holds the information needed to connect, authenticate, and run code in a kuberenetes cluster * * @public */ export interface ClusterInfo { /** Javascript object formed by parsing a valid kubeconfig file */ kubeconfig: Kubeconfig; /** * Registry to which Docker images used by the cluster in `kubeconfig` should be pushed and pulled * * @remarks * If `registryPrefix` is a string, it is assumed that the cluster can pull from the same string * that outsiders can push to. * * If `registryPrefix` is of the form `{ external: string, internal: string }` then the `external` * string will be used to push images, and the `internal` string will be used to pull images. * * Note(manishv) * This is a bit of a hack to allow one hostname or IP address to push images from outside * a particular environment (say k8s) and a different URL for that environment to pull * images. * * A good example of this is a k3s-dind (k3s docker-in-docker) instance of kubernetes where * a private registry is running on a docker network attached to the k3s-dind instance, but where we * want to push {@link docker.LocalDockerImage} built images to that registry. Since * {@link docker.LocalDockerImage | LocalDockerImage} is outside the k3s-dind environment, it must * use a host accessible network to push to the registry. However, since the k3s-dind instance sees * the registry from within Docker, it must use a different address to pull the images for use. * * Once network scopes are fully supported, this interface will change to whatever is appropriate. It * is best if you can arrange to have the same URL or registry string work for all access regardless * of which network the registry, Adapt host, and ultimate container running environment uses. * */ registryPrefix?: string | DockerSplitRegistryInfo; } /** @public */ export interface ResourceBase { /** * config to connect to the k8s cluster * * required if isTemplate is false */ config?: ClusterInfo; /** * Specifies whether this resource is just a template for use in a controller */ isTemplate?: boolean; apiVersion?: string; kind: Kind; metadata?: Metadata; } /** * @public */ export interface PolicyRule { /** * APIGroups is the name of the APIGroup that contains the resources. * * If multiple API groups are specified, any action requested against one * of the enumerated resources in any API group will be allowed. */ apiGroups?: string[]; /** * NonResourceURLs is a set of partial urls that a user should have access to. * * *s are allowed, but only as the full, final step in the path. * Since non-resource URLs are not namespaced, this field is only applicable * for ClusterRoles referenced from a ClusterRoleBinding. * Rules can either apply to API resources (such as "pods" or "secrets") or * non-resource URL paths (such as "/api"), but not both. */ nonResourceURLs?: string[]; /** * ResourceNames is an optional white list of names that the rule applies to. * * An empty set means that everything is allowed. */ resourceNames?: string[]; /** * Resources is a list of resources this rule applies to. * * ResourceAll represents all resources. */ resources: string[]; /** * Verbs is a list of Verbs that apply to ALL the ResourceKinds and * AttributeRestrictions contained in this rule. * * VerbAll represents all kinds. */ verbs: string[]; } /** * AggregationRule for {@link k8s.ClusterRole} * * @public */ export interface AggregationRule { /** * ClusterRoleSelectors holds a list of selectors which will be used to * find ClusterRoles and create the rules. * * If any of the selectors match, then the ClusterRole's permissions will be added */ clusterRoleSelector: LabelSelector; } /** @public */ export interface ResourceClusterRole extends ResourceBase { apiVersion: "rbac.authorization.k8s.io/v1"; kind: "ClusterRole"; aggregationRule?: AggregationRule; rules?: PolicyRule[]; } /** * RoleRef for {@link k8s.ResourceClusterRoleBinding} * * @public */ export interface RoleRef { /** apiGroup is the group for the resource being referenced */ apiGroup: string; /** kind is the type of resource being referenced */ kind: string; /** Name is the name of resource being referenced */ name: string; } /** * Subject for {@link k8s.ResourceClusterRoleBinding} * * @public */ export interface Subject { /** apiGroup is the group for the object being referenced */ apiGroup: string; /** kind is the type of object being referenced */ kind: string; /** * Name of the object being referenced. */ name: string; /** * Namespace of the referenced object. * * If the object kind is non-namespace, such as "User" or "Group", and this value * is not empty the Authorizer should report an error. */ namespace?: string; } /** @public */ export interface ResourceClusterRoleBinding extends ResourceBase { apiVersion: "rbac.authorization.k8s.io/v1"; kind: "ClusterRoleBinding"; roleRef: RoleRef; subjects: Subject[]; } /** @public */ export interface ResourceDaemonSet extends ResourceBase { apiVersion: "apps/v1"; kind: "DaemonSet"; spec: DaemonSetSpec; } /** @public */ export interface ResourcePod extends ResourceBase { kind: "Pod"; spec: PodSpec; } /** @public */ export interface ResourceService extends ResourceBase { kind: "Service"; spec: ServiceSpec; } /** @public */ export interface ResourceServiceAccount extends ResourceBase { kind: "ServiceAccount"; automountServiceAccountToken?: boolean; imagePullSecrets?: { name: string }[]; secrets?: ObjectReference[]; } /** @public */ export interface ResourceConfigMap extends ResourceBase { kind: "ConfigMap"; binaryData?: { [key: string]: string }; data?: { [key: string]: string }; /** @beta */ immutable?: boolean; } /** @public */ export interface ResourceSecret extends ResourceBase { kind: "Secret"; data?: { [key: string]: string }; stringData?: { [key: string]: string }; type?: string; } /** @public */ export interface ResourceCR extends ResourceBase { kind: string; spec: CRSpec; } /** @public */ export function computeNamespaceFromMetadata(metadata?: Metadata) { if (!metadata) return "default"; if (!metadata.namespace) return "default"; return metadata.namespace; } /** @public */ export interface Kubeconfig { apiVersion?: "v1"; kind: "Config"; "current-context": string; contexts: { name: string, context: { cluster: string, user: string } }[]; clusters: { name: string, cluster: { "certificate-authority-data": string; server: string; }; }[]; preferences?: unknown; users: { name: string, user: { "client-certificate-data"?: string; "client-key-data"?: string; "username"?: string; "password"?: string; } }[]; } /** * LabelSelectorRequirement used in {@link k8s.LabelSelector} * * @public */ interface LabelSelectorRequirement { /** * key is the label key that the selector applies to. * * patch strategy: merge * patch merge key: key */ key: string; /** * operator represents a key's relationship to a set of values. * Valid operators are In, NotIn, Exists and DoesNotExist. */ operator: string; /** * values is an array of string values. * If the operator is In or NotIn, the values array must be non-empty. * If the operator is Exists or DoesNotExist, the values array must be empty. * This array is replaced during a strategic merge patch. */ values: string[]; } /** @public */ export function isLabelSelector(x: any): x is LabelSelector { return x.matchLabels != null || x.matchExpressions != null; } /** @public */ export interface LabelSelector { /** * matchExpressions is a list of label selector requirements. The requirements are ANDed. */ matchExpressions?: LabelSelectorRequirement[]; /** * matchLabels is a map of `{key,value}`pairs. A single `{key,value}` in the matchLabels map * is equivalent to an element of matchExpressions, whose key field is "key", the operator * is "In", and the values array contains only "value". The requirements are ANDed. */ matchLabels?: { [key: string]: string }; } /** @public */ export interface LocalObjectReference { /** * Name of the referent. * * More info: {@link https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names} */ name: string; } /** * PodTemplateSpec from k8s API * * @public */ export interface PodTemplateSpec { /** * Standard object's metadata. * More Info: {@link https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata} */ metadata: Metadata; // tslint:disable: max-line-length /** * Specification of the desired behavior of the pod. * More Info: {@link https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status} */ // tslint:enable: max-line-length spec: PodSpec; } /** * ObjectReference from k8s API * * @public */ export interface ObjectReference { /** * If referring to a piece of an object instead of an entire object, * this string should contain a valid JSON/Go field access statement, * such as desiredState.manifest.containers[2]. * * For example, if the object reference is to a container within a pod, * this would take on a value like: "spec.containers\{name\}" (where "name" * refers to the name of the container that triggered the event) or if no * container name is specified "spec.containers[2]" * (container with index 2 in this pod). * This syntax is chosen only to have some well-defined way of referencing a * part of an object. */ fieldPath: string; /** * Name of the referent. * * More info: {@link https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names} * */ name: string; /** * Namespace of the referent. * * More info: {@link https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/} */ namespace: string; // tslint:disable: max-line-length /** * Specific resourceVersion to which this reference is made, if any. * * More info: {@link https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency} */ // tslint:enable: max-line-length resourceVersion: string; /** * UID of the referent. * * More info: {@link https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids} */ uid: string; }
the_stack
import * as E from 'fp-ts/Either' import * as M from 'fp-ts/Monoid' import * as O from 'fp-ts/Option' import * as RA from 'fp-ts/ReadonlyArray' import * as RTE from 'fp-ts/ReaderTaskEither' import * as TE from 'fp-ts/TaskEither' import { constVoid, Endomorphism, flow, pipe } from 'fp-ts/function' import * as TD from 'io-ts/TaskDecoder' import * as path from 'path' import * as Config from './Config' import { Example } from './Example' import { File, FileSystem } from './FileSystem' import { Logger } from './Logger' import { printModule } from './Markdown' import { Documentable, Module } from './Module' import * as P from './Parser' const CONFIG_FILE_NAME = 'docs-ts.json' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 0.6.0 */ export interface Capabilities { readonly example: Example readonly fileSystem: FileSystem readonly logger: Logger readonly ast: P.Ast } /** * @category model * @since 0.6.0 */ export interface Effect<A> extends RTE.ReaderTaskEither<Capabilities, string, A> {} /** * @category model * @since 0.6.0 */ export interface Environment extends Capabilities { readonly settings: Config.Settings } /** * @category model * @since 0.6.0 */ export interface Program<A> extends RTE.ReaderTaskEither<Environment, string, A> {} // ------------------------------------------------------------------------------------- // decoders // ------------------------------------------------------------------------------------- interface PackageJSON { readonly name: string readonly homepage: string } const PackageJSONDecoder = pipe(TD.type({ name: TD.string }), TD.intersect(TD.partial({ homepage: TD.string }))) // ------------------------------------------------------------------------------------- // files // ------------------------------------------------------------------------------------- const readFile = (path: string): Effect<File> => pipe( RTE.ask<Capabilities>(), RTE.chainTaskEitherK(({ fileSystem }) => fileSystem.readFile(path)), RTE.map((content) => File(path, content, false)) ) const readFiles: (paths: ReadonlyArray<string>) => Effect<ReadonlyArray<File>> = RA.traverse(RTE.ApplicativePar)( readFile ) const writeFile = (file: File): Effect<void> => { const overwrite: Effect<void> = pipe( RTE.ask<Capabilities>(), RTE.chainTaskEitherK(({ fileSystem, logger }) => pipe( logger.debug(`Overwriting file ${file.path}`), TE.chain(() => fileSystem.writeFile(file.path, file.content)) ) ) ) const skip: Effect<void> = pipe( RTE.ask<Capabilities>(), RTE.chainTaskEitherK(({ logger }) => logger.debug(`File ${file.path} already exists, skipping creation`)) ) const write: Effect<void> = pipe( RTE.ask<Capabilities>(), RTE.chainTaskEitherK(({ fileSystem }) => fileSystem.writeFile(file.path, file.content)) ) return pipe( RTE.ask<Capabilities>(), RTE.chain(({ fileSystem }) => RTE.fromTaskEither(fileSystem.exists(file.path))), RTE.chain((exists) => (exists ? (file.overwrite ? overwrite : skip) : write)) ) } const writeFiles: (files: ReadonlyArray<File>) => Effect<void> = flow( RA.traverse(RTE.ApplicativePar)(writeFile), RTE.map(constVoid) ) const readPackageJSON: Effect<PackageJSON> = pipe( RTE.ask<Capabilities>(), RTE.chainTaskEitherK(({ fileSystem, logger }) => pipe( fileSystem.readFile(path.join(process.cwd(), 'package.json')), TE.mapLeft(() => `Unable to read package.json in "${process.cwd()}"`), TE.chainEitherK((json) => E.parseJSON( json, flow(E.toError, (err) => String(err.message)) ) ), TE.chain((json) => pipe( PackageJSONDecoder.decode(json), TE.mapLeft((decodeError) => `Unable to decode package.json:\n${TD.draw(decodeError)}`) ) ), TE.chain(({ name, homepage }) => pipe( logger.debug(`Project name detected: ${name}`), TE.chain(() => pipe( O.fromNullable(homepage), TE.fromOption(() => `Missing homepage in package.json`), TE.map((homepage) => ({ name, homepage })) ) ) ) ) ) ) ) const readSourcePaths: Program<ReadonlyArray<string>> = pipe( RTE.ask<Environment, string>(), RTE.chainTaskEitherK(({ fileSystem, logger, settings }) => pipe( fileSystem.search(path.join(settings.srcDir, '**', '*.ts'), settings.exclude), TE.map(RA.map(path.normalize)), TE.chainFirst((paths) => pipe(logger.info(`Found ${paths.length} modules`))) ) ) ) const readSourceFiles: Program<ReadonlyArray<File>> = pipe( RTE.ask<Environment, string>(), RTE.chain((C) => pipe( readSourcePaths, RTE.chainTaskEitherK((paths) => pipe(C, readFiles(paths))) ) ) ) // ------------------------------------------------------------------------------------- // parsers // ------------------------------------------------------------------------------------- const parseFiles = (files: ReadonlyArray<File>): Program<ReadonlyArray<Module>> => pipe( RTE.ask<Environment, string>(), RTE.chainFirst(({ logger }) => RTE.fromTaskEither(logger.debug('Parsing files...'))), RTE.chain(() => P.parseFiles(files)) ) // ------------------------------------------------------------------------------------- // examples // ------------------------------------------------------------------------------------- const foldFiles = M.fold(RA.getMonoid<File>()) const getExampleFiles = (modules: ReadonlyArray<Module>): Program<ReadonlyArray<File>> => pipe( RTE.ask<Environment, string>(), RTE.map((env) => pipe( modules, RA.chain((module) => { const prefix = module.path.join('-') const getDocumentableExamples = (id: string) => (documentable: Documentable): ReadonlyArray<File> => pipe( documentable.examples, RA.mapWithIndex((i, content) => File( path.join(env.settings.outDir, 'examples', `${prefix}-${id}-${documentable.name}-${i}.ts`), `${content}\n`, true ) ) ) const moduleExamples = getDocumentableExamples('module')(module) const methods = pipe( module.classes, RA.chain((c) => foldFiles([ pipe(c.methods, RA.chain(getDocumentableExamples(`${c.name}-method`))), pipe(c.staticMethods, RA.chain(getDocumentableExamples(`${c.name}-staticmethod`))) ]) ) ) const interfaces = pipe(module.interfaces, RA.chain(getDocumentableExamples('interface'))) const typeAliases = pipe(module.typeAliases, RA.chain(getDocumentableExamples('typealias'))) const constants = pipe(module.constants, RA.chain(getDocumentableExamples('constant'))) const functions = pipe(module.functions, RA.chain(getDocumentableExamples('function'))) return foldFiles([moduleExamples, methods, interfaces, typeAliases, constants, functions]) }) ) ) ) const addAssertImport = (code: string): string => code.indexOf('assert.') !== -1 ? `import * as assert from 'assert'\n${code}` : code const replaceProjectName = (source: string): Program<string> => pipe( RTE.ask<Environment>(), RTE.map(({ settings }) => { const importRegex = (projectName: string) => new RegExp(`from (?<quote>['"])${projectName}(?:\/lib)?(?:\/(?<path>.*))?\\k<quote>`, 'g') return source.replace(importRegex(settings.projectName), (...args) => { const groups: { path?: string } = args[args.length - 1] return `from '../../src${Boolean(groups.path) ? `/${groups.path}` : ''}'` }) }) ) const handleImports: (files: ReadonlyArray<File>) => Program<ReadonlyArray<File>> = RA.traverse(RTE.ApplicativePar)( (file) => pipe( replaceProjectName(file.content), RTE.map(addAssertImport), RTE.map((content) => File(file.path, content, file.overwrite)) ) ) const getExampleIndex = (examples: ReadonlyArray<File>): Program<File> => { const content = pipe( examples, RA.foldMap(M.monoidString)((example) => `import './${path.basename(example.path)}'\n`) ) return pipe( RTE.ask<Environment, string>(), RTE.map((env) => File(path.join(env.settings.outDir, 'examples', 'index.ts'), `${content}\n`, true)) ) } const cleanExamples: Program<void> = pipe( RTE.ask<Environment, string>(), RTE.chainTaskEitherK(({ fileSystem, settings }) => fileSystem.remove(path.join(settings.outDir, 'examples'))) ) const spawnTsNode: Program<void> = pipe( RTE.ask<Environment, string>(), RTE.chainFirst(({ logger }) => RTE.fromTaskEither(logger.debug('Type checking examples...'))), RTE.chainTaskEitherK(({ example, settings }) => { const command = process.platform === 'win32' ? 'ts-node.cmd' : 'ts-node' const executablePath = path.join(process.cwd(), settings.outDir, 'examples', 'index.ts') return example.run(command, executablePath) }) ) const writeExamples = (examples: ReadonlyArray<File>): Program<void> => pipe( RTE.ask<Environment, string>(), RTE.chainFirst(({ logger }) => RTE.fromTaskEither(logger.debug('Writing examples...'))), RTE.chain((C) => pipe( getExampleIndex(examples), RTE.map((index) => RA.cons(index, examples)), RTE.chainTaskEitherK((files) => pipe(C, writeFiles(files))) ) ) ) const typeCheckExamples = (modules: ReadonlyArray<Module>): Program<void> => pipe( getExampleFiles(modules), RTE.chain(handleImports), RTE.chain((examples) => examples.length === 0 ? cleanExamples : pipe( writeExamples(examples), RTE.chain(() => spawnTsNode), RTE.chain(() => cleanExamples) ) ) ) // ------------------------------------------------------------------------------------- // markdown // ------------------------------------------------------------------------------------- const getHome: Program<File> = pipe( RTE.ask<Environment, string>(), RTE.map(({ settings }) => File( path.join(process.cwd(), settings.outDir, 'index.md'), `--- title: Home nav_order: 1 --- `, false ) ) ) const getModulesIndex: Program<File> = pipe( RTE.ask<Environment, string>(), RTE.map(({ settings }) => File( path.join(process.cwd(), settings.outDir, 'modules', 'index.md'), `--- title: Modules has_children: true permalink: /docs/modules nav_order: 2 ---`, false ) ) ) const replace = (searchValue: string | RegExp, replaceValue: string): Endomorphism<string> => (s) => s.replace(searchValue, replaceValue) /* tslint:disable:no-regex-spaces */ const resolveConfigYML = (previousContent: string, settings: Config.Settings): string => pipe( previousContent, replace(/^remote_theme:.*$/m, `remote_theme: ${settings.theme}`), replace(/^search_enabled:.*$/m, `search_enabled: ${settings.enableSearch}`), replace( /^ '\S* on GitHub':\n - '.*'/m, ` '${settings.projectName} on GitHub':\n - '${settings.projectHomepage}'` ) ) /* tslint:enable:no-regex-spaces */ const getHomepageNavigationHeader = (settings: Config.Settings): string => { const isGitHub = settings.projectHomepage.toLowerCase().includes('github') return isGitHub ? settings.projectName + ' on GitHub' : 'Homepage' } const getConfigYML: Program<File> = pipe( RTE.ask<Environment, string>(), RTE.chainTaskEitherK(({ fileSystem, settings }) => { const filePath = path.join(process.cwd(), settings.outDir, '_config.yml') return pipe( fileSystem.exists(filePath), TE.chain((exists) => exists ? pipe( fileSystem.readFile(filePath), TE.map((content) => File(filePath, resolveConfigYML(content, settings), true)) ) : TE.of( File( filePath, `remote_theme: ${settings.theme} # Enable or disable the site search search_enabled: ${settings.enableSearch} # Aux links for the upper right navigation aux_links: '${getHomepageNavigationHeader(settings)}': - '${settings.projectHomepage}'`, false ) ) ) ) }) ) const getMarkdownOutputPath = (module: Module): Program<string> => pipe( RTE.ask<Environment, string>(), RTE.map(({ settings }) => path.join(settings.outDir, 'modules', `${module.path.slice(1).join(path.sep)}.md`)) ) const getModuleMarkdownFiles = (modules: ReadonlyArray<Module>): Program<ReadonlyArray<File>> => pipe( modules, RTE.traverseArrayWithIndex((order, module) => pipe( getMarkdownOutputPath(module), RTE.bindTo('outputPath'), RTE.bind('content', () => RTE.right(printModule(module, order + 1))), RTE.map(({ content, outputPath }) => File(outputPath, content, true)) ) ) ) const getMarkdownFiles = (modules: ReadonlyArray<Module>): Program<ReadonlyArray<File>> => pipe( RTE.sequenceArray([getHome, getModulesIndex, getConfigYML]), RTE.chain((meta) => pipe( getModuleMarkdownFiles(modules), RTE.map((files) => RA.getMonoid<File>().concat(meta, files)) ) ) ) const writeMarkdownFiles = (files: ReadonlyArray<File>): Program<void> => pipe( RTE.ask<Environment, string>(), RTE.chainFirst<Environment, string, Environment, void>(({ fileSystem, logger, settings }) => { const outPattern = path.join(settings.outDir, '**/*.ts.md') return pipe( logger.debug(`Cleaning up docs folder: deleting ${outPattern}`), TE.chain(() => fileSystem.remove(outPattern)), RTE.fromTaskEither ) }), RTE.chainTaskEitherK((C) => pipe( C.logger.debug('Writing markdown files...'), TE.chain(() => pipe(C, writeFiles(files))) ) ) ) // ------------------------------------------------------------------------------------- // config // ------------------------------------------------------------------------------------- const getDefaultSettings = (projectName: string, projectHomepage: string): Config.Settings => pipe(Config.build(projectName, projectHomepage), Config.resolveSettings) const hasConfiguration: Effect<boolean> = pipe( RTE.ask<Capabilities>(), RTE.chainTaskEitherK(({ fileSystem, logger }) => pipe( logger.debug('Checking for configuration file...'), TE.chain(() => fileSystem.exists(path.join(process.cwd(), CONFIG_FILE_NAME))) ) ) ) const readConfiguration: Effect<File> = pipe( RTE.ask<Capabilities>(), RTE.chain(() => readFile(path.join(process.cwd(), CONFIG_FILE_NAME))) ) const parseConfiguration = (defaultSettings: Config.Settings) => (file: File): Effect<Config.Settings> => pipe( RTE.ask<Capabilities>(), RTE.chainTaskEitherK(({ logger }) => pipe( E.parseJSON(file.content, toErrorMsg), TE.fromEither, TE.chainFirst(() => logger.info(`Found configuration file`)), TE.chainFirst(() => logger.debug(`Parsing configuration file found at: ${file.path}`)), TE.chain(Config.decode), TE.bimap( (decodeError) => `Invalid configuration file detected:\n${decodeError}`, (settings) => ({ ...defaultSettings, ...settings }) ) ) ) ) const useDefaultSettings = (defaultSettings: Config.Settings): Effect<Config.Settings> => pipe( RTE.ask<Capabilities>(), RTE.chainTaskEitherK(({ logger }) => pipe( logger.info('No configuration file detected, using default settings'), TE.map(() => defaultSettings) ) ) ) const getDocsConfiguration = (projectName: string, projectHomepage: string): Effect<Config.Settings> => pipe( hasConfiguration, RTE.bindTo('hasConfig'), RTE.bind('defaultSettings', () => RTE.right(getDefaultSettings(projectName, projectHomepage))), RTE.chain(({ defaultSettings, hasConfig }) => hasConfig ? pipe(readConfiguration, RTE.chain(parseConfiguration(defaultSettings))) : useDefaultSettings(defaultSettings) ) ) // ------------------------------------------------------------------------------------- // program // ------------------------------------------------------------------------------------- /** * @category program * @since 0.6.0 */ export const main: Effect<void> = pipe( RTE.ask<Capabilities>(), RTE.chain((capabilities) => pipe( readPackageJSON, RTE.chain((pkg) => pipe( getDocsConfiguration(pkg.name, pkg.homepage), RTE.chainTaskEitherK((settings) => { const program = pipe( readSourceFiles, RTE.chain(parseFiles), RTE.chainFirst(typeCheckExamples), RTE.chain(getMarkdownFiles), RTE.chain(writeMarkdownFiles) ) return program({ ...capabilities, settings }) }) ) ) ) ) ) // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- const toErrorMsg: (u: unknown) => string = flow(E.toError, (err) => String(err.message))
the_stack
import { transfer } from 'comlink'; import { RemoteReadableStream, RemoteWritableStream, } from '@transcend-io/remote-web-streams'; import streamSaver from 'streamsaver'; import mime from 'mime-types'; import { ReadableStream, WritableStreamIsNative, WritableStreamPonyfill, } from './streams'; // Local import { JobCompletionEmit, PenumbraDecryptionInfo, PenumbraEncryptedFile, PenumbraEncryptionOptions, PenumbraFile, PenumbraFileWithID, PenumbraTextOrURI, PenumbraWorkerAPI, RemoteResource, ZipOptions, } from './types'; import { PenumbraZipWriter } from './zip'; import { blobCache, isNumber, isViewableText } from './utils'; import { getWorker, setWorkerLocation } from './workers'; import { advancedStreamsSupported, supported } from './ua-support'; import { preconnect, preload } from './resource-hints'; const resolver = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'a', ) as HTMLAnchorElement; const { createWriteStream } = streamSaver; if (!WritableStreamIsNative) { // eslint-disable-next-line @typescript-eslint/no-explicit-any (streamSaver as any).WritableStream = WritableStreamPonyfill; } /** * Retrieve and decrypt files (batch job) */ async function getJob(...resources: RemoteResource[]): Promise<PenumbraFile[]> { if (resources.length === 0) { throw new Error('penumbra.get() called without arguments'); } if (advancedStreamsSupported) { // WritableStream constructor supported const worker = await getWorker(); const DecryptionChannel = worker.comlink; const remoteStreams = resources.map(() => new RemoteReadableStream()); const readables = remoteStreams.map((stream, i) => { const { url } = resources[i]; resolver.href = url; const path = resolver.pathname; // derive path from URL return { path, // derived path is overridden if PenumbraFile contains path ...resources[i], stream: stream.readable, }; }); const writablePorts = remoteStreams.map(({ writablePort }) => writablePort); new DecryptionChannel().then((thread: PenumbraWorkerAPI) => { thread.get(transfer(writablePorts, writablePorts), resources); }); return readables as PenumbraFile[]; } const { fetchAndDecrypt } = await import('./crypto'); /** * Fetch remote files from URLs, decipher them (if encrypted), * fully buffer the response, and return ArrayBuffer[] */ const decryptedFiles: PenumbraFile[] = await Promise.all( resources.map(async (resource) => { if (!('url' in resource)) { throw new Error('penumbra.get(): RemoteResource missing URL'); } return { ...resource, stream: await fetchAndDecrypt(resource), } as PenumbraFile; }), ); return decryptedFiles; } /** * penumbra.get() API * * ```ts * // Load a resource and get a ReadableStream * await penumbra.get(resource); * * // Buffer all responses & read them as text * await Promise.all((await penumbra.get(resources)).map(({ stream }) => * new Response(stream).text() * )); * * // Buffer a response & read as text * await new Response((await penumbra.get(resource))[0].stream).text(); * * // Example call with an included resource * await penumbra.get({ * url: 'https://s3-us-west-2.amazonaws.com/bencmbrook/NYT.txt.enc', * filePrefix: 'NYT', * mimetype: 'text/plain', * decryptionOptions: { * key: 'vScyqmJKqGl73mJkuwm/zPBQk0wct9eQ5wPE8laGcWM=', * iv: '6lNU+2vxJw6SFgse', * authTag: 'gadZhS1QozjEmfmHLblzbg==', * }, * }); * ``` */ export function get(...resources: RemoteResource[]): Promise<PenumbraFile[]> { return Promise.all( resources.map(async (resource) => (await getJob(resource))[0]), ); } const DEFAULT_FILENAME = 'download'; const DEFAULT_MIME_TYPE = 'application/octet-stream'; /** Maximum allowed resource size for encrypt/decrypt on the main thread */ const MAX_ALLOWED_SIZE_MAIN_THREAD = 32 * 1024 * 1024; // 32 MiB /** * Save a zip containing files retrieved by Penumbra * * @param options - ZipOptions * @returns PenumbraZipWriter class instance */ function saveZip(options?: ZipOptions): PenumbraZipWriter { return new PenumbraZipWriter(options); } /** * Save files retrieved by Penumbra * * @param data - The data files to save * @param fileName - The name of the file to save to * @returns AbortController */ function save( files: PenumbraFile[], fileName?: string, controller = new AbortController(), ): AbortController { let size: number | undefined = 0; // eslint-disable-next-line no-restricted-syntax for (const file of files) { if (!isNumber(file.size)) { size = undefined; break; } size += file.size; } // Multiple files if ('length' in files && files.length > 1) { const writer = saveZip({ name: fileName || `${DEFAULT_FILENAME}.zip`, size, files, controller, }); writer.write(...files); return controller; } // Single file const file: PenumbraFile = 'stream' in files ? files : files[0]; const [ filename, extension = file.mimetype ? mime.extension(file.mimetype) : '', ] = (fileName || file.filePrefix || DEFAULT_FILENAME) .split(/(\.\w+\s*$)/) // split filename extension .filter(Boolean); // filter empty matches const singleFileName = `${filename}${extension}`; const { signal } = controller; // Write a single readable stream to file file.stream.pipeTo(createWriteStream(singleFileName), { signal, }); return controller; } /** * Load files retrieved by Penumbra into memory as a Blob * * @param data - The data to load * @returns A blob of the data */ function getBlob( files: PenumbraFile[] | PenumbraFile | ReadableStream, type?: string, // = data[0].mimetype ): Promise<Blob> { if ('length' in files && files.length > 1) { throw new Error('penumbra.getBlob(): Called with multiple files'); } let rs: ReadableStream; let fileType: string | undefined; if (files instanceof ReadableStream) { rs = files; } else { const file = 'length' in files ? files[0] : files; if (file.stream instanceof ArrayBuffer || ArrayBuffer.isView(file.stream)) { return Promise.resolve( new Blob( [ new Uint8Array( file.stream as ArrayBufferLike, 0, file.stream.byteLength, ), ], { type: file.mimetype }, ), ); } rs = file.stream; fileType = file.mimetype; } const headers = new Headers({ 'Content-Type': type || fileType || DEFAULT_MIME_TYPE, }); return new Response(rs, { headers }).blob(); } let jobID = 0; const decryptionConfigs = new Map<string | number, PenumbraDecryptionInfo>(); const trackJobCompletion = ( searchForID: string | number, ): Promise<PenumbraDecryptionInfo> => new Promise((complete) => { const listener = ({ type, detail: { id, decryptionInfo }, }: JobCompletionEmit): void => { decryptionConfigs.set(id, decryptionInfo); if (typeof searchForID !== 'undefined' && `${id}` === `${searchForID}`) { // eslint-disable-next-line @typescript-eslint/no-explicit-any (self.removeEventListener as any)(type, listener); complete(decryptionInfo); } }; self.addEventListener('penumbra-complete', listener); }); /** * Get the decryption config for an encrypted file * * ```ts * penumbra.getDecryptionInfo(file: PenumbraEncryptedFile): Promise<PenumbraDecryptionInfo> * ``` */ export async function getDecryptionInfo( file: PenumbraEncryptedFile, ): Promise<PenumbraDecryptionInfo> { const { id } = file; if (!decryptionConfigs.has(id)) { // decryption config not yet received. waiting for event with promise return trackJobCompletion(id); } return decryptionConfigs.get(id) as PenumbraDecryptionInfo; } /** * Encrypt files (batch job) */ async function encryptJob( options: PenumbraEncryptionOptions | null, ...files: PenumbraFile[] ): Promise<PenumbraEncryptedFile[]> { // Ensure a file is passed if (files.length === 0) { throw new Error('penumbra.encrypt() called without arguments'); } // collect file sizes and assign job IDs for completion tracking const ids: number[] = []; const sizes: number[] = []; files.forEach((file) => { // eslint-disable-next-line no-plusplus, no-param-reassign ids.push((file.id = jobID++)); const { size } = file; if (size) { sizes.push(size); } else { throw new Error('penumbra.encrypt(): Unable to determine file size'); } }); // We stream the encryption if supported by the browser if (advancedStreamsSupported) { // WritableStream constructor supported const worker = await getWorker(); const EncryptionChannel = worker.comlink; const remoteReadableStreams = files.map(() => new RemoteReadableStream()); const remoteWritableStreams = files.map(() => new RemoteWritableStream()); // extract ports from remote readable/writable streams for Comlink.transfer const readablePorts = remoteWritableStreams.map( ({ readablePort }) => readablePort, ); const writablePorts = remoteReadableStreams.map( ({ writablePort }) => writablePort, ); // enter worker thread and grab the metadata await (new EncryptionChannel() as Promise<PenumbraWorkerAPI>).then( /** * PenumbraWorkerAPI.encrypt calls require('./encrypt').encrypt() * from the worker thread and starts reading the input stream from * [remoteWritableStream.writable] */ (thread) => { thread.encrypt( options, ids, sizes, transfer(readablePorts, readablePorts), transfer(writablePorts, writablePorts), ); }, ); // encryption jobs submitted and still processing remoteWritableStreams.forEach((remoteWritableStream, i) => { files[i].stream.pipeTo(remoteWritableStream.writable); }); // construct output files with corresponding remote readable streams const readables = remoteReadableStreams.map( (stream, i): PenumbraEncryptedFile => ({ ...files[i], // iv: metadata[i].iv, stream: stream.readable, size: sizes[i], id: ids[i], }), ); return readables; } // throw new Error( // "Your browser doesn't support streaming encryption. Buffered encryption is not yet supported.", // ); const filesWithIds = files as PenumbraFileWithID[]; let totalSize = 0; filesWithIds.forEach(({ size = 0 }) => { totalSize += size; if (totalSize > MAX_ALLOWED_SIZE_MAIN_THREAD) { console.error(`Your browser doesn't support streaming encryption.`); throw new Error( 'penumbra.encrypt(): File is too large to encrypt without writable streams', ); } }); const { encrypt: encryptFile } = await import('./crypto'); const encryptedFiles = await Promise.all( filesWithIds.map( (file): PenumbraEncryptedFile => { const { stream } = encryptFile(options, file, file.size as number); return { ...file, ...options, stream, }; }, ), ); return encryptedFiles; } /** * penumbra.encrypt() API * * ```ts * await penumbra.encrypt(options, ...files); * // usage example: * size = 4096 * 64 * 64; * addEventListener('penumbra-progress',(e)=>console.log(e.type, e.detail)); * addEventListener('penumbra-complete',(e)=>console.log(e.type, e.detail)); * file = penumbra.encrypt(null, {stream: new Uint8Array(size), size}); * let data = []; * file.then(async ([encrypted]) => { * console.log('encryption started'); * data.push(new Uint8Array(await new Response(encrypted.stream).arrayBuffer())); * }); * ``` */ export function encrypt( options: PenumbraEncryptionOptions | null, ...files: PenumbraFile[] ): Promise<PenumbraEncryptedFile[]> { return Promise.all( files.map(async (file) => (await encryptJob(options, file))[0]), ); } /** * Decrypt files encrypted by penumbra.encrypt() (batch job) */ async function decryptJob( options: PenumbraDecryptionInfo, ...files: PenumbraEncryptedFile[] ): Promise<PenumbraFile[]> { if (files.length === 0) { throw new Error('penumbra.decrypt() called without arguments'); } if (advancedStreamsSupported) { // WritableStream constructor supported const worker = await getWorker(); const DecryptionChannel = worker.comlink; const remoteReadableStreams = files.map(() => new RemoteReadableStream()); const remoteWritableStreams = files.map(() => new RemoteWritableStream()); const ids: number[] = []; const sizes: number[] = []; // collect file sizes and assign job IDs for completion tracking files.forEach((file) => { // eslint-disable-next-line no-plusplus, no-param-reassign ids.push((file.id = file.id || jobID++)); const { size } = file; if (size) { sizes.push(size); } else { throw new Error('penumbra.decrypt(): Unable to determine file size'); } }); // extract ports from remote readable/writable streams for Comlink.transfer const readablePorts = remoteWritableStreams.map( ({ readablePort }) => readablePort, ); const writablePorts = remoteReadableStreams.map( ({ writablePort }) => writablePort, ); // enter worker thread await new DecryptionChannel().then((thread: PenumbraWorkerAPI) => { /** * PenumbraWorkerAPI.decrypt calls require('./decrypt').decrypt() * from the worker thread and starts reading the input stream from * [remoteWritableStream.writable] */ thread.decrypt( options, ids, sizes, transfer(readablePorts, readablePorts), transfer(writablePorts, writablePorts), ); }); // decryption jobs submitted and still processing remoteWritableStreams.forEach((remoteWritableStream, i) => { files[i].stream.pipeTo(remoteWritableStream.writable); }); // construct output files with corresponding remote readable streams const readables: PenumbraEncryptedFile[] = remoteReadableStreams.map( (stream, i): PenumbraEncryptedFile => ({ ...files[i], size: sizes[i], id: ids[i], stream: stream.readable, }), ); return readables; } files.forEach(({ size = 0 }) => { if (size > MAX_ALLOWED_SIZE_MAIN_THREAD) { console.error(`Your browser doesn't support streaming decryption.`); throw new Error( 'penumbra.decrypt(): File is too large to decrypt without writable streams', ); } }); // Buffered worker solution: // let decryptedFiles: PenumbraFile[] = await new DecryptionChannel().then( // async (thread: PenumbraWorkerAPI) => { // const buffers = await thread.getBuffers(options, files); // decryptedFiles = buffers.map((stream, i) => ({ // stream, // ...files[i], // })); // return decryptedFiles; // }, // ); const { decrypt: decryptFile } = await import('./crypto'); const decryptedFiles: PenumbraFile[] = files.map((file) => decryptFile(options, file, file.size as number), ); return decryptedFiles; } /** * penumbra.decrypt() API * * Decrypts files encrypted by penumbra.encrypt() * * ```ts * await penumbra.decrypt(options, ...files); * // usage example: * size = 4096 * 64 * 64; * addEventListener('penumbra-progress',(e)=>console.log(e.type, e.detail)); * addEventListener('penumbra-complete',(e)=>console.log(e.type, e.detail)); * file = penumbra.encrypt(null, {stream: new Uint8Array(size), size}); * let data = []; * file.then(async ([encrypted]) => { * console.log('encryption started'); * data.push(new Uint8Array(await new Response(encrypted.stream).arrayBuffer())); * }); */ export function decrypt( options: PenumbraDecryptionInfo, ...files: PenumbraEncryptedFile[] ): Promise<PenumbraFile[]> { return Promise.all( files.map(async (file) => (await decryptJob(options, file))[0]), ); } /** * Get file text (if content is viewable) or URI (if content is not viewable) * * @param files - A list of files to get the text of * @returns A list with the text itself or a URI encoding the file if applicable */ function getTextOrURI(files: PenumbraFile[]): Promise<PenumbraTextOrURI>[] { return files.map( async (file): Promise<PenumbraTextOrURI> => { const { mimetype = '' } = file; if (mimetype && isViewableText(mimetype)) { return { type: 'text', data: await new Response(file.stream).text(), mimetype, }; } const url = URL.createObjectURL(await getBlob(file)); const cache = blobCache.get(); cache.push(new URL(url)); blobCache.set(cache); return { type: 'uri', data: url, mimetype }; }, ); } const penumbra = { preconnect, preload, get, encrypt, decrypt, getDecryptionInfo, save, supported, getBlob, getTextOrURI, saveZip, setWorkerLocation, }; export default penumbra;
the_stack
// Add Functor into Kernel Call (done) /** * @file * kernel.cuh * * @brief Forward Edge Map Kernel Entrypoint */ #pragma once #include <gunrock/util/cta_work_distribution.cuh> #include <gunrock/util/cta_work_progress.cuh> #include <gunrock/util/kernel_runtime_stats.cuh> #include <gunrock/oprtr/TWC_advance/kernel_policy.cuh> #include <gunrock/oprtr/TWC_advance/cta.cuh> namespace gunrock { namespace oprtr { namespace TWC { /** * Arch dispatch */ /** * Not valid for this arch (default) * @tparam FLAG Operator flags * @tparam GraphT Graph type * @tparam InKeyT Input keys type * @tparam OutKeyT Output keys type * @tparam VALID */ template <OprtrFlag FLAG, typename GraphT, typename InKeyT, typename OutKeyT, bool VALID = #ifdef __CUDA_ARCH__ true #else false #endif > struct Dispatch { }; /** * @brief Kernel dispatch code for different architectures. * @tparam FLAG Operator flags * @tparam GraphT Graph type * @tparam InKeyT Input keys type * @tparam OutKeyT Output keys type */ template <OprtrFlag FLAG, typename GraphT, typename InKeyT, typename OutKeyT> struct Dispatch<FLAG, GraphT, InKeyT, OutKeyT, true> { typedef typename GraphT::VertexT VertexT; typedef typename GraphT::SizeT SizeT; typedef typename GraphT::ValueT ValueT; typedef KernelPolicy<FLAG, VertexT, InKeyT, OutKeyT, SizeT, ValueT, // Data types 8, // int _MIN_CTA_OCCUPANCY, // Tunable parameters 7, // int _LOG_THREADS, 1, // int _LOG_LOAD_VEC_SIZE, 1, // int _LOG_LOADS_PER_TILE, 5, // int _LOG_RAKING_THREADS, 32, // int _WARP_GATHER_THRESHOLD, 128 * 4, // int _CTA_GATHER_THRESHOLD> 7> // int _LOG_SCHEDULE_GRANULARITY KernelPolicyT; typedef Cta<GraphT, KernelPolicyT> CtaT; template <typename AdvanceOpT> static __device__ __forceinline__ void Kernel( const GraphT &graph, const InKeyT *&keys_in, const SizeT &num_inputs, const VertexT &queue_index, // const SizeT *&output_offsets, // const SizeT *&block_input_starts, // const SizeT &partition_size, // const SizeT &num_partitions, OutKeyT *&keys_out, ValueT *&values_out, const SizeT &num_outputs, util::CtaWorkProgress<SizeT> &work_progress, // const ValueT *&reduce_values_in, // ValueT *&reduce_values_out, AdvanceOpT advance_op) { // Shared storage for the kernel __shared__ typename KernelPolicyT::SmemStorage smem_storage; // Determine work decomposition if (threadIdx.x == 0) { // Initialize work decomposition in smem smem_storage.state.work_decomposition .template Init<KernelPolicyT::LOG_SCHEDULE_GRANULARITY>(num_inputs, gridDim.x); } // Barrier to protect work decomposition __syncthreads(); // Determine threadblock's work range util::CtaWorkLimits<SizeT> work_limits; smem_storage.state.work_decomposition .template GetCtaWorkLimits<KernelPolicyT::LOG_TILE_ELEMENTS, KernelPolicyT::LOG_SCHEDULE_GRANULARITY>( work_limits); // Return if we have no work to do if (!work_limits.elements) { return; } // CTA processing abstraction // Cta cta( // queue_reset, // queue_index, // label, // d_row_offsets, // d_inverse_row_offsets, // d_column_indices, // d_inverse_column_indices, // d_keys_in, // d_keys_out, // d_values_out, // d_data_slice, // input_queue_length, // max_in_frontier, // max_out_frontier, // work_progress, // smem_storage, // //ADVANCE_TYPE, // input_inverse_graph, // //R_TYPE, // //R_OP, // d_value_to_reduce, // d_reduce_frontier); CtaT cta(graph, keys_in, num_inputs, keys_out, values_out, queue_index, // reduce_values_in, reduce_values_out, work_progress, smem_storage); // Process full tiles while (work_limits.offset < work_limits.guarded_offset) { cta.ProcessTile(work_limits.offset, KernelPolicyT::TILE_ELEMENTS, advance_op); work_limits.offset += KernelPolicyT::TILE_ELEMENTS; } // Clean up last partial tile with guarded-i/o if (work_limits.guarded_elements) { cta.ProcessTile(work_limits.offset, work_limits.guarded_elements, advance_op); } } }; /** * @brief Forward edge map kernel entry point. * * @tparam KernelPolicy Kernel policy type for forward edge mapping. * @tparam ProblemData Problem data type for forward edge mapping. * @tparam Functor Functor type for the specific problem type. * * @param[in] queue_reset If reset queue counter * @param[in] queue_index Current frontier queue counter index * @param[in] label Distance from source (label) of current frontier * @param[in] num_elements Number of elements * @param[in] d_in_queue Device pointer of VertexId to the incoming * frontier queue * @param[in] d_pred_out Device pointer of VertexId to the outgoing * predecessor queue (only used when both mark_pred and enable_idempotence are * set) * @param[in] d_out_queue Device pointer of VertexId to the outgoing * frontier queue * @param[in] d_column_indices Device pointer of VertexId to the column indices * queue * @param[in] problem Device pointer to the problem object * @param[in] work_progress queueing counters to record work progress * @param[in] max_in_queue Maximum number of elements we can place into the * incoming frontier * @param[in] max_out_queue Maximum number of elements we can place into the * outgoing frontier * @param[in] kernel_stats Per-CTA clock timing statistics (used when * KernelPolicy::INSTRUMENT is set) */ template <OprtrFlag FLAG, typename GraphT, typename InKeyT, typename OutKeyT, typename AdvanceOpT> __launch_bounds__( Dispatch<FLAG, GraphT, InKeyT, OutKeyT, true>::KernelPolicyT::THREADS, Dispatch<FLAG, GraphT, InKeyT, OutKeyT, true>::KernelPolicyT::CTA_OCCUPANCY) __global__ void Kernel(const bool queue_reset, const typename GraphT::VertexT queue_index, const GraphT graph, const InKeyT *keys_in, typename GraphT::SizeT num_inputs, // const typename GraphT::SizeT *output_offsets, // const typename GraphT::SizeT *block_input_starts, // const typename GraphT::SizeT partition_size, // const typename GraphT::SizeT num_partitions, OutKeyT *keys_out, typename GraphT::ValueT *values_out, typename GraphT::SizeT *num_outputs, util::CtaWorkProgress<typename GraphT::SizeT> work_progress, // util::KernelRuntimeStats kernel_stats, // const typename GraphT::ValueT *reduce_values_in , // typename GraphT::ValueT *reduce_values_out, AdvanceOpT advance_op) { PrepareQueue(queue_reset, queue_index, num_inputs, num_outputs, work_progress, true); Dispatch<FLAG, GraphT, InKeyT, OutKeyT>::Kernel( graph, keys_in, num_inputs, queue_index, // output_offsets, // block_input_starts, //partition_size, //num_partitions, keys_out, values_out, num_outputs[0], work_progress, // reduce_values_in, reduce_values_out, advance_op); } template <OprtrFlag FLAG, typename GraphT, typename FrontierInT, typename FrontierOutT, typename ParametersT, typename AdvanceOpT, typename FilterOpT> cudaError_t Launch_CSR_CSC(const GraphT &graph, const FrontierInT *frontier_in, FrontierOutT *frontier_out, ParametersT &parameters, AdvanceOpT advance_op, FilterOpT filter_op) { typedef typename GraphT::SizeT SizeT; typedef typename GraphT::ValueT ValueT; typedef typename FrontierInT ::ValueT InKeyT; typedef typename FrontierOutT::ValueT OutKeyT; typedef typename Dispatch<FLAG, GraphT, InKeyT, OutKeyT, true>::KernelPolicyT KernelPolicyT; cudaError_t retval = cudaSuccess; // load edge-expand-partitioned kernel if (parameters.get_output_length) { // util::PrintMsg("getting output length"); GUARD_CU(ComputeOutputLength<FLAG>(graph, frontier_in, parameters)); GUARD_CU(parameters.frontier->output_length.Move(util::DEVICE, util::HOST, 1, 0, parameters.stream)); GUARD_CU2(cudaStreamSynchronize(parameters.stream), "cudaStreamSynchronize failed"); // GUARD_CU2(cudaDeviceSynchronize(), // "cudaDeviceSynchronize failed"); } // int blocks = 1; // TODO: calculate number of blocks int num_blocks = (parameters.max_grid_size <= 0) ? parameters.cuda_props->device_props.multiProcessorCount * KernelPolicyT::CTA_OCCUPANCY : parameters.max_grid_size; Kernel<FLAG, GraphT, InKeyT, OutKeyT> <<<num_blocks, KernelPolicyT::THREADS, 0, parameters.stream>>>( parameters.frontier->queue_reset, parameters.frontier->queue_index, graph, (frontier_in == NULL) ? ((InKeyT *)NULL) : frontier_in->GetPointer(util::DEVICE), parameters.frontier->queue_length, (frontier_out == NULL) ? ((OutKeyT *)NULL) : frontier_out->GetPointer(util::DEVICE), (parameters.values_out == NULL) ? ((ValueT *)NULL) : parameters.values_out->GetPointer(util::DEVICE), parameters.frontier->output_length.GetPointer(util::DEVICE), parameters.frontier->work_progress, //(parameters.reduce_values_in == NULL) ? ((ValueT*)NULL) // : (parameters.reduce_values_in -> GetPointer(util::DEVICE)), //(parameters.reduce_values_out == NULL) ? ((ValueT*)NULL) // : (parameters.reduce_values_out -> GetPointer(util::DEVICE)), advance_op); if (frontier_out != NULL) { parameters.frontier->queue_index++; } return retval; } template <typename GraphT, bool VALID> struct GraphT_Switch { template <OprtrFlag FLAG, typename FrontierInT, typename FrontierOutT, typename ParametersT, typename AdvanceOpT, typename FilterOpT> static cudaError_t Launch_Csr_Csc(const GraphT &graph, const FrontierInT *frontier_in, FrontierOutT *frontier_out, ParametersT &parameters, AdvanceOpT advance_op, FilterOpT filter_op) { return util::GRError( cudaErrorInvalidDeviceFunction, "TWC is not implemented for given graph representation."); } }; template <typename GraphT> struct GraphT_Switch<GraphT, true> { template <OprtrFlag FLAG, typename FrontierInT, typename FrontierOutT, typename ParametersT, typename AdvanceOpT, typename FilterOpT> static cudaError_t Launch_Csr_Csc(const GraphT &graph, const FrontierInT *frontier_in, FrontierOutT *frontier_out, ParametersT &parameters, AdvanceOpT advance_op, FilterOpT filter_op) { return Launch_CSR_CSC<FLAG>(graph, frontier_in, frontier_out, parameters, advance_op, filter_op); } }; template <OprtrFlag FLAG, typename GraphT, typename FrontierInT, typename FrontierOutT, typename ParametersT, typename AdvanceOpT, typename FilterOpT> cudaError_t Launch(const GraphT &graph, const FrontierInT *frontier_in, FrontierOutT *frontier_out, ParametersT &parameters, AdvanceOpT advance_op, FilterOpT filter_op) { cudaError_t retval = cudaSuccess; if (GraphT::FLAG & gunrock::graph::HAS_CSR) retval = GraphT_Switch<GraphT, (GraphT::FLAG & gunrock::graph::HAS_CSR) != 0>:: template Launch_Csr_Csc<FLAG>(graph, frontier_in, frontier_out, parameters, advance_op, filter_op); else if (GraphT::FLAG & gunrock::graph::HAS_CSC) retval = GraphT_Switch<GraphT, (GraphT::FLAG & gunrock::graph::HAS_CSC) != 0>:: template Launch_Csr_Csc<FLAG>(graph, frontier_in, frontier_out, parameters, advance_op, filter_op); else retval = util::GRError(cudaErrorInvalidDeviceFunction, "TWC is not implemented for given graph representation."); return retval; } } // namespace TWC } // namespace oprtr } // namespace gunrock // Leave this at the end of the file // Local Variables: // mode:c++ // c-file-style: "NVIDIA" // End:
the_stack
static inline void THNN_(VolumetricConvolution_shapeCheck) (THCState *state, THCTensor *input, THCTensor *gradOutput, THCTensor *weight, THCTensor *gradWeight, THCTensor *bias, int dT, int dW, int dH, int padT, int padW, int padH) { THCUNN_argCheck(state, input->nDimension == 4 || input->nDimension == 5, 2, input, "4D or 5D (batch mode) tensor expected for input, but got: %s"); THArgCheck(!weight || THCTensor_(isContiguous)(state, weight), 4, "weight tensor has to be contiguous"); THArgCheck(!bias || THCTensor_(isContiguous)(state, bias), 5, "bias tensor has to be contiguous"); THArgCheck(!gradWeight || THCTensor_(isContiguous)(state, gradWeight), 5, "gradWeight tensor has to be contiguous"); THArgCheck(dT > 0 && dW > 0 && dH > 0, 10, "stride should be greater than zero, but got dT: %d dH: %d dW: %d", dT, dH, dW); if (gradOutput != NULL) { THCUNN_argCheck(state, gradOutput->nDimension == 4 || gradOutput->nDimension == 5, 3, gradOutput, "4D or 5D (batch mode) tensor expected for gradOutput, but got: %s"); } if (weight != NULL) { THCUNN_argCheck(state, weight->nDimension == 5, 4, weight, "5D (nOutputPlane x nInputPlane x kT x kH x kW) tensor " "expected for weight, but got: %s"); } if (gradWeight != NULL) { THCUNN_argCheck(state, gradWeight->nDimension == 5, 4, gradWeight, "5D (nOutputPlane x nInputPlane x kT x kH x kW) tensor " "expected for gradWeight, but got: %s"); } if (weight == NULL) { weight = gradWeight; } int nOutputPlane = (int)weight->size[0]; int nInputPlane = (int)weight->size[1]; int kT = (int)weight->size[2]; int kH = (int)weight->size[3]; int kW = (int)weight->size[4]; THArgCheck(kT > 0 && kW > 0 && kH > 0, 4, "kernel size should be greater than zero, but got kT: %d kH: %d kW: %d", kT, kH, kW); int ndim = input->nDimension; int dimf = 0; int dimh = 1; int dimw = 2; int dimd = 3; if (ndim == 5) { dimf++; dimh++; dimw++; dimd++; } int64_t inputWidth = input->size[dimw]; int64_t inputHeight = input->size[dimh]; int64_t inputDepth = input->size[dimd]; int64_t outputWidth = (inputWidth + 2*padH - kH) / dH + 1; int64_t outputHeight = (inputHeight + 2*padT - kT) / dT + 1; int64_t outputDepth = (inputDepth + 2*padW - kW) / dW + 1; if (outputWidth < 1 || outputHeight < 1 || outputDepth < 1) { THError( "Given input size: (%dx%dx%dx%d). Calculated output size: (%dx%dx%dx%d). Output size is too small", nInputPlane, inputDepth, inputHeight, inputWidth, nOutputPlane, outputDepth, outputHeight, outputWidth ); } if (bias != NULL) { THCUNN_check_dim_size(state, bias, 1, 0, weight->size[0]); } THCUNN_check_dim_size(state, input, ndim, dimf, nInputPlane); if (gradOutput != NULL) { THCUNN_check_dim_size(state, gradOutput, ndim, dimf, nOutputPlane); THCUNN_check_dim_size(state, gradOutput, ndim, dimh, outputHeight); THCUNN_check_dim_size(state, gradOutput, ndim, dimw, outputWidth); THCUNN_check_dim_size(state, gradOutput, ndim, dimd, outputDepth); } } void THNN_(VolumetricConvolution_updateOutput)( THCState *state, THCTensor *input, THCTensor *output, THCTensor *weight, THCTensor *bias, THCTensor *finput, THCTensor *fgradInput, int dT, int dW, int dH, int padT, int padW, int padH) { THCTensor *columns = finput; THCTensor *ones = fgradInput; THCUNN_assertSameGPU(state, 6, input, output, weight, bias, columns, ones); THNN_(VolumetricConvolution_shapeCheck)( state, input, NULL, weight, NULL, bias, dT, dW, dH, padT, padW, padH); input = THCTensor_(newContiguous)(state, input); int nOutputPlane = (int)weight->size[0]; int nInputPlane = (int)weight->size[1]; int kT = (int)weight->size[2]; int kH = (int)weight->size[3]; int kW = (int)weight->size[4]; int batch = 1; if (input->nDimension == 4) { // Force batch batch = 0; THCTensor_(resize5d)(state, input, 1, input->size[0], input->size[1], input->size[2], input->size[3]); } int64_t inputWidth = input->size[3]; int64_t inputHeight = input->size[2]; int64_t inputDepth = input->size[4]; int64_t outputWidth = (inputWidth + 2*padH - kH) / dH + 1; int64_t outputHeight = (inputHeight + 2*padT - kT) / dT + 1; int64_t outputDepth = (inputDepth + 2*padW - kW) / dW + 1; // Batch size + input planes int64_t batchSize = input->size[0]; // Resize output THCTensor_(resize5d)(state, output, batchSize, nOutputPlane, outputHeight, outputWidth, outputDepth); // Resize temporary columns THCTensor_(resize2d)(state, columns, nInputPlane*kW*kH*kT, outputDepth*outputHeight*outputWidth); // Define a buffer of ones, for bias accumulation // Note: this buffer can be shared with other modules, it only ever gets increased, // and always contains ones. if (ones->nDimension != 3 || ones->size[0]*ones->size[1]*ones->size[2] < outputDepth*outputHeight*outputWidth) { // Resize plane and fill with ones... THCTensor_(resize3d)(state, ones, outputHeight, outputWidth, outputDepth); THCTensor_(fill)(state, ones, ScalarConvert<int, real>::to(1)); } // Helpers THCTensor *input_n = THCTensor_(new)(state); THCTensor *output_n = THCTensor_(new)(state); // For each elt in batch, do: for (int elt = 0; elt < batchSize; elt ++) { // Matrix mulitply per output: THCTensor_(select)(state, input_n, input, 0, elt); THCTensor_(select)(state, output_n, output, 0, elt); // Do Bias first: // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) int64_t m_ = nOutputPlane; int64_t n_ = outputDepth * outputHeight * outputWidth; int64_t k_ = 1; // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) if (bias) { #ifdef THC_REAL_IS_FLOAT THCudaBlas_Sgemm( #elif defined(THC_REAL_IS_HALF) THCudaBlas_Hgemm( #elif defined(THC_REAL_IS_DOUBLE) THCudaBlas_Dgemm( #endif state, 't', 'n', n_, m_, k_, ScalarConvert<int, real>::to(1), THCTensor_(data)(state, ones), k_, THCTensor_(data)(state, bias), k_, ScalarConvert<int, real>::to(0), THCTensor_(data)(state, output_n), n_ ); } else { THCTensor_(zero)(state, output_n); } // Extract columns: im3d2col( THCState_getCurrentStream(state), THCTensor_(data)(state, input_n), nInputPlane, inputHeight, inputWidth, inputDepth, kT, kH, kW, padT, padH, padW, dT, dH, dW, THCTensor_(data)(state, columns) ); // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) int64_t m = weight->size[0]; int64_t n = columns->size[1]; int64_t k = weight->size[1]*weight->size[2]*weight->size[3]*weight->size[4]; // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) #ifdef THC_REAL_IS_FLOAT THCudaBlas_Sgemm( #elif defined(THC_REAL_IS_HALF) THCudaBlas_Hgemm( #elif defined(THC_REAL_IS_DOUBLE) THCudaBlas_Dgemm( #endif state, 'n', 'n', n, m, k, ScalarConvert<int, real>::to(1), THCTensor_(data)(state, columns), n, THCTensor_(data)(state, weight), k, ScalarConvert<int, real>::to(1), THCTensor_(data)(state, output_n), n ); } // Free THCTensor_(free)(state, input_n); THCTensor_(free)(state, output_n); // Resize output if (batch == 0) { THCTensor_(resize4d)(state, output, nOutputPlane, outputHeight, outputWidth, outputDepth); THCTensor_(resize4d)(state, input, nInputPlane, inputHeight, inputWidth, inputDepth); } THCTensor_(free)(state, input); } void THNN_(VolumetricConvolution_updateGradInput)( THCState *state, THCTensor *input, THCTensor *gradOutput, THCTensor *gradInput, THCTensor *weight, THCTensor *finput, int dT, int dW, int dH, int padT, int padW, int padH) { int nOutputPlane = (int)weight->size[0]; int nInputPlane = (int)weight->size[1]; int kT = (int)weight->size[2]; int kH = (int)weight->size[3]; int kW = (int)weight->size[4]; THCTensor *gradColumns = finput; THCUNN_assertSameGPU(state, 5, input, gradOutput, weight, gradColumns, gradInput); THNN_(VolumetricConvolution_shapeCheck)( state, input, gradOutput, weight, NULL, NULL, dT, dW, dH, padT, padW, padH); gradOutput = THCTensor_(newContiguous)(state, gradOutput); int batch = 1; if (input->nDimension == 4) { input = THCTensor_(newContiguous)(state, input); // Force batch batch = 0; THCTensor_(resize5d)(state, input, 1, input->size[0], input->size[1], input->size[2], input->size[3]); THCTensor_(resize5d)(state, gradOutput, 1, gradOutput->size[0], gradOutput->size[1], gradOutput->size[2], gradOutput->size[3]); } int64_t inputWidth = input->size[3]; int64_t inputHeight = input->size[2]; int64_t inputDepth = input->size[4]; int64_t outputWidth = (inputWidth + 2*padH - kH) / dH + 1; int64_t outputHeight = (inputHeight + 2*padT - kT) / dT + 1; int64_t outputDepth = (inputDepth + 2*padW - kW) / dW + 1; // Batch size + input planes int64_t batchSize = input->size[0]; // Resize output THCTensor_(resize5d)(state, gradInput, batchSize, nInputPlane, inputHeight, inputWidth, inputDepth); // Resize temporary columns THCTensor_(resize2d)(state, gradColumns, nInputPlane*kH*kT*kW, outputDepth*outputHeight*outputWidth); // Helpers THCTensor *gradInput_n = THCTensor_(new)(state); THCTensor *gradOutput_n = THCTensor_(new)(state); // For each elt in batch, do: for (int elt = 0; elt < batchSize; elt ++) { // Matrix mulitply per sample: THCTensor_(select)(state, gradInput_n, gradInput, 0, elt); THCTensor_(select)(state, gradOutput_n, gradOutput, 0, elt); // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) int64_t m = weight->size[1]*weight->size[2]*weight->size[3]*weight->size[4]; int64_t n = gradColumns->size[1]; int64_t k = weight->size[0]; // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) #ifdef THC_REAL_IS_FLOAT THCudaBlas_Sgemm( #elif defined(THC_REAL_IS_HALF) THCudaBlas_Hgemm( #elif defined(THC_REAL_IS_DOUBLE) THCudaBlas_Dgemm( #endif state, 'n', 't', n, m, k, ScalarConvert<int, real>::to(1), THCTensor_(data)(state, gradOutput_n), n, THCTensor_(data)(state, weight), m, ScalarConvert<int, real>::to(0), THCTensor_(data)(state, gradColumns), n ); // Unpack columns back into input: col2im3d<real, accreal>( THCState_getCurrentStream(state), THCTensor_(data)(state, gradColumns), nInputPlane, inputHeight, inputWidth, inputDepth, kT, kH, kW, padT, padH, padW, dT, dH, dW, THCTensor_(data)(state, gradInput_n) ); } // Free THCTensor_(free)(state, gradInput_n); THCTensor_(free)(state, gradOutput_n); // Resize output if (batch == 0) { THCTensor_(resize4d)(state, gradOutput, nOutputPlane, outputHeight, outputWidth, outputDepth); THCTensor_(resize4d)(state, input, nInputPlane, inputHeight, inputWidth, inputDepth); THCTensor_(resize4d)(state, gradInput, nInputPlane, inputHeight, inputWidth, inputDepth); THCTensor_(free)(state, input); } THCTensor_(free)(state, gradOutput); } void THNN_(VolumetricConvolution_accGradParameters)( THCState *state, THCTensor *input, THCTensor *gradOutput, THCTensor *gradWeight, THCTensor *gradBias, THCTensor *finput, THCTensor *fgradInput, int dT, int dW, int dH, int padT, int padW, int padH, accreal scale_) { real scale = ScalarConvert<accreal, real>::to(scale_); THCTensor *columns = finput; THCTensor *ones = fgradInput; THCUNN_assertSameGPU(state, 6, input, gradOutput, gradWeight, gradBias, columns, ones); THNN_(VolumetricConvolution_shapeCheck)( state, input, gradOutput, NULL, gradWeight, gradBias, dT, dW, dH, padT, padW, padH); int nOutputPlane = (int)gradWeight->size[0]; int nInputPlane = (int)gradWeight->size[1]; int kT = (int)gradWeight->size[2]; int kH = (int)gradWeight->size[3]; int kW = (int)gradWeight->size[4]; input = THCTensor_(newContiguous)(state, input); gradOutput = THCTensor_(newContiguous)(state, gradOutput); int batch = 1; if (input->nDimension == 4) { // Force batch batch = 0; THCTensor_(resize5d)(state, input, 1, input->size[0], input->size[1], input->size[2], input->size[3]); THCTensor_(resize5d)(state, gradOutput, 1, gradOutput->size[0], gradOutput->size[1], gradOutput->size[2], gradOutput->size[3]); } int64_t inputWidth = input->size[3]; int64_t inputHeight = input->size[2]; int64_t inputDepth = input->size[4]; int64_t outputWidth = (inputWidth + 2*padH - kH) / dH + 1; int64_t outputHeight = (inputHeight + 2*padT - kT) / dT + 1; int64_t outputDepth = (inputDepth + 2*padW - kW) / dW + 1; // Batch size + input planes int64_t batchSize = input->size[0]; // Define a buffer of ones, for bias accumulation if (ones->nDimension != 3 || ones->size[0]*ones->size[1]*ones->size[2] < outputDepth*outputHeight*outputWidth) { // Resize plane and fill with ones... THCTensor_(resize3d)(state, ones, outputHeight, outputWidth, outputDepth); THCTensor_(fill)(state, ones, ScalarConvert<int, real>::to(1)); } // Resize temporary columns THCTensor_(resize2d)(state, columns, nInputPlane*kH*kT*kW, outputDepth*outputHeight*outputWidth); // Helpers THCTensor *input_n = THCTensor_(new)(state); THCTensor *gradOutput_n = THCTensor_(new)(state); // For each elt in batch, do: for (int elt = 0; elt < batchSize; elt ++) { // Matrix mulitply per output: THCTensor_(select)(state, input_n, input, 0, elt); THCTensor_(select)(state, gradOutput_n, gradOutput, 0, elt); // Extract columns: im3d2col( THCState_getCurrentStream(state), THCTensor_(data)(state, input_n), nInputPlane, inputHeight, inputWidth, inputDepth, kT, kH, kW, padT, padH, padW, dT, dH, dW, THCTensor_(data)(state, columns) ); // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) int64_t m = gradWeight->size[0]; int64_t n = gradWeight->size[1]*gradWeight->size[2]*gradWeight->size[3]*gradWeight->size[4]; int64_t k = columns->size[1]; // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) #ifdef THC_REAL_IS_FLOAT THCudaBlas_Sgemm( #elif defined(THC_REAL_IS_HALF) THCudaBlas_Hgemm( #elif defined(THC_REAL_IS_DOUBLE) THCudaBlas_Dgemm( #endif state, 't', 'n', n, m, k, scale, THCTensor_(data)(state, columns), k, THCTensor_(data)(state, gradOutput_n), k, ScalarConvert<int, real>::to(1), THCTensor_(data)(state, gradWeight), n ); // Do Bias: // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) int64_t m_ = nOutputPlane; int64_t k_ = outputDepth * outputHeight * outputWidth; // Do GEMV (note: this is a bit confusing because gemv assumes column-major matrices) if (gradBias) { #if defined(THC_REAL_IS_FLOAT) || defined(THC_REAL_IS_DOUBLE) #ifdef THC_REAL_IS_FLOAT THCudaBlas_Sgemv( #elif defined(THC_REAL_IS_DOUBLE) THCudaBlas_Dgemv( #endif state, 't', k_, m_, scale, THCTensor_(data)(state, gradOutput_n), k_, THCTensor_(data)(state, ones), 1, ScalarConvert<int, real>::to(1), THCTensor_(data)(state, gradBias), 1 ); #endif #ifdef THC_REAL_IS_HALF THCudaBlas_Hgemm( state, 't', 'n', m_, 1, k_, scale, THCTensor_(data)(state, gradOutput_n), k_, THCTensor_(data)(state, ones), k_, ScalarConvert<int, real>::to(1), THCTensor_(data)(state, gradBias), m_ ); #endif } } // Free THCTensor_(free)(state, input_n); THCTensor_(free)(state, gradOutput_n); // Resize if (batch == 0) { THCTensor_(resize4d)(state, gradOutput, nOutputPlane, outputHeight, outputWidth, outputDepth); THCTensor_(resize4d)(state, input, nInputPlane, inputHeight, inputWidth, inputDepth); } THCTensor_(free)(state, input); THCTensor_(free)(state, gradOutput); } #endif
the_stack
#define BSZ 16 /** * \namespace kernels * \brief Contains all the custom-written CUDA kernels. */ namespace kernels { /** * \brief Calculates drag using a control-volume approach (left-right). * * Evaluate the contribution from the left and right parts of the control surface. * * \param FxX raw pointer to the vector storing the drag in the x-direction * \param lambda raw pointer to the vector storing all the pressure and Lagrangian forces * \param q raw pointer to the vector storing all the fluxes * \param nu viscosity * \param dx raw pointer to the vector storing the cell widths in the x-direction * \param dy raw pointer to the vector storing the cell widths in the y-direction * \param nx number of cells in the x-direction * \param ny number of cells in the y-direction * \param I x-index of the bottom-left corner cell of the control surface * \param J y-index of the top-right corner cell of the control surface * \param ncx number of cells in the x-direction in the control volume * \param ncy number of cells in the y-direction in the control volume */ __global__ void dragLeftRight(real *FxX, real *q, real *lambda, real nu, real *dx, real *dy, int nx, int ny, int I, int J, int ncx, int ncy) { int idx = threadIdx.x + blockIdx.x*blockDim.x; if(idx >= ncy) return; int Ip = (J+idx)*nx + I, Iu = (J+idx)*(nx-1) + (I-1); FxX[idx] = -( // multiply the pressure with the surface area to get p dy (lambda[Ip+ncx]-lambda[Ip-1])*dy[J+idx] + // divide q^2 by dy, so that just u^2 dy is obtained ( 0.25*(q[Iu+ncx+1] + q[Iu+ncx])*(q[Iu+ncx+1] + q[Iu+ncx]) - 0.25*(q[Iu] + q[Iu-1])*(q[Iu] + q[Iu-1]) )/dy[J+idx] - // no multiplication or division since du/dx dy = dq/dx nu* ( (q[Iu+ncx+1] - q[Iu+ncx])/dx[I+ncx] - (q[Iu] - q[Iu-1])/dx[I-1] ) ); } // dragLeftRight /** * \brief Calculate drag using a control-volume approach (bottom-top). * * Evaluate the contribution from the bottom and top parts of the control surface. * * \param FxY raw pointer to the vector storing the drag in the y-direction * \param q raw pointer to the vector storing all the fluxes * \param nu viscosity * \param dx raw pointer to the vector storing the cell widths in the x-direction * \param dy raw pointer to the vector storing the cell widths in the y-direction * \param nx number of cells in the x-direction * \param ny number of cells in the y-direction * \param I x-index of the bottom-left corner cell of the control surface * \param J y-index of the top-right corner cell of the control surface * \param ncx number of cells in the x-direction in the control volume * \param ncy number of cells in the y-direction in the control volume */ __global__ void dragBottomTop(real *FxY, real *q, real nu, real *dx, real *dy, int nx, int ny, int I, int J, int ncx, int ncy) { int idx = threadIdx.x + blockIdx.x*blockDim.x; if(idx > ncx) return; int Iu = J*(nx-1) + (I-1+idx), Iv = (nx-1)*ny + (J-1)*nx + I+idx; FxY[idx] = -( // multiply by dS ( 0.25 * ( q[Iu+ncy*(nx-1)]/dy[J+ncy] + q[Iu+(ncy-1)*(nx-1)]/dy[J+ncy-1] ) * ( q[Iv+ncy*nx]/dx[I+idx] + q[Iv+ncy*nx-1]/dx[I+idx-1] ) - 0.25 * ( q[Iu]/dy[J] + q[Iu-(nx-1)]/dy[J-1] ) * ( q[Iv]/dx[I+idx] + q[Iv-1]/dx[I+idx-1] ) ) - // multiply by dS (cannot use the leftRight trick in this case) nu* ( ( (q[Iu+ncy*(nx-1)]/dy[J+ncy] - q[Iu+(ncy-1)*(nx-1)]/dy[J+ncy-1])/2.0/(dy[J+ncy]+dy[J+ncy-1]) + (q[Iv+ncy*nx]/dx[I+idx] - q[Iv+ncy*nx-1]/dx[I+idx-1])/2.0/(dx[I+idx]+dx[I+idx-1]) ) - ( (q[Iu]/dy[J] - q[Iu-(nx-1)]/dy[J-1])/2.0/(dy[J]+dy[J-1]) + (q[Iv]/dx[I+idx] - q[Iv-1]/dx[I+idx-1])/2.0/(dx[I+idx]+dx[I+idx-1]) ) ) )*0.5*(dx[I+idx]+dx[I+idx-1]); } // dragBottomTop /** * \brief Calculate drag using a control-volume approach (unsteady). * * Evaluate the unsteady contribution of the control volume. * * \param FxU raw pointer to the vector storing the unsteady drag components * \param q raw pointer to the vector storing all the fluxes * \param qOld raw pointer to the vector sotring all the fluxes at the previous time-step * \param dx raw pointer to the vector storing the cell widths in the x-direction * \param dy raw pointer to the vector storing the cell widths in the y-direction * \param dt time increment * \param nx number of cells in the x-direction * \param ny number of cells in the y-direcyion * \param I x-index of the bottom-left cell of the control surface * \param J y-index of the top-right cell of the control surface * \param ncx number of cells in the x-direction in the control volume * \param nyc number of cells in the y-direction in the control volume */ __global__ void dragUnsteady(real *FxU, real *q, real *qOld, real *dx, real *dy, real dt, int nx, int ny, int I, int J, int ncx, int ncy) { int idx = threadIdx.x + blockIdx.x*blockDim.x; if(idx >= (ncx+1)*ncy) return; int i = idx%(ncx+1), j = idx/(ncx+1); int Iu = (J+j)*(nx-1) + (I-1+i); FxU[idx] = - (q[Iu] - qOld[Iu])/dt * 0.5*(dx[I+i]+dx[I-1+i]); } // dragUnsteady /** * \brief Calculate lift using a control-volume approach (left-right). * * Evaluate the contribution from the left and right parts of the control surface. * * \param FyX raw pointer to the vector storing the lift components in the x-direction * \param q raw pointer to the vector storing all the fluxes * \param nu viscosity * \param dx raw pointer to the vector storing the cell widths in the x-direction * \param dy raw pointer to the vector storing the cell widths in the y-direction * \param nx number of cells in the x-direction * \param ny number of cells in the y-direcyion * \param I x-index of the bottom-left cell of the control surface * \param J y-index of the top-right cell of the control surface * \param ncx number of cells in the x-direction in the control volume * \param nyc number of cells in the y-direction in the control volume */ __global__ void liftLeftRight(real *FyX, real *q, real nu, real *dx, real *dy, int nx, int ny, int I, int J, int ncx, int ncy) { int idx = threadIdx.x + blockIdx.x*blockDim.x; if(idx > ncy) return; int Iu = (J+idx)*(nx-1) + (I-1), Iv = (nx-1)*ny + (J-1+idx)*nx + I; FyX[idx] = -( // multiply by dS ( 0.25 * ( q[Iu+ncx]/dy[J+idx] + q[Iu+ncx-(nx-1)]/dy[J-1+idx] ) * ( q[Iv+ncx]/dx[I+ncx] + q[Iv+ncx-1]/dx[I+ncx-1] ) - 0.25 * ( q[Iu]/dy[J+idx] + q[Iu-(nx-1)]/dy[J-1+idx] ) * ( q[Iv]/dx[I] + q[Iv-1]/dx[I-1] ) ) - // multiply by dS (cannot use the leftRight trick in this case) nu* ( ( (q[Iu+ncx]/dy[J+idx] - q[Iu+ncx-(nx-1)]/dy[J-1+idx])/2.0/(dy[J+idx]+dy[J-1+idx]) + (q[Iv+ncx]/dx[I+ncx] - q[Iv+ncx-1]/dx[I+ncx-1])/2.0/(dx[I+ncx]+dx[I+ncx-1]) ) - ( (q[Iu]/dy[J+idx] - q[Iu-(nx-1)]/dy[J-1+idx])/2.0/(dy[J+idx]+dy[J-1+idx]) + (q[Iv]/dx[I] - q[Iv-1]/dx[I-1])/2.0/(dx[I]+dx[I-1]) ) ) )*0.5*(dy[J+idx]+dy[J-1+idx]); } // liftLeftRight /** * \brief Calculate lift using a control-volume approach (bottom-top). * * Evaluate the contribution from the bottom and top parts of the control surface. * * \param FyY raw pointer to the vector storing the lift components in the y-direction * \param q raw pointer to the vector storing all the fluxes * \param lambda raw pointer to the vector storing the pressure and Lagrangian forces * \param nu viscosity * \param dx raw pointer to the vector storing the cell widths in the x-direction * \param dy raw pointer to the vector storing the cell widths in the y-direction * \param nx number of cells in the x-direction * \param ny number of cells in the y-direcyion * \param I x-index of the bottom-left cell of the control surface * \param J y-index of the top-right cell of the control surface * \param ncx number of cells in the x-direction in the control volume * \param nyc number of cells in the y-direction in the control volume */ __global__ void liftBottomTop(real *FyY, real *q, real *lambda, real nu, real *dx, real *dy, int nx, int ny, int I, int J, int ncx, int ncy) { int idx = threadIdx.x + blockIdx.x*blockDim.x; if(idx >= ncx) return; int Ip = J*nx + I+idx, Iv = (nx-1)*ny + (J-1)*nx + I+idx; FyY[idx] = -( // multiply the pressure with the surface area to get p dx (lambda[Ip+ncy*nx]-lambda[Ip-nx])*dx[I+idx] + // divide q^2 by dx, so that just v^2 dx is obtained ( 0.25*(q[Iv+(ncy+1)*nx] + q[Iv+ncy*nx])*(q[Iv+(ncy+1)*nx] + q[Iv+ncy*nx]) - 0.25*(q[Iv] + q[Iv-nx])*(q[Iv] + q[Iv-nx]) )/dx[I+idx] - // no multiplication or division since dv/dy dx = dq/dy nu* ( (q[Iv+(ncy+1)*nx] - q[Iv+ncy*nx])/dy[J+ncy] - (q[Iv] - q[Iv-nx])/dy[J-1] ) ); } // liftBottomTop /** * \brief Calculate lift using a control-volume approach (unsteady). * * Evaluate the unsteady contribution of the control volume. * * \param FyU raw pointer to the vector storing the unsteady lift components * \param q raw pointer to the vector storing all the fluxes * \param qOld raw pointer to the vector sotring all the fluxes at the previous time-step * \param dx raw pointer to the vector storing the cell widths in the x-direction * \param dy raw pointer to the vector storing the cell widths in the y-direction * \param dt time increment * \param nx number of cells in the x-direction * \param ny number of cells in the y-direcyion * \param I x-index of the bottom-left cell of the control surface * \param J y-index of the top-right cell of the control surface * \param ncx number of cells in the x-direction in the control volume * \param nyc number of cells in the y-direction in the control volume */ __global__ void liftUnsteady(real *FyU, real *q, real *qOld, real *dx, real *dy, real dt, int nx, int ny, int I, int J, int ncx, int ncy) { int idx = threadIdx.x + blockIdx.x*blockDim.x; if( idx >= ncx*(ncy+1) ) return; int i = idx%ncx, j = idx/ncx; int Iv = (J-1+j)*nx + (I+i) + (nx-1)*ny; FyU[idx] = - (q[Iv] - qOld[Iv])/dt * 0.5*(dy[J+j]+dy[J-1+j]); } // liftUnsteady /** * \brief Kernel not usable. */ __global__ void forceX(real *f, real *q, real *rn, int *tags, int nx, int ny, real *dx, real *dy, real dt, real alpha, real nu) { int bx = blockIdx.x, by = blockIdx.y, i = threadIdx.x, j = threadIdx.y; // work out global index of first point in block int I = (BSZ-2)*bx + i, J = (BSZ-2)*by + j; if (I >= nx-1 || J >= ny) { return; } int Gidx_x = J*(nx-1) + I; real dTerm; __shared__ real u[BSZ][BSZ]; __shared__ real Dx[BSZ][BSZ], Dy[BSZ][BSZ]; Dy[j][i] = dy[J]; Dx[j][i] = dx[I]; /// transfer from global to shared memory u[j][i] = q[Gidx_x]/Dy[j][i]; __syncthreads(); /// check bounds for convective term in the x-direction int global_check = ( I==0 || I==(nx-2) || J==0 || J==(ny-1) ), ///< check if we compute globally block_check = ( i==0 || i==(BSZ-1) || j==0 || j==(BSZ-1) ); ///< check if element within block computes /// X-component if( !(global_check || block_check) ) { dTerm = alpha*nu*2.0*( \ ( Dx[j][i]*u[j][i+1] - (Dx[j][i]+Dx[j][i+1])*u[j][i] + Dx[j][i+1]*u[j][i-1] ) / ( Dx[j][i]*Dx[j][i+1]*(Dx[j][i]+Dx[j][i+1]) ) \ + 4.0*( (Dy[j][i]+Dy[j-1][i])*u[j+1][i] - (Dy[j-1][i] + 2.0*Dy[j][i] + Dy[j+1][i])*u[j][i] + (Dy[j][i]+Dy[j+1][i])*u[j-1][i] ) \ /( (Dy[j][i]+Dy[j-1][i]) * (Dy[j-1][i] + 2.0*Dy[j][i] + Dy[j+1][i]) * (Dy[j][i]+Dy[j+1][i]) ) \ ); f[Gidx_x] = ( u[j][i]/dt - dTerm - rn[Gidx_x]/(0.5*(Dx[j][i]+Dx[j][i+1])) ) * (!(tags[Gidx_x]==-1)); } } // forceX /** * \brief Kernel not usable. */ __global__ void forceY() { } // forceY } // End of namespace kernels
the_stack
using namespace cuHE; using namespace cuHE_Utils; /////////////////////////////////////////////////////////////////////////////// // @class CuDHS /////////////////////////////////////////////////////////////////////////////// //// Constructor ////////////////////////////////////////// CuDHS::CuDHS(int d, int p, int w, int min, int cut, int m) { setParameters(d, p, w, min, cut, m); coeffMod_ = new ZZ[param.depth]; pk_ = new ZZX[param.depth]; sk_ = new ZZX[param.depth]; if (param.logRelin > 0) { ek_ = new ZZX[param.numEvalKey]; } else { ek_ = NULL; } // generate polynomial modulus genPolyMod_(); // create polynomial ring initCuHE(coeffMod_, polyMod_); B = 1; // key generation keyGen(); numSlot_ = param.modLen/factorDegree(); // setup batching #ifdef batching batcher = new Batcher(polyMod_, param.modLen/numSlot_, numSlot_); #endif } CuDHS::CuDHS(string key) { PicklableMap* pm = new PicklableMap(key); int d = stoi( pm->get("d")->getValues() ); int p = stoi( pm->get("p")->getValues() ); int w = stoi( pm->get("w")->getValues() ); int min = stoi( pm->get("min")->getValues() ); int cut = stoi( pm->get("cut")->getValues() ); int m = stoi( pm->get("m")->getValues() ); setParameters(d, p, w, min, cut, m); coeffMod_ = pm->get("coeffMod")->getCoeffs(); polyMod_ = pm->get("polyMod")->getPoly(); pk_ = new ZZX[param.depth]; for (int i=0; i < param.depth; i++) { stringstream buffer; buffer << "pk" << i; pk_[i] = pm->get(buffer.str())->getPoly(); } sk_ = NULL; try { pm->get("sk0"); sk_ = new ZZX[param.depth]; } catch (char const* s) { sk_ = NULL; } if (sk_ != NULL) { for (int i=0; i < param.depth; i++) { stringstream buffer; buffer << "sk" << i; sk_[i] = pm->get(buffer.str())->getPoly(); } } if (param.logRelin > 0) { ek_ = new ZZX[param.numEvalKey]; for (int i=0; i < param.numEvalKey; i++) { stringstream buffer; buffer << "ek" << i; ek_[i] = pm->get(buffer.str())->getPoly(); } } else { ek_ = NULL; } initCuHE(coeffMod_, polyMod_); // create polynomial ring B = 1; numSlot_ = param.modLen/factorDegree(); batcher = new Batcher(polyMod_, param.modLen/numSlot_, numSlot_); // setup batching } string CuDHS::getPublicKey() { PicklableMap* pm = new PicklableMap(getPublicPicklables()); return pm->toString(); } vector<Picklable*> CuDHS::getPublicPicklables() { vector<Picklable*> ps; ZZ* zz = new ZZ[1]; zz[0] = conv<ZZ>(param.depth); Picklable* d = new Picklable("d", zz, 1); ps.push_back(d); zz[0] = conv<ZZ>(param.modMsg); Picklable* p = new Picklable("p", zz, 1); ps.push_back(p); zz[0] = conv<ZZ>(param.logRelin); Picklable* w = new Picklable("w", zz, 1); ps.push_back(w); zz[0] = conv<ZZ>(param.logCoeffMin); Picklable* min = new Picklable("min", zz, 1); ps.push_back(min); zz[0] = conv<ZZ>(param.logCoeffCut); Picklable* cut = new Picklable("cut", zz, 1); ps.push_back(cut); zz[0] = conv<ZZ>(param.mSize); Picklable* m = new Picklable("m", zz, 1); ps.push_back(m); Picklable* coeffMod = new Picklable("coeffMod", coeffMod_, param.depth); ps.push_back(coeffMod); Picklable* polyMod = new Picklable("polyMod", polyMod_); ps.push_back(polyMod); for (int i=0; i < param.depth; i++) { stringstream buffer; buffer << "pk" << i; ps.push_back( new Picklable(buffer.str(), pk_[i]) ); } for (int i=0; i < param.numEvalKey; i++) { stringstream buffer; buffer << "ek" << i; ps.push_back( new Picklable(buffer.str(), ek_[i]) ); } return ps; } string CuDHS::getPrivateKey() { vector<Picklable*> ps = getPublicPicklables(); for (int i=0; i < param.depth; i++) { stringstream buffer; buffer << "sk" << i; ps.push_back( new Picklable(buffer.str(), sk_[i]) ); } PicklableMap* pm = new PicklableMap(ps); return pm->toString(); } CuDHS::~CuDHS() { clear(polyMod_); delete [] coeffMod_; delete [] pk_; delete [] sk_; if (ek_ != NULL) delete [] ek_; #ifdef batching delete batcher; #endif } ZZX CuDHS::polyMod() { return polyMod_;}; ZZ* CuDHS::coeffMod() { return coeffMod_;}; int CuDHS::numSlot() { return numSlot_;}; ZZX* CuDHS::ek() { return ek_;}; //// Primitives /////////////////////////////////////////// void CuDHS::keyGen() { genPkSk(); if (param.logRelin > 0) { genEk(); } } void CuDHS::encrypt(ZZX& out, ZZX in, int lvl) { ZZX s, e, t; s = sample(); e = sample(); coeffReduce(s, s, lvl); mulZZX(t, pk_[lvl], s, lvl, 0, 0); // t = pk_[lvl]*s; // t %= polyMod_; // coeffReduce(t, t, lvl); t += e*param.modMsg+in; coeffReduce(t, t, lvl); out = t; } void CuDHS::decrypt(ZZX& out, ZZX in, int lvl, int maxMulPath) { if (sk_ == NULL) { cout << "operation not available without private key." << endl; return; } ZZ x; ZZX t = in; coeffReduce(t, t, lvl); if (param.logRelin > 0) for (int i=0; i<maxMulPath; i++) mulZZX(t, t, sk_[lvl], lvl, 0, 0); else mulZZX(t, t, sk_[lvl], lvl, 0, 0); // ZZX t = sk_[lvl]*in; // t %= polyMod_; // coeffReduce(t, t, coeffMod_[lvl]); clear(out); for (int i=0; i<=deg(t); i++) { x = coeff(t, i); if (x > ((coeffMod_[lvl]-1)/2)) x -= coeffMod_[lvl]; SetCoeff(out, i, (x%param.modMsg)); } } void CuDHS::unbalance(ZZX& x, int lvl) { ZZ tp, q = coeffMod_[lvl]; for (int i=0; i<=deg(x); i++) { tp = coeff(x, i); if (tp < 0) tp += q; SetCoeff(x, i, tp); } } void CuDHS::balance(ZZX& x, int lvl) { ZZ tp, q = coeffMod_[lvl]; for (int i=0; i<=deg(x); i++) { tp = coeff(x, i); if (tp > ((q-1)/2)) tp -= q; SetCoeff(x, i, tp); } } //// Tools //////////////////////////////////////////////// int CuDHS::factorDegree() { int ret = 1; while ( (power(to_ZZ(param.modMsg), ret)-1)%param.mSize != 0 ) ret++; return ret; } void CuDHS::genPolyMod_() { int s; polyMod_ = 1; ZZX *t_vec = new ZZX[param.mSize]; int *s_vec = new int[param.mSize]; for (int i=0; i<param.mSize; i++) s_vec[i] = 0; for (int d=1; d<=param.mSize; d++) { if (GCD(d, param.mSize) == d) { ZZX t; SetCoeff(t, 0 , -1); SetCoeff(t, param.mSize/d, 1); s = mobuisFunction(d); t_vec[d-1] = t; s_vec[d-1] = s; } } for (int i=0; i<param.mSize; i++) if (s_vec[i] == 1) polyMod_ *= t_vec[i]; for (int i=0; i<param.mSize; i++) if (s_vec[i] == -1) polyMod_ /= t_vec[i]; delete [] t_vec; delete [] s_vec; } void CuDHS::genPkSk() { // sample ZZX f, g, ft, f_inv; coeffReduce(polyMod_, polyMod_, 0);// bool isfound = false; while (!isfound) { isfound = true; ft = sample(); f = ft*param.modMsg + 1; coeffReduce(f, f, 0);// findInverse(f_inv, f, coeffMod_[0], isfound); coeffReduce(f_inv, f_inv, 0); } isfound = false; g = sample(); coeffReduce(g, g, 0); // sk[0], pk[0] from (f, g, f_inv) sk_[0] = f; mulZZX(pk_[0], g, f_inv, 0, 0, 0); // pk[0] = g*f_inv, reduce // cout<<pk_[0]<<endl; // pk_[0] = g*f_inv; // pk_[0] %= polyMod_; // coeffReduce(pk_[0], pk_[0], 0); pk_[0] *= param.modMsg; coeffReduce(pk_[0], pk_[0], 0); coeffReduce(sk_[0], sk_[0], 0); for(int i=1; i<param.depth; i++){ sk_[i] = sk_[i-1]; coeffReduce(sk_[i], sk_[i], i); pk_[i] = pk_[i-1]; coeffReduce(pk_[i], pk_[i], i); } } void CuDHS::genEk() { ZZX tk = sk_[0]; ZZ tw =to_ZZ(1); ZZ w = to_ZZ(1)<<param.logRelin; ZZX s, e, result, tp; for (int i=0; i<param.numEvalKey; i++) { tp = tk*tw; s = sample(); e = sample(); coeffReduce(s, s, 0); coeffReduce(e, e, 0); coeffReduce(tp, tp, 0); mulZZX(ek_[i], pk_[0], s, 0, 0, 0); ek_[i] += e*param.modMsg+tp; // ek2.key[i] = pk[0]*s + e*p + tp; // Arith_PolyReduce(ek2.key[i], ek2.key[i]); coeffReduce(ek_[i], ek_[i], 0); tw *= w; } initRelinearization(ek_); } void CuDHS::coeffReduce(ZZX& out, ZZX in, int lvl) { coeffReduce(out, in, coeffMod_[lvl]); } void CuDHS::coeffReduce(ZZX& out, ZZX in, ZZ q) { clear(out); for (int i=0; i<=deg(in); i++) SetCoeff(out, i, coeff(in,i)%q); } ZZX CuDHS::sample(){ ZZX ret; for (int i=0; i<param.modLen; i++) SetCoeff(ret, i, RandomBnd(to_ZZ(2*B+1))-B); return ret; } void CuDHS::findInverse(ZZX &f_inv, ZZX &f, ZZ &q, bool &isfound) { ZZ_p::init(q); ZZ_pX phi; phi = to_ZZ_pX(polyMod_); ZZ_pE::init(phi); ZZ_pE f_, f_inv_; f_ = to_ZZ_pE(to_ZZ_pX(f)); try{ f_inv_ = inv(f_); } catch(runtime_error &e) { isfound = false; } ZZ_pX tp = rep(f_inv_); for(int i=0; i<param.modLen; i++) SetCoeff(f_inv, i, rep(coeff(tp, i))); } int CuDHS::mobuisFunction(int n) { int t, primes; primes = 0; if (n == 1) return 1; else { for (int i=2; i<=n; i++) { if (ProbPrime(i)) { if (GCD(i,n) == i) { t=n/i; primes++; if (GCD(i, t) == i) return 0; } } } if (primes%2 == 0) return 1; else return -1; } } /////////////////////////////////////////////////////////////////////////////// // @class Batcher /////////////////////////////////////////////////////////////////////////////// //// Constructor ////////////////////////////////////////// Batcher::Batcher(ZZX polymod, int f_degree, int f_size) { if (param.modMsg != 2) { cout<<"Error: This Batcher code only supports 1-bit messages."<<endl; terminate(); } ZZ_p::init(to_ZZ(2)); SetModulus(polymod); ComputeFactors(f_degree, f_size); CalculateMs(); CalculateNs(); CalculateMxNs(); } Batcher::~Batcher() {} void Batcher::SetModulus(ZZX m) { modulus = to_ZZ_pX(m); } void Batcher::ComputeFactors(int f_degree, int f_size) { factors.SetLength(f_size); int s = 1<<f_degree; ZZ_pX *list = new ZZ_pX[s]; for (int i=0; i<s; i++) list[i] = to_ZZ_pX(num2ZZX(i+s)); int j=0; ZZ_pX t1 = modulus; ZZ_pX comp, remin, quo; SetCoeff(comp, 0, 0); for (int i=0; i<s; i++) { DivRem(quo, remin, t1, list[i]); if (remin == comp) { t1 = quo; factors[j] = list[i]; j++; } } size = factors.length(); } void Batcher::CalculateMs() { ZZ_pX temp; M.SetLength(size); for (int i=0; i<size; i++) { M[i] = modulus; M[i] = M[i] / factors[i]; } } void Batcher::CalculateNs() { ZZ_pX mi; N.SetLength(size); for (int i=0; i<size; i++) { mi = factors[i]; ZZ_pE::init(mi); ZZ_pE t = to_ZZ_pE((M[i])%mi); ZZ_pE ti = inv(t); N[i] = rep(ti); } } void Batcher::CalculateMxNs() { MxN.SetLength(size); for (int i=0; i<size; i++) MxN[i] = (M[i]*N[i])%modulus; } void Batcher::encode(ZZX &poly, ZZX mess) { ZZ_p::init(to_ZZ(2)); ZZ_pX res; SetCoeff(res, 0, 0); for (int i=0; i<size; i++) if (coeff(mess,i) == 1) res = res + MxN[i]; res %= modulus; poly = to_ZZX(res); } void Batcher::decode(ZZX &mess, ZZX poly) { ZZ t; ZZ_pX mess_p, tm; mess_p = to_ZZ_pX(poly); clear(mess); for (int i=0; i<size; i++) { tm = mess_p%factors[i]; t = rep(coeff(tm, 0)); t %= to_ZZ(2); SetCoeff(mess, i, t); } } ZZX Batcher::num2ZZX(int num){ ZZX res; SetCoeff(res, 0 , 0); if(num == 0) return res; else{ for(int i=0; i<32; i++) SetCoeff(res, i, (num>>i)%2); } return res; }
the_stack
#include <opencv2/cudafeatures2d.hpp> #include "cuda_runtime.h" #include "device_launch_parameters.h" #include "labeling_algorithms.h" #include "register.h" #define BLOCK_ROWS 16 #define BLOCK_COLS 16 using namespace cv; // Algorithm itself has good performances, but memory allocation is a problem. // I will try to reduce it. namespace { // Only use it with unsigned numeric types template <typename T> __device__ __forceinline__ unsigned char HasBit(T bitmap, unsigned char pos) { return (bitmap >> pos) & 1; } __device__ __forceinline__ void SetBit(unsigned char &bitmap, unsigned char pos) { bitmap |= (1 << pos); } __global__ void Init(const cuda::PtrStepSzb img, cuda::PtrStepSzi labels, unsigned char *last_pixel) { unsigned row = (blockIdx.y * BLOCK_ROWS + threadIdx.y) * 2; unsigned col = (blockIdx.x * BLOCK_COLS + threadIdx.x) * 2; unsigned img_index = row * img.step + col; unsigned labels_index = row * (labels.step / labels.elem_size) + col; if (row < labels.rows && col < labels.cols) { unsigned P0 = 0x777; unsigned P = 0; if (img[img_index]) { P |= P0; } if (col + 1 < img.cols) { if (img[img_index + 1]) { P |= (P0 << 1); } if (row + 1 < img.rows && img[img_index + img.step + 1]) { P |= (P0 << 5); } } if (row + 1 < img.rows) { if (img[img_index + img.step]) { P |= (P0 << 4); } } if (col == 0) { P &= 0xEEEE; } if (col + 1 >= img.cols) { P &= 0x3333; } else if (col + 2 >= img.cols) { P &= 0x7777; } if (row == 0) { P &= 0xFFF0; } if (row + 1 >= img.rows) { P &= 0xFF; } else if (row + 2 >= img.rows) { P &= 0xFFF; } // P is now ready to be used to find neighbour blocks (or it should be) // P value avoids range errors unsigned char conn_bitmask = 0; if (P > 0) { labels[labels_index] = labels_index + 1; if (HasBit(P, 0) && img[img_index - img.step - 1]) { SetBit(conn_bitmask, 0); } if ((HasBit(P, 1) && img[img_index - img.step]) || (HasBit(P, 2) && img[img_index + 1 - img.step])) { SetBit(conn_bitmask, 1); } if (HasBit(P, 3) && img[img_index + 2 - img.step]) { SetBit(conn_bitmask, 2); } if ((HasBit(P, 4) && img[img_index - 1]) || (HasBit(P, 8) && img[img_index + img.step - 1])) { SetBit(conn_bitmask, 3); } if ((HasBit(P, 7) && img[img_index + 2]) || (HasBit(P, 11) && img[img_index + img.step + 2])) { SetBit(conn_bitmask, 4); } if (HasBit(P, 12) && img[img_index + 2 * img.step - 1]) { SetBit(conn_bitmask, 5); } if ((HasBit(P, 13) && img[img_index + 2 * img.step]) || (HasBit(P, 14) && img[img_index + 2 * img.step + 1])) { SetBit(conn_bitmask, 6); } if (HasBit(P, 15) && img[img_index + 2 * img.step + 2]) { SetBit(conn_bitmask, 7); } } else { labels[labels_index] = 0; } // Connection bitmask is stored in the north-east int of every block // If columns are odd, in the last column, it's stored in the south-west of every block instead // If columns are odd and rows are odd, it's stored in *last_pixel if (col + 1 < labels.cols) labels[labels_index + 1] = conn_bitmask; else if (row + 1 < labels.rows) labels[labels_index + (labels.step / labels.elem_size)] = conn_bitmask; else *last_pixel = conn_bitmask; } } __device__ unsigned int MinLabel(unsigned l1, unsigned l2) { if (l1 && l2) return min(l1, l2); else return l1; } __device__ unsigned int FindMinLabel(cuda::PtrStepSzi labels, unsigned char neighbours, unsigned label, unsigned labels_index) { unsigned int min = label; if (HasBit(neighbours, 0)) { min = MinLabel(min, labels.data[labels_index - 2 * (labels.step / labels.elem_size) - 2]); } if (HasBit(neighbours, 1)) { min = MinLabel(min, labels.data[labels_index - 2 * (labels.step / labels.elem_size)]); } if (HasBit(neighbours, 2)) { min = MinLabel(min, labels.data[labels_index - 2 * (labels.step / labels.elem_size) + 2]); } if (HasBit(neighbours, 3)) { min = MinLabel(min, labels.data[labels_index - 2]); } if (HasBit(neighbours, 4)) { min = MinLabel(min, labels.data[labels_index + 2]); } if (HasBit(neighbours, 5)) { min = MinLabel(min, labels.data[labels_index + 2 * (labels.step / labels.elem_size) - 2]); } if (HasBit(neighbours, 6)) { min = MinLabel(min, labels.data[labels_index + 2 * (labels.step / labels.elem_size)]); } if (HasBit(neighbours, 7)) { min = MinLabel(min, labels.data[labels_index + 2 * (labels.step / labels.elem_size) + 2]); } return min; } __global__ void Scan(cuda::PtrStepSzi labels, unsigned char *changes, unsigned char *last_pixel) { unsigned row = (blockIdx.y * BLOCK_ROWS + threadIdx.y) * 2; unsigned col = (blockIdx.x * BLOCK_COLS + threadIdx.x) * 2; unsigned labels_index = row * (labels.step / labels.elem_size) + col; if (row < labels.rows && col < labels.cols) { unsigned char neighbours; if (col + 1 < labels.cols) neighbours = labels[labels_index + 1]; else if (row + 1 < labels.rows) neighbours = labels[labels_index + (labels.step / labels.elem_size)]; else neighbours = *last_pixel; unsigned label = labels[labels_index]; if (label) { unsigned min_label = FindMinLabel(labels, neighbours, label, labels_index); if (min_label < label) { labels[label - 1] = min(static_cast<unsigned int>(labels[label - 1]), min_label); *changes = 1; } } } } __global__ void Analyze(cuda::PtrStepSzi labels) { unsigned row = (blockIdx.y * BLOCK_ROWS + threadIdx.y) * 2; unsigned col = (blockIdx.x * BLOCK_COLS + threadIdx.x) * 2; unsigned labels_index = row * (labels.step / labels.elem_size) + col; if (row < labels.rows && col < labels.cols) { unsigned label = labels[labels_index]; if (label) { // Performances are the same as the paper variant unsigned index = labels_index; while (label - 1 != index) { index = label - 1; label = labels[index]; } labels[labels_index] = label; } } } __global__ void FinalLabeling(cuda::PtrStepSzi labels, const cuda::PtrStepSzb img) { unsigned row = (blockIdx.y * BLOCK_ROWS + threadIdx.y) * 2; unsigned col = (blockIdx.x * BLOCK_COLS + threadIdx.x) * 2; unsigned labels_index = row * (labels.step / labels.elem_size) + col; unsigned img_index = row * (img.step / img.elem_size) + col; if (row < labels.rows && col < labels.cols) { unsigned int label = labels[labels_index]; if (img[img_index]) {} // labels[labels_index] = label; else { labels[labels_index] = 0; } if (col + 1 < labels.cols) { if (img[img_index + 1]) labels[labels_index + 1] = label; else { labels[labels_index + 1] = 0; } if (row + 1 < labels.rows) { if (img[img_index + img.step + 1]) labels[labels_index + (labels.step / labels.elem_size) + 1] = label; else { labels[labels_index + (labels.step / labels.elem_size) + 1] = 0; } } } if (row + 1 < labels.rows) { if (img[img_index + img.step]) labels[labels_index + (labels.step / labels.elem_size)] = label; else { labels[labels_index + (labels.step / labels.elem_size)] = 0; } } } } } class BE_LIGHT : public GpuLabeling2D<Connectivity2D::CONN_8> { private: dim3 grid_size_; dim3 block_size_; char changes_; unsigned char *d_changes_; bool d_changed_alloc_ = false; unsigned char *last_pixel_; public: BE_LIGHT() {} void PerformLabeling() { d_img_labels_.create(d_img_.size(), CV_32SC1); if (d_img_.rows == 1) { if (d_img_.cols == 1) { d_img_.convertTo(d_img_labels_, CV_32SC1); return; } else if (d_img_.cols % 2) { cudaMalloc(&d_changes_, sizeof(unsigned char) * 2); d_changed_alloc_ = true; last_pixel_ = d_changes_ + 1; } else { cudaMalloc(&d_changes_, sizeof(unsigned char)); d_changed_alloc_ = true; } } else if (d_img_.cols == 1) { if (d_img_.rows % 2) { cudaMalloc(&d_changes_, sizeof(unsigned char) * 2); d_changed_alloc_ = true; last_pixel_ = d_changes_ + 1; } else { cudaMalloc(&d_changes_, sizeof(unsigned char)); d_changed_alloc_ = true; } } else { d_changes_ = d_img_labels_.data + d_img_labels_.step; last_pixel_ = d_img_labels_.data + d_img_labels_.step + sizeof(unsigned int); } grid_size_ = dim3((((d_img_.cols + 1) / 2) + BLOCK_COLS - 1) / BLOCK_COLS, (((d_img_.rows + 1) / 2) + BLOCK_ROWS - 1) / BLOCK_ROWS, 1); block_size_ = dim3(BLOCK_COLS, BLOCK_ROWS, 1); Init << <grid_size_, block_size_ >> >(d_img_, d_img_labels_, last_pixel_); //cuda::GpuMat d_expanded_connections; //d_expanded_connections.create(d_connections_.rows * 3, d_connections_.cols * 3, CV_8UC1); //ExpandConnections << <grid_size_, block_size_ >> > (d_connections_, d_expanded_connections); //Mat1b expanded_connections; //d_expanded_connections.download(expanded_connections); //d_expanded_connections.release(); //Mat1i init_labels; //d_block_labels_.download(init_labels); while (true) { changes_ = 0; cudaMemcpy(d_changes_, &changes_, sizeof(unsigned char), cudaMemcpyHostToDevice); Scan << <grid_size_, block_size_ >> > (d_img_labels_, d_changes_, last_pixel_); cudaMemcpy(&changes_, d_changes_, sizeof(unsigned char), cudaMemcpyDeviceToHost); if (!changes_) break; Analyze << <grid_size_, block_size_ >> > (d_img_labels_); } //Mat1i block_info_final; //d_img_labels_.download(block_info_final); /*if ((img_.rows % 2) && (img_.cols % 2)) LastPixel << <1, 1 >> > (d_img_labels_, last_pixel_); */ FinalLabeling << <grid_size_, block_size_ >> >(d_img_labels_, d_img_); // d_img_labels_.download(img_labels_); if (d_changed_alloc_) cudaFree(d_changes_); } private: bool Alloc() { d_img_labels_.create(d_img_.size(), CV_32SC1); if (d_img_.rows == 1) { if (d_img_.cols == 1) { d_img_.convertTo(d_img_labels_, CV_32SC1); return true; } else if (d_img_.cols % 2) { cudaMalloc(&d_changes_, sizeof(unsigned char) * 2); last_pixel_ = d_changes_ + 1; } else { cudaMalloc(&d_changes_, sizeof(unsigned char)); } } else if (d_img_.cols == 1) { if (d_img_.rows % 2) { cudaMalloc(&d_changes_, sizeof(unsigned char) * 2); last_pixel_ = d_changes_ + 1; } else { cudaMalloc(&d_changes_, sizeof(unsigned char)); } } else { d_changes_ = d_img_labels_.data + d_img_labels_.step; last_pixel_ = d_img_labels_.data + d_img_labels_.step + sizeof(unsigned int); } return false; } void Dealloc() { if (d_changed_alloc_) cudaFree(d_changes_); } double MemoryTransferHostToDevice() { perf_.start(); d_img_.upload(img_); perf_.stop(); return perf_.last(); } void MemoryTransferDeviceToHost() { d_img_labels_.download(img_labels_); } void AllScans() { last_pixel_ = d_changes_ + 1; grid_size_ = dim3((((d_img_.cols + 1) / 2) + BLOCK_COLS - 1) / BLOCK_COLS, (((d_img_.rows + 1) / 2) + BLOCK_ROWS - 1) / BLOCK_ROWS, 1); block_size_ = dim3(BLOCK_COLS, BLOCK_ROWS, 1); Init << <grid_size_, block_size_ >> >(d_img_, d_img_labels_, last_pixel_); //cuda::GpuMat d_expanded_connections; //d_expanded_connections.create(d_connections_.rows * 3, d_connections_.cols * 3, CV_8UC1); //ExpandConnections << <grid_size_, block_size_ >> > (d_connections_, d_expanded_connections); //Mat1b expanded_connections; //d_expanded_connections.download(expanded_connections); //d_expanded_connections.release(); //Mat1i init_labels; //d_block_labels_.download(init_labels); while (true) { changes_ = 0; cudaMemcpy(d_changes_, &changes_, sizeof(unsigned char), cudaMemcpyHostToDevice); Scan << <grid_size_, block_size_ >> > (d_img_labels_, d_changes_, last_pixel_); cudaMemcpy(&changes_, d_changes_, sizeof(unsigned char), cudaMemcpyDeviceToHost); if (!changes_) break; Analyze << <grid_size_, block_size_ >> > (d_img_labels_); } //Mat1i block_labels; //d_block_labels_.download(block_labels); FinalLabeling << <grid_size_, block_size_ >> >(d_img_labels_, d_img_); cudaDeviceSynchronize(); } public: void PerformLabelingWithSteps() { perf_.start(); bool done = Alloc(); perf_.stop(); double alloc_timing = perf_.last(); if (!done) { perf_.start(); AllScans(); perf_.stop(); perf_.store(Step(StepType::ALL_SCANS), perf_.last()); } perf_.start(); Dealloc(); perf_.stop(); double dealloc_timing = perf_.last(); perf_.store(Step(StepType::ALLOC_DEALLOC), alloc_timing + dealloc_timing); } }; REGISTER_LABELING(BE_LIGHT);
the_stack
extern "C" { #include <ccv.h> #include <ccv_internal.h> #include <nnc/ccv_nnc.h> #include <nnc/ccv_nnc_easy.h> #include <nnc/ccv_nnc_internal.h> } #include <nnc/gpu/ccv_nnc_compat.h> static int _ccv_nnc_data_transfer(const ccv_nnc_cmd_t cmd, const ccv_nnc_hint_t hint, const int flags, ccv_nnc_tensor_t* const* const inputs, const int input_size, ccv_nnc_tensor_t* const* const outputs, const int output_size, ccv_nnc_stream_context_t* const stream_context) { int i; for (i = 0; i < ccv_min(input_size, output_size); i++) { const ccv_nnc_tensor_t* a = inputs[i]; ccv_nnc_tensor_t* b = outputs[i]; if (a == b) continue; assert(!CCV_IS_TENSOR_VIEW(a)); assert(!CCV_IS_TENSOR_VIEW(b)); assert(ccv_nnc_tensor_count(a->info) == ccv_nnc_tensor_count(b->info)); assert(CCV_GET_DATA_TYPE_SIZE(a->info.datatype) == CCV_GET_DATA_TYPE_SIZE(b->info.datatype)); const size_t size = (ssize_t)ccv_nnc_tensor_count(a->info) * CCV_GET_DATA_TYPE_SIZE(a->info.datatype); if (stream_context) { cudaStream_t stream = ccv_nnc_stream_context_get_stream(stream_context); if (CCV_TENSOR_GET_MEMORY(a->info.type) == CCV_TENSOR_CPU_MEMORY && CCV_TENSOR_GET_MEMORY(b->info.type) == CCV_TENSOR_GPU_MEMORY) CUDA_ENFORCE(cudaMemcpyAsync(b->data.u8, a->data.u8, size, cudaMemcpyHostToDevice, stream)); else if (CCV_TENSOR_GET_MEMORY(a->info.type) == CCV_TENSOR_GPU_MEMORY && CCV_TENSOR_GET_MEMORY(b->info.type) == CCV_TENSOR_CPU_MEMORY) CUDA_ENFORCE(cudaMemcpyAsync(b->data.u8, a->data.u8, size, cudaMemcpyDeviceToHost, stream)); else if (CCV_TENSOR_GET_MEMORY(a->info.type) == CCV_TENSOR_CPU_MEMORY && CCV_TENSOR_GET_MEMORY(b->info.type) == CCV_TENSOR_CPU_MEMORY) CUDA_ENFORCE(cudaMemcpyAsync(b->data.u8, a->data.u8, size, cudaMemcpyHostToHost, stream)); else if (CCV_TENSOR_GET_MEMORY(a->info.type) == CCV_TENSOR_GPU_MEMORY && CCV_TENSOR_GET_MEMORY(b->info.type) == CCV_TENSOR_GPU_MEMORY) { const int device_a = CCV_TENSOR_GET_DEVICE_ID(a->info.type); const int device_b = CCV_TENSOR_GET_DEVICE_ID(b->info.type); if (device_a == device_b) CUDA_ENFORCE(cudaMemcpyAsync(b->data.u8, a->data.u8, size, cudaMemcpyDeviceToDevice, stream)); else CUDA_ENFORCE(cudaMemcpyPeerAsync(b->data.u8, device_b, a->data.u8, device_a, size, stream)); } } else { if (CCV_TENSOR_GET_MEMORY(a->info.type) == CCV_TENSOR_CPU_MEMORY && CCV_TENSOR_GET_MEMORY(b->info.type) == CCV_TENSOR_GPU_MEMORY) CUDA_ENFORCE(cudaMemcpy(b->data.u8, a->data.u8, size, cudaMemcpyHostToDevice)); else if (CCV_TENSOR_GET_MEMORY(a->info.type) == CCV_TENSOR_GPU_MEMORY && CCV_TENSOR_GET_MEMORY(b->info.type) == CCV_TENSOR_CPU_MEMORY) CUDA_ENFORCE(cudaMemcpy(b->data.u8, a->data.u8, size, cudaMemcpyDeviceToHost)); else if (CCV_TENSOR_GET_MEMORY(a->info.type) == CCV_TENSOR_CPU_MEMORY && CCV_TENSOR_GET_MEMORY(b->info.type) == CCV_TENSOR_CPU_MEMORY) CUDA_ENFORCE(cudaMemcpy(b->data.u8, a->data.u8, size, cudaMemcpyHostToHost)); else if (CCV_TENSOR_GET_MEMORY(a->info.type) == CCV_TENSOR_GPU_MEMORY && CCV_TENSOR_GET_MEMORY(b->info.type) == CCV_TENSOR_GPU_MEMORY) { const int device_a = CCV_TENSOR_GET_DEVICE_ID(a->info.type); const int device_b = CCV_TENSOR_GET_DEVICE_ID(b->info.type); if (device_a == device_b) CUDA_ENFORCE(cudaMemcpy(b->data.u8, a->data.u8, size, cudaMemcpyDeviceToDevice)); else CUDA_ENFORCE(cudaMemcpyPeer(b->data.u8, device_b, a->data.u8, device_a, size)); } } } return CCV_NNC_EXEC_SUCCESS; } REGISTER_COMMAND_BACKEND(CCV_NNC_DATA_TRANSFER_FORWARD, CCV_NNC_BACKEND_GPU_REF)(ccv_nnc_cmd_backend_registry_t* const registry) { registry->tensor_formats = CCV_TENSOR_FORMAT_NCHW | CCV_TENSOR_FORMAT_NHWC | CCV_TENSOR_FORMAT_CHWN; registry->tensor_datatypes = CCV_64F | CCV_32F | CCV_16F | CCV_32S; registry->tensor_memory = CCV_TENSOR_CPU_MEMORY | CCV_TENSOR_GPU_MEMORY; registry->algorithms = 1; registry->exec = _ccv_nnc_data_transfer; } REGISTER_COMMAND_BACKEND(CCV_NNC_DATA_TRANSFER_BACKWARD, CCV_NNC_BACKEND_GPU_REF)(ccv_nnc_cmd_backend_registry_t* const registry) { registry->tensor_formats = CCV_TENSOR_FORMAT_NCHW | CCV_TENSOR_FORMAT_NHWC | CCV_TENSOR_FORMAT_CHWN; registry->tensor_datatypes = CCV_64F | CCV_32F | CCV_16F | CCV_32S; registry->tensor_memory = CCV_TENSOR_CPU_MEMORY | CCV_TENSOR_GPU_MEMORY; registry->algorithms = 1; registry->exec = _ccv_nnc_data_transfer; } template<typename NUM1, typename NUM2> __global__ void _ccv_nnc_data_conversion_kernel(const size_t count, const NUM1* const a, NUM2* const b) { CUDA_1D_KERNEL_LOOP(i, count) { b[i] = a[i]; } } static int _ccv_nnc_datatype_conversion(const ccv_nnc_cmd_t cmd, const ccv_nnc_hint_t hint, const int flags, ccv_nnc_tensor_t* const* const inputs, const int input_size, ccv_nnc_tensor_t* const* const outputs, const int output_size, ccv_nnc_stream_context_t* const stream_context) { assert(output_size <= input_size); int i; for (i = 0; i < output_size; i++) { const ccv_nnc_tensor_view_t* a = (ccv_nnc_tensor_view_t*)inputs[i]; ccv_nnc_tensor_view_t* b = (ccv_nnc_tensor_view_t*)outputs[i]; assert(a != b); // Cannot do inplace transform. assert(a->info.format == b->info.format); assert(CCV_TENSOR_GET_DEVICE_ID(a->info.type) == CCV_TENSOR_GET_DEVICE_ID(b->info.type)); cudaStream_t stream = ccv_nnc_stream_context_get_stream(stream_context); const size_t tensor_count = ccv_nnc_tensor_count(a->info); if (a->info.datatype == b->info.datatype) { // If it is the same, just do a normal data transfer. const size_t size = tensor_count * CCV_GET_DATA_TYPE_SIZE(a->type); cudaMemcpyAsync(b->data.u8, a->data.u8, size, cudaMemcpyDeviceToDevice, stream); } else if (a->info.datatype == CCV_32F && b->info.datatype == CCV_16F) { assert(!CCV_IS_TENSOR_VIEW(a)); assert(!CCV_IS_TENSOR_VIEW(b)); assert(tensor_count == ccv_nnc_tensor_count(b->info)); _ccv_nnc_data_conversion_kernel<<<CUDA_GET_BLOCKS(tensor_count), CUDA_NUM_THREADS, 0, stream>>>(tensor_count, a->data.f32, (__half*)b->data.f16); } else if (a->info.datatype == CCV_16F && b->info.datatype == CCV_32F) { assert(!CCV_IS_TENSOR_VIEW(a)); assert(!CCV_IS_TENSOR_VIEW(b)); const int tensor_count = ccv_nnc_tensor_count(a->info); assert(tensor_count == ccv_nnc_tensor_count(b->info)); _ccv_nnc_data_conversion_kernel<<<CUDA_GET_BLOCKS(tensor_count), CUDA_NUM_THREADS, 0, stream>>>(tensor_count, (__half*)a->data.f16, b->data.f32); } else if (a->info.datatype == CCV_64F && b->info.datatype == CCV_32F) { assert(!CCV_IS_TENSOR_VIEW(a)); assert(!CCV_IS_TENSOR_VIEW(b)); assert(tensor_count == ccv_nnc_tensor_count(b->info)); _ccv_nnc_data_conversion_kernel<<<CUDA_GET_BLOCKS(tensor_count), CUDA_NUM_THREADS, 0, stream>>>(tensor_count, a->data.f64, b->data.f32); } else if (a->info.datatype == CCV_32F && b->info.datatype == CCV_64F) { assert(!CCV_IS_TENSOR_VIEW(a)); assert(!CCV_IS_TENSOR_VIEW(b)); const int tensor_count = ccv_nnc_tensor_count(a->info); assert(tensor_count == ccv_nnc_tensor_count(b->info)); _ccv_nnc_data_conversion_kernel<<<CUDA_GET_BLOCKS(tensor_count), CUDA_NUM_THREADS, 0, stream>>>(tensor_count, a->data.f32, b->data.f64); } else if (a->info.datatype == CCV_64F && b->info.datatype == CCV_16F) { assert(!CCV_IS_TENSOR_VIEW(a)); assert(!CCV_IS_TENSOR_VIEW(b)); assert(tensor_count == ccv_nnc_tensor_count(b->info)); _ccv_nnc_data_conversion_kernel<<<CUDA_GET_BLOCKS(tensor_count), CUDA_NUM_THREADS, 0, stream>>>(tensor_count, a->data.f64, (__half*)b->data.f16); } else if (a->info.datatype == CCV_16F && b->info.datatype == CCV_64F) { assert(!CCV_IS_TENSOR_VIEW(a)); assert(!CCV_IS_TENSOR_VIEW(b)); const int tensor_count = ccv_nnc_tensor_count(a->info); assert(tensor_count == ccv_nnc_tensor_count(b->info)); _ccv_nnc_data_conversion_kernel<<<CUDA_GET_BLOCKS(tensor_count), CUDA_NUM_THREADS, 0, stream>>>(tensor_count, (__half*)a->data.f16, b->data.f64); } } return CCV_NNC_EXEC_SUCCESS; } REGISTER_COMMAND_BACKEND(CCV_NNC_DATATYPE_CONVERSION_FORWARD, CCV_NNC_BACKEND_GPU_REF)(ccv_nnc_cmd_backend_registry_t* const registry) { registry->tensor_formats = CCV_TENSOR_FORMAT_NCHW | CCV_TENSOR_FORMAT_NHWC | CCV_TENSOR_FORMAT_CHWN; registry->tensor_datatypes = CCV_64F | CCV_32F | CCV_16F; registry->tensor_memory = CCV_TENSOR_GPU_MEMORY; registry->algorithms = 1; registry->exec = _ccv_nnc_datatype_conversion; } REGISTER_COMMAND_BACKEND(CCV_NNC_DATATYPE_CONVERSION_BACKWARD, CCV_NNC_BACKEND_GPU_REF)(ccv_nnc_cmd_backend_registry_t* const registry) { registry->tensor_formats = CCV_TENSOR_FORMAT_NCHW | CCV_TENSOR_FORMAT_NHWC | CCV_TENSOR_FORMAT_CHWN; registry->tensor_datatypes = CCV_64F | CCV_32F | CCV_16F; registry->tensor_memory = CCV_TENSOR_GPU_MEMORY; registry->algorithms = 1; registry->exec = _ccv_nnc_datatype_conversion; } template<typename NUM1, typename NUM2> __global__ void _ccv_nnc_masked_fill_kernel(const size_t a_count, const size_t b_count, const NUM2 p, const NUM1 q, const NUM1* const a, const NUM2* const b, NUM1* const c) { CUDA_1D_KERNEL_LOOP(i, a_count) { c[i] = (b[i % b_count] == p) ? q : a[i]; } } static void _ccv_nnc_masked_fill_gpu_ref(const float p, const float q, ccv_nnc_tensor_view_t* const a, ccv_nnc_tensor_view_t* const b, ccv_nnc_tensor_view_t* const c, ccv_nnc_stream_context_t* const stream_context) { assert(c->info.datatype == a->info.datatype); cudaStream_t stream = ccv_nnc_stream_context_get_stream(stream_context); const size_t a_count = ccv_nnc_tensor_count(a->info); const size_t b_count = ccv_nnc_tensor_count(b->info); assert(a_count >= b_count); assert(!CCV_IS_TENSOR_VIEW(a)); assert(!CCV_IS_TENSOR_VIEW(b)); assert(!CCV_IS_TENSOR_VIEW(c)); if (a->info.datatype == CCV_32F && b->info.datatype == CCV_32F) _ccv_nnc_masked_fill_kernel<<<CUDA_GET_BLOCKS(a_count), CUDA_NUM_THREADS, 0, stream>>>(a_count, b_count, p, q, a->data.f32, b->data.f32, c->data.f32); else if (a->info.datatype == CCV_32F && b->info.datatype == CCV_32S) _ccv_nnc_masked_fill_kernel<<<CUDA_GET_BLOCKS(a_count), CUDA_NUM_THREADS, 0, stream>>>(a_count, b_count, (int)(p + 0.5), q, a->data.f32, b->data.i32, c->data.f32); else if (a->info.datatype == CCV_32F && b->info.datatype == CCV_16F) _ccv_nnc_masked_fill_kernel<<<CUDA_GET_BLOCKS(a_count), CUDA_NUM_THREADS, 0, stream>>>(a_count, b_count, (__half)p, q, a->data.f32, (__half*)b->data.f16, c->data.f32); else if (a->info.datatype == CCV_16F && b->info.datatype == CCV_32F) _ccv_nnc_masked_fill_kernel<<<CUDA_GET_BLOCKS(a_count), CUDA_NUM_THREADS, 0, stream>>>(a_count, b_count, p, (__half)q, (__half*)a->data.f16, b->data.f32, (__half*)c->data.f16); else if (a->info.datatype == CCV_16F && b->info.datatype == CCV_32S) _ccv_nnc_masked_fill_kernel<<<CUDA_GET_BLOCKS(a_count), CUDA_NUM_THREADS, 0, stream>>>(a_count, b_count, (int)(p + 0.5), (__half)q, (__half*)a->data.f16, b->data.i32, (__half*)c->data.f16); else if (a->info.datatype == CCV_16F && b->info.datatype == CCV_16F) _ccv_nnc_masked_fill_kernel<<<CUDA_GET_BLOCKS(a_count), CUDA_NUM_THREADS, 0, stream>>>(a_count, b_count, (__half)p, (__half)q, (__half*)a->data.f16, (__half*)b->data.f16, (__half*)c->data.f16); else if (a->info.datatype == CCV_32S && b->info.datatype == CCV_32F) _ccv_nnc_masked_fill_kernel<<<CUDA_GET_BLOCKS(a_count), CUDA_NUM_THREADS, 0, stream>>>(a_count, b_count, p, (int)(q + 0.5), a->data.i32, b->data.f32, c->data.i32); else if (a->info.datatype == CCV_32S && b->info.datatype == CCV_32S) _ccv_nnc_masked_fill_kernel<<<CUDA_GET_BLOCKS(a_count), CUDA_NUM_THREADS, 0, stream>>>(a_count, b_count, (int)(p + 0.5), (int)(q + 0.5), a->data.i32, b->data.i32, c->data.i32); else if (a->info.datatype == CCV_32S && b->info.datatype == CCV_16F) _ccv_nnc_masked_fill_kernel<<<CUDA_GET_BLOCKS(a_count), CUDA_NUM_THREADS, 0, stream>>>(a_count, b_count, (__half)p, (int)(q + 0.5), a->data.i32, (__half*)b->data.f16, c->data.i32); } static int _ccv_nnc_masked_fill_forw(const ccv_nnc_cmd_t cmd, const ccv_nnc_hint_t hint, const int flags, ccv_nnc_tensor_t* const* const inputs, const int input_size, ccv_nnc_tensor_t* const* const outputs, const int output_size, ccv_nnc_stream_context_t* const stream_context) { assert(input_size >= 2); assert(inputs[0]); assert(inputs[1]); assert(outputs[0]); _ccv_nnc_masked_fill_gpu_ref(cmd.info.blas.a[0], cmd.info.blas.a[1], (ccv_nnc_tensor_view_t*)inputs[0], (ccv_nnc_tensor_view_t*)inputs[1], (ccv_nnc_tensor_view_t*)outputs[0], stream_context); return CCV_NNC_EXEC_SUCCESS; } static int _ccv_nnc_masked_fill_back(const ccv_nnc_cmd_t cmd, const ccv_nnc_hint_t hint, const int flags, ccv_nnc_tensor_t* const* const inputs, const int input_size, ccv_nnc_tensor_t* const* const outputs, const int output_size, ccv_nnc_stream_context_t* const stream_context) { assert(input_size >= 3); _ccv_nnc_masked_fill_gpu_ref(cmd.info.blas.a[0], 0, (ccv_nnc_tensor_view_t*)inputs[0], (ccv_nnc_tensor_view_t*)inputs[2], (ccv_nnc_tensor_view_t*)outputs[0], stream_context); // TODO: doesn't really support taking gradient on mask. // if (output_size >= 2 && outputs[1]) return CCV_NNC_EXEC_SUCCESS; } REGISTER_COMMAND_BACKEND(CCV_NNC_MASKED_FILL_FORWARD, CCV_NNC_BACKEND_GPU_REF)(ccv_nnc_cmd_backend_registry_t* const registry) { registry->tensor_formats = CCV_TENSOR_FORMAT_NCHW | CCV_TENSOR_FORMAT_NHWC | CCV_TENSOR_FORMAT_CHWN; registry->tensor_datatypes = CCV_32F | CCV_32S | CCV_16F; registry->tensor_memory = CCV_TENSOR_GPU_MEMORY; registry->algorithms = 1; registry->exec = _ccv_nnc_masked_fill_forw; } REGISTER_COMMAND_BACKEND(CCV_NNC_MASKED_FILL_BACKWARD, CCV_NNC_BACKEND_GPU_REF)(ccv_nnc_cmd_backend_registry_t* const registry) { registry->tensor_formats = CCV_TENSOR_FORMAT_NCHW | CCV_TENSOR_FORMAT_NHWC | CCV_TENSOR_FORMAT_CHWN; registry->tensor_datatypes = CCV_32F | CCV_32S | CCV_16F; registry->tensor_memory = CCV_TENSOR_GPU_MEMORY; registry->algorithms = 1; registry->exec = _ccv_nnc_masked_fill_back; }
the_stack
#include <ATen/ATen.h> #include "grid_sampler_cuda.cuh" #include <ATen/cuda/CUDAContext.h> #include <ATen/cuda/CUDAApplyUtils.cuh> #include <ATen/cuda/detail/TensorInfo.cuh> #include <ATen/cuda/detail/IndexUtils.cuh> #include <ATen/cuda/detail/KernelUtils.h> #include <c10/macros/Macros.h> namespace mmdetection { using namespace at::cuda::detail; using mmdetection::detail::GridSamplerInterpolation; using mmdetection::detail::GridSamplerPadding; namespace { template <typename scalar_t> C10_LAUNCH_BOUNDS_1(1024) __global__ void grid_sampler_2d_forward_kernel_cuda( const int nthreads, TensorInfo<scalar_t, int> input, TensorInfo<scalar_t, int> grid, TensorInfo<scalar_t, int> output, const GridSamplerInterpolation interpolation_mode, const GridSamplerPadding padding_mode, bool align_corners) { int C = input.sizes[1]; int inp_H = input.sizes[2]; int inp_W = input.sizes[3]; int out_H = grid.sizes[1]; int out_W = grid.sizes[2]; int inp_sN = input.strides[0]; int inp_sC = input.strides[1]; int inp_sH = input.strides[2]; int inp_sW = input.strides[3]; int grid_sN = grid.strides[0]; int grid_sH = grid.strides[1]; int grid_sW = grid.strides[2]; int grid_sCoor = grid.strides[3]; int out_sN = output.strides[0]; int out_sC = output.strides[1]; int out_sH = output.strides[2]; int out_sW = output.strides[3]; CUDA_KERNEL_LOOP(index, nthreads) { const int w = index % out_W; const int h = (index / out_W) % out_H; const int n = index / (out_H * out_W); const int grid_offset = n * grid_sN + h * grid_sH + w * grid_sW; // get the corresponding input x, y co-ordinates from grid scalar_t ix = grid.data[grid_offset]; scalar_t iy = grid.data[grid_offset + grid_sCoor]; ix = grid_sampler_compute_source_index(ix, inp_W, padding_mode, align_corners); iy = grid_sampler_compute_source_index(iy, inp_H, padding_mode, align_corners); if (interpolation_mode == GridSamplerInterpolation::Bilinear) { // get NE, NW, SE, SW pixel values from (x, y) int ix_nw = static_cast<int>(::floor(ix)); int iy_nw = static_cast<int>(::floor(iy)); int ix_ne = ix_nw + 1; int iy_ne = iy_nw; int ix_sw = ix_nw; int iy_sw = iy_nw + 1; int ix_se = ix_nw + 1; int iy_se = iy_nw + 1; // get surfaces to each neighbor: scalar_t nw = (ix_se - ix) * (iy_se - iy); scalar_t ne = (ix - ix_sw) * (iy_sw - iy); scalar_t sw = (ix_ne - ix) * (iy - iy_ne); scalar_t se = (ix - ix_nw) * (iy - iy_nw); // calculate bilinear weighted pixel value and set output pixel auto inp_ptr_NC = input.data + n * inp_sN; auto out_ptr_NCHW = output.data + n * out_sN + h * out_sH + w * out_sW; for (int c = 0; c < C; ++c, inp_ptr_NC += inp_sC, out_ptr_NCHW += out_sC) { *out_ptr_NCHW = static_cast<scalar_t>(0); if (within_bounds_2d(iy_nw, ix_nw, inp_H, inp_W)) { *out_ptr_NCHW += inp_ptr_NC[iy_nw * inp_sH + ix_nw * inp_sW] * nw; } if (within_bounds_2d(iy_ne, ix_ne, inp_H, inp_W)) { *out_ptr_NCHW += inp_ptr_NC[iy_ne * inp_sH + ix_ne * inp_sW] * ne; } if (within_bounds_2d(iy_sw, ix_sw, inp_H, inp_W)) { *out_ptr_NCHW += inp_ptr_NC[iy_sw * inp_sH + ix_sw * inp_sW] * sw; } if (within_bounds_2d(iy_se, ix_se, inp_H, inp_W)) { *out_ptr_NCHW += inp_ptr_NC[iy_se * inp_sH + ix_se * inp_sW] * se; } } } else if (interpolation_mode == GridSamplerInterpolation::Nearest) { int ix_nearest = static_cast<int>(::round(ix)); int iy_nearest = static_cast<int>(::round(iy)); // assign nearest neighor pixel value to output pixel auto inp_ptr_NC = input.data + n * inp_sN; auto out_ptr_NCHW = output.data + n * out_sN + h * out_sH + w * out_sW; for (int c = 0; c < C; ++c, inp_ptr_NC += inp_sC, out_ptr_NCHW += out_sC) { if (within_bounds_2d(iy_nearest, ix_nearest, inp_H, inp_W)) { *out_ptr_NCHW = inp_ptr_NC[iy_nearest * inp_sH + ix_nearest * inp_sW]; } else { *out_ptr_NCHW = static_cast<scalar_t>(0); } } } } } template <typename scalar_t> C10_LAUNCH_BOUNDS_1(1024) __global__ void grid_sampler_3d_forward_kernel_cuda( const int nthreads, TensorInfo<scalar_t, int> input, TensorInfo<scalar_t, int> grid, TensorInfo<scalar_t, int> output, const GridSamplerInterpolation interpolation_mode, const GridSamplerPadding padding_mode, bool align_corners) { int C = input.sizes[1]; int inp_D = input.sizes[2]; int inp_H = input.sizes[3]; int inp_W = input.sizes[4]; int out_D = grid.sizes[1]; int out_H = grid.sizes[2]; int out_W = grid.sizes[3]; int inp_sN = input.strides[0]; int inp_sC = input.strides[1]; int inp_sD = input.strides[2]; int inp_sH = input.strides[3]; int inp_sW = input.strides[4]; int grid_sN = grid.strides[0]; int grid_sD = grid.strides[1]; int grid_sH = grid.strides[2]; int grid_sW = grid.strides[3]; int grid_sCoor = grid.strides[4]; int out_sN = output.strides[0]; int out_sC = output.strides[1]; int out_sD = output.strides[2]; int out_sH = output.strides[3]; int out_sW = output.strides[4]; CUDA_KERNEL_LOOP(index, nthreads) { const int w = index % out_W; const int h = (index / out_W) % out_H; const int d = (index / (out_H * out_W)) % out_D; const int n = index / (out_D * out_H * out_W); const int grid_offset = n * grid_sN + d * grid_sD + h * grid_sH + w * grid_sW; // get the corresponding input x, y, z co-ordinates from grid scalar_t ix = grid.data[grid_offset]; scalar_t iy = grid.data[grid_offset + grid_sCoor]; scalar_t iz = grid.data[grid_offset + 2 * grid_sCoor]; ix = grid_sampler_compute_source_index(ix, inp_W, padding_mode, align_corners); iy = grid_sampler_compute_source_index(iy, inp_H, padding_mode, align_corners); iz = grid_sampler_compute_source_index(iz, inp_D, padding_mode, align_corners); if (interpolation_mode == GridSamplerInterpolation::Bilinear) { // get corner pixel values from (x, y, z) // for 4d, we used north-east-south-west // for 5d, we add top-bottom int ix_tnw = static_cast<int>(::floor(ix)); int iy_tnw = static_cast<int>(::floor(iy)); int iz_tnw = static_cast<int>(::floor(iz)); int ix_tne = ix_tnw + 1; int iy_tne = iy_tnw; int iz_tne = iz_tnw; int ix_tsw = ix_tnw; int iy_tsw = iy_tnw + 1; int iz_tsw = iz_tnw; int ix_tse = ix_tnw + 1; int iy_tse = iy_tnw + 1; int iz_tse = iz_tnw; int ix_bnw = ix_tnw; int iy_bnw = iy_tnw; int iz_bnw = iz_tnw + 1; int ix_bne = ix_tnw + 1; int iy_bne = iy_tnw; int iz_bne = iz_tnw + 1; int ix_bsw = ix_tnw; int iy_bsw = iy_tnw + 1; int iz_bsw = iz_tnw + 1; int ix_bse = ix_tnw + 1; int iy_bse = iy_tnw + 1; int iz_bse = iz_tnw + 1; // get surfaces to each neighbor: scalar_t tnw = (ix_bse - ix) * (iy_bse - iy) * (iz_bse - iz); scalar_t tne = (ix - ix_bsw) * (iy_bsw - iy) * (iz_bsw - iz); scalar_t tsw = (ix_bne - ix) * (iy - iy_bne) * (iz_bne - iz); scalar_t tse = (ix - ix_bnw) * (iy - iy_bnw) * (iz_bnw - iz); scalar_t bnw = (ix_tse - ix) * (iy_tse - iy) * (iz - iz_tse); scalar_t bne = (ix - ix_tsw) * (iy_tsw - iy) * (iz - iz_tsw); scalar_t bsw = (ix_tne - ix) * (iy - iy_tne) * (iz - iz_tne); scalar_t bse = (ix - ix_tnw) * (iy - iy_tnw) * (iz - iz_tnw); auto inp_ptr_NC = input.data + n * inp_sN; auto out_ptr_NCDHW = output.data + n * out_sN + d * out_sD + h * out_sH + w * out_sW; for (int c = 0; c < C; ++c, inp_ptr_NC += inp_sC, out_ptr_NCDHW += out_sC) { // (c, iz_tnw, iy_tnw, ix_tnw) * tnw + (c, iz_tne, iy_tne, ix_tne) * tne // + (c, iz_tsw, iy_tsw, ix_tsw) * tsw + (c, iz_tse, iy_tse, ix_tse) * tse // + (c, iz_bnw, iy_bnw, ix_bnw) * bnw + (c, iz_bne, iy_bne, ix_bne) * bne // + (c, iz_bsw, iy_bsw, ix_bsw) * bsw + (c, iz_bse, iy_bse, ix_bse) * bse *out_ptr_NCDHW = static_cast<scalar_t>(0); if (within_bounds_3d(iz_tnw, iy_tnw, ix_tnw, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_tnw * inp_sD + iy_tnw * inp_sH + ix_tnw * inp_sW] * tnw; } if (within_bounds_3d(iz_tne, iy_tne, ix_tne, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_tne * inp_sD + iy_tne * inp_sH + ix_tne * inp_sW] * tne; } if (within_bounds_3d(iz_tsw, iy_tsw, ix_tsw, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_tsw * inp_sD + iy_tsw * inp_sH + ix_tsw * inp_sW] * tsw; } if (within_bounds_3d(iz_tse, iy_tse, ix_tse, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_tse * inp_sD + iy_tse * inp_sH + ix_tse * inp_sW] * tse; } if (within_bounds_3d(iz_bnw, iy_bnw, ix_bnw, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_bnw * inp_sD + iy_bnw * inp_sH + ix_bnw * inp_sW] * bnw; } if (within_bounds_3d(iz_bne, iy_bne, ix_bne, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_bne * inp_sD + iy_bne * inp_sH + ix_bne * inp_sW] * bne; } if (within_bounds_3d(iz_bsw, iy_bsw, ix_bsw, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_bsw * inp_sD + iy_bsw * inp_sH + ix_bsw * inp_sW] * bsw; } if (within_bounds_3d(iz_bse, iy_bse, ix_bse, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_bse * inp_sD + iy_bse * inp_sH + ix_bse * inp_sW] * bse; } } } else if (interpolation_mode == GridSamplerInterpolation::Nearest) { int ix_nearest = static_cast<int>(::round(ix)); int iy_nearest = static_cast<int>(::round(iy)); int iz_nearest = static_cast<int>(::round(iz)); // assign nearest neighor pixel value to output pixel auto inp_ptr_NC = input.data + n * inp_sN; auto out_ptr_NCDHW = output.data + n * out_sN + d * out_sD + h * out_sH + w * out_sW; for (int c = 0; c < C; ++c, inp_ptr_NC += inp_sC, out_ptr_NCDHW += out_sC) { if (within_bounds_3d(iz_nearest, iy_nearest, ix_nearest, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW = inp_ptr_NC[iz_nearest * inp_sD + iy_nearest * inp_sH + ix_nearest * inp_sW]; } else { *out_ptr_NCDHW = static_cast<scalar_t>(0); } } } } } template <typename scalar_t> C10_LAUNCH_BOUNDS_1(1024) __global__ void grid_sampler_2d_backward_kernel_cuda( const int nthreads, TensorInfo<scalar_t, int> grad_output, TensorInfo<scalar_t, int> input, TensorInfo<scalar_t, int> grid, TensorInfo<scalar_t, int> grad_input, // initialized to zeros TensorInfo<scalar_t, int> grad_grid, // initialized to empty const GridSamplerInterpolation interpolation_mode, const GridSamplerPadding padding_mode, bool align_corners) { int C = input.sizes[1]; int inp_H = input.sizes[2]; int inp_W = input.sizes[3]; int out_H = grid.sizes[1]; int out_W = grid.sizes[2]; int inp_sN = input.strides[0]; int inp_sC = input.strides[1]; int inp_sH = input.strides[2]; int inp_sW = input.strides[3]; int grid_sN = grid.strides[0]; int grid_sH = grid.strides[1]; int grid_sW = grid.strides[2]; int grid_sCoor = grid.strides[3]; int gOut_sN = grad_output.strides[0]; int gOut_sC = grad_output.strides[1]; int gOut_sH = grad_output.strides[2]; int gOut_sW = grad_output.strides[3]; int gInp_sN = grad_input.strides[0]; int gInp_sC = grad_input.strides[1]; int gInp_sH = grad_input.strides[2]; int gInp_sW = grad_input.strides[3]; int gGrid_sW = grad_grid.strides[2]; CUDA_KERNEL_LOOP(index, nthreads) { const int w = index % out_W; const int h = (index / out_W) % out_H; const int n = index / (out_H * out_W); const int grid_offset = n * grid_sN + h * grid_sH + w * grid_sW; // get the corresponding input x, y co-ordinates from grid scalar_t ix = grid.data[grid_offset]; scalar_t iy = grid.data[grid_offset + grid_sCoor]; // multipliers for gradients on ix and iy scalar_t gix_mult, giy_mult; ix = grid_sampler_compute_source_index_set_grad(ix, inp_W, padding_mode, align_corners, &gix_mult); iy = grid_sampler_compute_source_index_set_grad(iy, inp_H, padding_mode, align_corners, &giy_mult); if (interpolation_mode == GridSamplerInterpolation::Bilinear) { // get NE, NW, SE, SW pixel values from (x, y) int ix_nw = static_cast<int>(::floor(ix)); int iy_nw = static_cast<int>(::floor(iy)); int ix_ne = ix_nw + 1; int iy_ne = iy_nw; int ix_sw = ix_nw; int iy_sw = iy_nw + 1; int ix_se = ix_nw + 1; int iy_se = iy_nw + 1; // get surfaces to each neighbor: scalar_t nw = (ix_se - ix) * (iy_se - iy); scalar_t ne = (ix - ix_sw) * (iy_sw - iy); scalar_t sw = (ix_ne - ix) * (iy - iy_ne); scalar_t se = (ix - ix_nw) * (iy - iy_nw); scalar_t gix = static_cast<scalar_t>(0), giy = static_cast<scalar_t>(0); scalar_t *gOut_ptr_NCHW = grad_output.data + n * gOut_sN + h * gOut_sH + w * gOut_sW; scalar_t *gInp_ptr_NC = grad_input.data + n * gInp_sN; scalar_t *inp_ptr_NC = input.data + n * inp_sN; for (int c = 0; c < C; ++c, inp_ptr_NC += inp_sC, gInp_ptr_NC += gInp_sC, gOut_ptr_NCHW += gOut_sC) { scalar_t gOut = *gOut_ptr_NCHW; // calculate and set grad_input safe_add_2d(gInp_ptr_NC, iy_nw, ix_nw, gInp_sH, gInp_sW, inp_H, inp_W, nw * gOut); safe_add_2d(gInp_ptr_NC, iy_ne, ix_ne, gInp_sH, gInp_sW, inp_H, inp_W, ne * gOut); safe_add_2d(gInp_ptr_NC, iy_sw, ix_sw, gInp_sH, gInp_sW, inp_H, inp_W, sw * gOut); safe_add_2d(gInp_ptr_NC, iy_se, ix_se, gInp_sH, gInp_sW, inp_H, inp_W, se * gOut); // calculate grad_grid if (within_bounds_2d(iy_nw, ix_nw, inp_H, inp_W)) { scalar_t nw_val = inp_ptr_NC[iy_nw * inp_sH + ix_nw * inp_sW]; gix -= nw_val * (iy_se - iy) * gOut; giy -= nw_val * (ix_se - ix) * gOut; } if (within_bounds_2d(iy_ne, ix_ne, inp_H, inp_W)) { scalar_t ne_val = inp_ptr_NC[iy_ne * inp_sH + ix_ne * inp_sW]; gix += ne_val * (iy_sw - iy) * gOut; giy -= ne_val * (ix - ix_sw) * gOut; } if (within_bounds_2d(iy_sw, ix_sw, inp_H, inp_W)) { scalar_t sw_val = inp_ptr_NC[iy_sw * inp_sH + ix_sw * inp_sW]; gix -= sw_val * (iy - iy_ne) * gOut; giy += sw_val * (ix_ne - ix) * gOut; } if (within_bounds_2d(iy_se, ix_se, inp_H, inp_W)) { scalar_t se_val = inp_ptr_NC[iy_se * inp_sH + ix_se * inp_sW]; gix += se_val * (iy - iy_nw) * gOut; giy += se_val * (ix - ix_nw) * gOut; } } // assuming grad_grid is contiguous // thus we can // 1. use index with gGrid_sW to directly compute gGrid_ptr_NHW // 2. directly assign to gGrid_ptr_NHW[0], gGrid_ptr_NHW[1] scalar_t *gGrid_ptr_NHW = grad_grid.data + index * gGrid_sW; gGrid_ptr_NHW[0] = gix_mult * gix; gGrid_ptr_NHW[1] = giy_mult * giy; } else if (interpolation_mode == GridSamplerInterpolation::Nearest) { int ix_nearest = static_cast<int>(::round(ix)); int iy_nearest = static_cast<int>(::round(iy)); // assign nearest neighor pixel value to output pixel scalar_t *gOut_ptr_NCHW = grad_output.data + n * gOut_sN + h * gOut_sH + w * gOut_sW; scalar_t *gInp_ptr_NC = grad_input.data + n * gInp_sN; for (int c = 0; c < C; ++c, gInp_ptr_NC += gInp_sC, gOut_ptr_NCHW += gOut_sC) { // calculate and set grad_input safe_add_2d(gInp_ptr_NC, iy_nearest, ix_nearest, gInp_sH, gInp_sW, inp_H, inp_W, *gOut_ptr_NCHW); } // assuming grad_grid is contiguous // thus we can // 1. use index with gGrid_sW to directly compute gGrid_ptr_NHW // 2. directly assign to gGrid_ptr_NHW[0], gGrid_ptr_NHW[1] scalar_t *gGrid_ptr_NHW = grad_grid.data + index * gGrid_sW; gGrid_ptr_NHW[0] = static_cast<scalar_t>(0); gGrid_ptr_NHW[1] = static_cast<scalar_t>(0); } } } template <typename scalar_t> C10_LAUNCH_BOUNDS_1(1024) __global__ void grid_sampler_3d_backward_kernel_cuda( const int nthreads, TensorInfo<scalar_t, int> grad_output, TensorInfo<scalar_t, int> input, TensorInfo<scalar_t, int> grid, TensorInfo<scalar_t, int> grad_input, // initialized to zeros TensorInfo<scalar_t, int> grad_grid, // initialized to empty const GridSamplerInterpolation interpolation_mode, const GridSamplerPadding padding_mode, bool align_corners) { int C = input.sizes[1]; int inp_D = input.sizes[2]; int inp_H = input.sizes[3]; int inp_W = input.sizes[4]; int out_D = grid.sizes[1]; int out_H = grid.sizes[2]; int out_W = grid.sizes[3]; int inp_sN = input.strides[0]; int inp_sC = input.strides[1]; int inp_sD = input.strides[2]; int inp_sH = input.strides[3]; int inp_sW = input.strides[4]; int grid_sN = grid.strides[0]; int grid_sD = grid.strides[1]; int grid_sH = grid.strides[2]; int grid_sW = grid.strides[3]; int grid_sCoor = grid.strides[4]; int gOut_sN = grad_output.strides[0]; int gOut_sC = grad_output.strides[1]; int gOut_sD = grad_output.strides[2]; int gOut_sH = grad_output.strides[3]; int gOut_sW = grad_output.strides[4]; int gInp_sN = grad_input.strides[0]; int gInp_sC = grad_input.strides[1]; int gInp_sD = grad_input.strides[2]; int gInp_sH = grad_input.strides[3]; int gInp_sW = grad_input.strides[4]; int gGrid_sW = grad_grid.strides[3]; CUDA_KERNEL_LOOP(index, nthreads) { const int w = index % out_W; const int h = (index / out_W) % out_H; const int d = (index / (out_H * out_W)) % out_D; const int n = index / (out_D * out_H * out_W); const int grid_offset = n * grid_sN + d * grid_sD + h * grid_sH + w * grid_sW; // get the corresponding input x, y, z co-ordinates from grid scalar_t ix = grid.data[grid_offset]; scalar_t iy = grid.data[grid_offset + grid_sCoor]; scalar_t iz = grid.data[grid_offset + 2 * grid_sCoor]; // multipliers for gradients on ix, iy, and iz scalar_t gix_mult, giy_mult, giz_mult; ix = grid_sampler_compute_source_index_set_grad(ix, inp_W, padding_mode, align_corners, &gix_mult); iy = grid_sampler_compute_source_index_set_grad(iy, inp_H, padding_mode, align_corners, &giy_mult); iz = grid_sampler_compute_source_index_set_grad(iz, inp_D, padding_mode, align_corners, &giz_mult); if (interpolation_mode == GridSamplerInterpolation::Bilinear) { // get corner pixel values from (x, y, z) // for 4d, we used north-east-south-west // for 5d, we add top-bottom int ix_tnw = static_cast<int>(::floor(ix)); int iy_tnw = static_cast<int>(::floor(iy)); int iz_tnw = static_cast<int>(::floor(iz)); int ix_tne = ix_tnw + 1; int iy_tne = iy_tnw; int iz_tne = iz_tnw; int ix_tsw = ix_tnw; int iy_tsw = iy_tnw + 1; int iz_tsw = iz_tnw; int ix_tse = ix_tnw + 1; int iy_tse = iy_tnw + 1; int iz_tse = iz_tnw; int ix_bnw = ix_tnw; int iy_bnw = iy_tnw; int iz_bnw = iz_tnw + 1; int ix_bne = ix_tnw + 1; int iy_bne = iy_tnw; int iz_bne = iz_tnw + 1; int ix_bsw = ix_tnw; int iy_bsw = iy_tnw + 1; int iz_bsw = iz_tnw + 1; int ix_bse = ix_tnw + 1; int iy_bse = iy_tnw + 1; int iz_bse = iz_tnw + 1; // get surfaces to each neighbor: scalar_t tnw = (ix_bse - ix) * (iy_bse - iy) * (iz_bse - iz); scalar_t tne = (ix - ix_bsw) * (iy_bsw - iy) * (iz_bsw - iz); scalar_t tsw = (ix_bne - ix) * (iy - iy_bne) * (iz_bne - iz); scalar_t tse = (ix - ix_bnw) * (iy - iy_bnw) * (iz_bnw - iz); scalar_t bnw = (ix_tse - ix) * (iy_tse - iy) * (iz - iz_tse); scalar_t bne = (ix - ix_tsw) * (iy_tsw - iy) * (iz - iz_tsw); scalar_t bsw = (ix_tne - ix) * (iy - iy_tne) * (iz - iz_tne); scalar_t bse = (ix - ix_tnw) * (iy - iy_tnw) * (iz - iz_tnw); scalar_t gix = static_cast<scalar_t>(0), giy = static_cast<scalar_t>(0), giz = static_cast<scalar_t>(0); scalar_t *gOut_ptr_NCDHW = grad_output.data + n * gOut_sN + d * gOut_sD + h * gOut_sH + w * gOut_sW; scalar_t *gInp_ptr_NC = grad_input.data + n * gInp_sN; scalar_t *inp_ptr_NC = input.data + n * inp_sN; // calculate bilinear weighted pixel value and set output pixel for (int c = 0; c < C; ++c, gOut_ptr_NCDHW += gOut_sC, gInp_ptr_NC += gInp_sC, inp_ptr_NC += inp_sC) { scalar_t gOut = *gOut_ptr_NCDHW; // calculate and set grad_input safe_add_3d(gInp_ptr_NC, iz_tnw, iy_tnw, ix_tnw, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, tnw * gOut); safe_add_3d(gInp_ptr_NC, iz_tne, iy_tne, ix_tne, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, tne * gOut); safe_add_3d(gInp_ptr_NC, iz_tsw, iy_tsw, ix_tsw, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, tsw * gOut); safe_add_3d(gInp_ptr_NC, iz_tse, iy_tse, ix_tse, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, tse * gOut); safe_add_3d(gInp_ptr_NC, iz_bnw, iy_bnw, ix_bnw, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, bnw * gOut); safe_add_3d(gInp_ptr_NC, iz_bne, iy_bne, ix_bne, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, bne * gOut); safe_add_3d(gInp_ptr_NC, iz_bsw, iy_bsw, ix_bsw, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, bsw * gOut); safe_add_3d(gInp_ptr_NC, iz_bse, iy_bse, ix_bse, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, bse * gOut); // calculate grad_grid if (within_bounds_3d(iz_tnw, iy_tnw, ix_tnw, inp_D, inp_H, inp_W)) { scalar_t tnw_val = inp_ptr_NC[iz_tnw * inp_sD + iy_tnw * inp_sH + ix_tnw * inp_sW]; gix -= tnw_val * (iy_bse - iy) * (iz_bse - iz) * gOut; giy -= tnw_val * (ix_bse - ix) * (iz_bse - iz) * gOut; giz -= tnw_val * (ix_bse - ix) * (iy_bse - iy) * gOut; } if (within_bounds_3d(iz_tne, iy_tne, ix_tne, inp_D, inp_H, inp_W)) { scalar_t tne_val = inp_ptr_NC[iz_tne * inp_sD + iy_tne * inp_sH + ix_tne * inp_sW]; gix += tne_val * (iy_bsw - iy) * (iz_bsw - iz) * gOut; giy -= tne_val * (ix - ix_bsw) * (iz_bsw - iz) * gOut; giz -= tne_val * (ix - ix_bsw) * (iy_bsw - iy) * gOut; } if (within_bounds_3d(iz_tsw, iy_tsw, ix_tsw, inp_D, inp_H, inp_W)) { scalar_t tsw_val = inp_ptr_NC[iz_tsw * inp_sD + iy_tsw * inp_sH + ix_tsw * inp_sW]; gix -= tsw_val * (iy - iy_bne) * (iz_bne - iz) * gOut; giy += tsw_val * (ix_bne - ix) * (iz_bne - iz) * gOut; giz -= tsw_val * (ix_bne - ix) * (iy - iy_bne) * gOut; } if (within_bounds_3d(iz_tse, iy_tse, ix_tse, inp_D, inp_H, inp_W)) { scalar_t tse_val = inp_ptr_NC[iz_tse * inp_sD + iy_tse * inp_sH + ix_tse * inp_sW]; gix += tse_val * (iy - iy_bnw) * (iz_bnw - iz) * gOut; giy += tse_val * (ix - ix_bnw) * (iz_bnw - iz) * gOut; giz -= tse_val * (ix - ix_bnw) * (iy - iy_bnw) * gOut; } if (within_bounds_3d(iz_bnw, iy_bnw, ix_bnw, inp_D, inp_H, inp_W)) { scalar_t bnw_val = inp_ptr_NC[iz_bnw * inp_sD + iy_bnw * inp_sH + ix_bnw * inp_sW]; gix -= bnw_val * (iy_tse - iy) * (iz - iz_tse) * gOut; giy -= bnw_val * (ix_tse - ix) * (iz - iz_tse) * gOut; giz += bnw_val * (ix_tse - ix) * (iy_tse - iy) * gOut; } if (within_bounds_3d(iz_bne, iy_bne, ix_bne, inp_D, inp_H, inp_W)) { scalar_t bne_val = inp_ptr_NC[iz_bne * inp_sD + iy_bne * inp_sH + ix_bne * inp_sW]; gix += bne_val * (iy_tsw - iy) * (iz - iz_tsw) * gOut; giy -= bne_val * (ix - ix_tsw) * (iz - iz_tsw) * gOut; giz += bne_val * (ix - ix_tsw) * (iy_tsw - iy) * gOut; } if (within_bounds_3d(iz_bsw, iy_bsw, ix_bsw, inp_D, inp_H, inp_W)) { scalar_t bsw_val = inp_ptr_NC[iz_bsw * inp_sD + iy_bsw * inp_sH + ix_bsw * inp_sW]; gix -= bsw_val * (iy - iy_tne) * (iz - iz_tne) * gOut; giy += bsw_val * (ix_tne - ix) * (iz - iz_tne) * gOut; giz += bsw_val * (ix_tne - ix) * (iy - iy_tne) * gOut; } if (within_bounds_3d(iz_bse, iy_bse, ix_bse, inp_D, inp_H, inp_W)) { scalar_t bse_val = inp_ptr_NC[iz_bse * inp_sD + iy_bse * inp_sH + ix_bse * inp_sW]; gix += bse_val * (iy - iy_tnw) * (iz - iz_tnw) * gOut; giy += bse_val * (ix - ix_tnw) * (iz - iz_tnw) * gOut; giz += bse_val * (ix - ix_tnw) * (iy - iy_tnw) * gOut; } } // assuming grad_grid is contiguous // thus we can // 1. use index with gGrid_sW to directly compute gGrid_ptr_NDHW // 2. directly assign to gGrid_ptr_NDHW[0], gGrid_ptr_NDHW[1], gGrid_ptr_NDHW[2] scalar_t *gGrid_ptr_NDHW = grad_grid.data + index * gGrid_sW; gGrid_ptr_NDHW[0] = gix_mult * gix; gGrid_ptr_NDHW[1] = giy_mult * giy; gGrid_ptr_NDHW[2] = giz_mult * giz; } else if (interpolation_mode == GridSamplerInterpolation::Nearest) { int ix_nearest = static_cast<int>(::round(ix)); int iy_nearest = static_cast<int>(::round(iy)); int iz_nearest = static_cast<int>(::round(iz)); // assign nearest neighor pixel value to output pixel scalar_t *gOut_ptr_NCDHW = grad_output.data + n * gOut_sN + d * gOut_sD + h * gOut_sH + w * gOut_sW; scalar_t *gInp_ptr_NC = grad_input.data + n * gInp_sN; for (int c = 0; c < C; ++c, gOut_ptr_NCDHW += gOut_sC, gInp_ptr_NC += gInp_sC) { // calculate and set grad_input safe_add_3d(gInp_ptr_NC, iz_nearest, iy_nearest, ix_nearest, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, *gOut_ptr_NCDHW); } // assuming grad_grid is contiguous // thus we can // 1. use index with gGrid_sW to directly compute gGrid_ptr_NDHW // 2. directly assign to gGrid_ptr_NDHW[0], gGrid_ptr_NDHW[1], gGrid_ptr_NDHW[2] scalar_t *gGrid_ptr_NDHW = grad_grid.data + index * gGrid_sW; gGrid_ptr_NDHW[0] = static_cast<scalar_t>(0); gGrid_ptr_NDHW[1] = static_cast<scalar_t>(0); gGrid_ptr_NDHW[2] = static_cast<scalar_t>(0); } } } } // namespace using namespace at; // No shape checking needed here. See # NOTE [ grid_sampler Native Functions ]. Tensor grid_sampler_2d_forward_cuda(const Tensor& input, const Tensor& grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners) { auto N = input.size(0); auto H = grid.size(1); auto W = grid.size(2); auto output = at::empty({N, input.size(1), H, W}, input.options()); int count = static_cast<int>(N * H * W); if (count > 0) { AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.scalar_type(), "grid_sampler_2d_forward_cuda", [&] { grid_sampler_2d_forward_kernel_cuda<scalar_t> <<<GET_BLOCKS(count), CUDA_NUM_THREADS, 0, at::cuda::getCurrentCUDAStream()>>>( count, getTensorInfo<scalar_t, int>(input), getTensorInfo<scalar_t, int>(grid), getTensorInfo<scalar_t, int>(output), static_cast<GridSamplerInterpolation>(interpolation_mode), static_cast<GridSamplerPadding>(padding_mode), align_corners); }); } return output; } // No shape checking needed here. See # NOTE [ grid_sampler Native Functions ]. Tensor grid_sampler_3d_forward_cuda(const Tensor& input, const Tensor& grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners) { auto N = input.size(0); auto D = grid.size(1); auto H = grid.size(2); auto W = grid.size(3); auto output = at::empty({N, input.size(1), D, H, W}, input.options()); int count = static_cast<int>(N * D * H * W); if (count > 0) { AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.scalar_type(), "grid_sampler_3d_forward_cuda", [&] { grid_sampler_3d_forward_kernel_cuda<scalar_t> <<<GET_BLOCKS(count), CUDA_NUM_THREADS, 0, at::cuda::getCurrentCUDAStream()>>>( count, getTensorInfo<scalar_t, int>(input), getTensorInfo<scalar_t, int>(grid), getTensorInfo<scalar_t, int>(output), static_cast<GridSamplerInterpolation>(interpolation_mode), static_cast<GridSamplerPadding>(padding_mode), align_corners); }); } return output; } // No shape checking needed here. See # NOTE [ grid_sampler Native Functions ]. std::tuple<Tensor, Tensor> grid_sampler_2d_backward_cuda(const Tensor& grad_output, const Tensor& input, const Tensor& grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners) { auto N = input.size(0); auto H = grid.size(1); auto W = grid.size(2); auto grad_input = at::zeros_like(input); auto grad_grid = at::empty_like(grid); int count = static_cast<int>(N * H * W); if (count > 0) { AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.scalar_type(), "grid_sampler_2d_backward_cuda", [&] { grid_sampler_2d_backward_kernel_cuda<scalar_t> <<<GET_BLOCKS(count), CUDA_NUM_THREADS, 0, at::cuda::getCurrentCUDAStream()>>>( count, getTensorInfo<scalar_t, int>(grad_output), getTensorInfo<scalar_t, int>(input), getTensorInfo<scalar_t, int>(grid), getTensorInfo<scalar_t, int>(grad_input), getTensorInfo<scalar_t, int>(grad_grid), static_cast<GridSamplerInterpolation>(interpolation_mode), static_cast<GridSamplerPadding>(padding_mode), align_corners); }); } return std::make_tuple(grad_input, grad_grid); } // No shape checking needed here. See # NOTE [ grid_sampler Native Functions ]. std::tuple<Tensor, Tensor> grid_sampler_3d_backward_cuda(const Tensor& grad_output, const Tensor& input, const Tensor& grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners) { auto N = input.size(0); auto D = grid.size(1); auto H = grid.size(2); auto W = grid.size(3); auto grad_input = at::zeros_like(input); auto grad_grid = at::empty_like(grid); int count = static_cast<int>(N * D * H * W); if (count > 0) { AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.scalar_type(), "grid_sampler_3d_backward_cuda", [&] { grid_sampler_3d_backward_kernel_cuda<scalar_t> <<<GET_BLOCKS(count), CUDA_NUM_THREADS, 0, at::cuda::getCurrentCUDAStream()>>>( count, getTensorInfo<scalar_t, int>(grad_output), getTensorInfo<scalar_t, int>(input), getTensorInfo<scalar_t, int>(grid), getTensorInfo<scalar_t, int>(grad_input), getTensorInfo<scalar_t, int>(grad_grid), static_cast<GridSamplerInterpolation>(interpolation_mode), static_cast<GridSamplerPadding>(padding_mode), align_corners); }); } return std::make_tuple(grad_input, grad_grid); } } // namespace mmdetection
the_stack
#define LO16(x) ((x) & 0x0000FFFF) #define HI16(x) ((x) >> 16) #define getLastCudaError(msg) __getLastCudaError (msg, __FILE__, __LINE__) inline void __getLastCudaError(const char *errorMessage, const char *file, const int line) { cudaError_t err = cudaGetLastError(); if (cudaSuccess != err) { fprintf(stderr, "%s(%i) : getLastCudaError() CUDA error : %s : (%d) %s.\n", file, line, errorMessage, (int)err, cudaGetErrorString(err)); exit(EXIT_FAILURE); } } void convContrastNorm(cudamat* images, cudamat* meanDiffs, cudamat* denoms, cudamat* target, int numFilters, int sizeX, float addScale, float powScale); void convResponseNormUndo(cudamat* outGrads, cudamat* denoms, cudamat* inputs, cudamat* acts, cudamat* target, int numFilters, int sizeX, float addScale, float powScale, float scaleTargets, float scaleOutput); void convContrastNormUndoCu(cudamat* outGrads, cudamat* denoms, cudamat* meanDiffs, cudamat* acts, cudamat* target, int numFilters, int sizeX, float addScale, float powScale, float scaleTargets, float scaleOutput); class MaxPooler { public: __device__ inline float operator()(const float a, const float b) const { return a > b ? a : b; } __device__ inline float getBaseValue() const { return -2e38; } __device__ inline float output(const float a) const { return a; } }; class ProbMaxPooler { public: __device__ inline float operator()(const float a, const float b, const float r1, const float r2) const { return a * r1 > b * r2 ? 0 : 1; } __device__ inline float getBaseValue() const { return -2e38; } __device__ inline float output(const float a) const { return a; } }; /* * Block size B_YxB_X. Each block applies B_Y * filtersPerThread filters to B_X * imgsPerThread images. * threadIdx.x determines image * threadIdx.y determines filter * * blockIdx.x determines image batch of B_X * imgsPerThread * blockIdx.y determines filter batch of module and B_Y * filtersPerThread * * images: (numColors, imgPixels, numImages) with stride given * filters: (numColors, filterPixels, numFilters) if conv * (numModules, numColors, filterPixels, numFilters) otherwise * * targets: (numFilters, numModules, numImages) * * B_Y one of 4, 8, 16 * B_X one of 16, 32 * imgsPerThread one of 1, 2, 4 * filtersPerThread one of 1, 2, 4, 8 * * Number of filters per module should be divisible by B_Y * filtersPerThread * checkImgBounds indicates whether number of images is divisible by B_X * imgsPerThread * * The imgSize here is the size of the actual image without the padding. * */ template <int B_Y, int B_X, int imgsPerThread, int filtersPerThread, int numColors, bool scale, bool checkImgBounds> __global__ void filterActs_YxX_color(float* images, float* filters, float* targets, const int numImages, const int numFilters, const int imgSize, const int filterSize, const int paddingStart, const int moduleStride, const int numModulesX, const int imgStride, const float scaleTargets, const float scaleOutputs, const bool conv) { __shared__ float shFilters[B_Y*numColors][B_Y * filtersPerThread]; // pre-load B_Y pixels from B_Y*filtersPerThread filters __shared__ float shImages[B_Y*numColors][B_X * imgsPerThread]; // pre-load B_Y pixels from B_X*imgsPerThread images const int imgPixels = imgSize * imgSize; const int filterPixels = filterSize * filterSize; const int blocksPerModule = numFilters / (B_Y*filtersPerThread); const int moduleIdx = blockIdx.y / blocksPerModule; const int blockFilterIdx = blockIdx.y % blocksPerModule; const int tidx = threadIdx.y * B_X + threadIdx.x; const int imgLoadModPosY = (moduleIdx / numModulesX) * moduleStride; const int imgLoadModPosX = (moduleIdx % numModulesX) * moduleStride; const int shFilterLoadY = tidx / (B_Y * filtersPerThread); const int shFilterLoadX = tidx % (B_Y * filtersPerThread); const int myImgIdx = blockIdx.x * B_X * imgsPerThread + threadIdx.x; images += myImgIdx; filters += filtersPerThread * B_Y * blockFilterIdx + shFilterLoadY * numFilters + shFilterLoadX; if (!conv) { filters += moduleIdx * numColors * filterPixels * numFilters; } targets += moduleIdx * numImages + (blockFilterIdx * B_Y * filtersPerThread + threadIdx.y) * numImages * numModulesX * numModulesX + myImgIdx; float prod[filtersPerThread][imgsPerThread]; #pragma unroll for(int f = 0; f < filtersPerThread; f++) { #pragma unroll for(int g = 0; g < imgsPerThread; g++) { prod[f][g] = 0; } } for (int p = 0; p < filterPixels; p += B_Y) { /* * Load B_Y pixels from B_Y*filtersPerThread filters */ if (shFilterLoadY < B_Y) { #pragma unroll for (int p2 = 0; p2 < B_Y; p2 += B_X/filtersPerThread) { if (p + p2 + shFilterLoadY < filterPixels) { #pragma unroll for (int c = 0; c < numColors; c++) { shFilters[shFilterLoadY + p2 + c * B_Y][shFilterLoadX] = filters[(c * filterPixels + p + p2) * numFilters]; } } else { #pragma unroll for (int c = 0; c < numColors; c++) { shFilters[shFilterLoadY + p2 + c * B_Y][shFilterLoadX] = 0; } } } } /* * Load B_Y pixels from B_X*imgsPerThread images */ const int pixIdx = p + threadIdx.y; if (pixIdx < filterPixels) { const int x = paddingStart + imgLoadModPosX + pixIdx % filterSize; const int y = paddingStart + imgLoadModPosY + pixIdx / filterSize; if (y >= 0 && y< imgSize && x >= 0 && x < imgSize) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkImgBounds || myImgIdx + i * B_X < numImages) { #pragma unroll for (int c = 0; c < numColors; c++) { shImages[threadIdx.y + c * B_Y][threadIdx.x + i * B_X] = images[imgStride * (c * imgPixels + y * imgSize + x) + i * B_X]; } } else { #pragma unroll for (int c = 0; c < numColors; c++) { shImages[threadIdx.y + c * B_Y][threadIdx.x + i * B_X] = 0; } } } } else { // Padding #pragma unroll for (int i = 0; i < imgsPerThread; i++) { #pragma unroll for (int c = 0; c < numColors; c++) { shImages[threadIdx.y + c * B_Y][threadIdx.x + i * B_X] = 0; } } } } __syncthreads(); #pragma unroll for (int i = 0; i < B_Y*numColors; i++) { #pragma unroll for(int f = 0; f < filtersPerThread; f++) { #pragma unroll for(int g = 0; g < imgsPerThread; g++) { prod[f][g] += shImages[i][g * B_X + threadIdx.x] * shFilters[i][threadIdx.y + f * B_Y]; } } } __syncthreads(); } if (scale) { #pragma unroll for (int g = 0; g < imgsPerThread; g++) { if (!checkImgBounds || myImgIdx + g * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { targets[g * B_X + f * B_Y * numImages * numModulesX * numModulesX] = scaleTargets * targets[g * B_X + f * B_Y * numImages * numModulesX * numModulesX] + scaleOutputs * prod[f][g]; } } } } else { #pragma unroll for (int g = 0; g < imgsPerThread; g++) { if (!checkImgBounds || myImgIdx + g * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { targets[g * B_X + f * B_Y * numImages * numModulesX * numModulesX] = scaleOutputs * prod[f][g]; } } } } } /* * Block size B_YxB_X. Each block applies B_Y * filtersPerThread filters to B_X * imgsPerThread images. * threadIdx.x determines image * threadIdx.y determines filter * * blockIdx.x determines image batch of B_X * imgsPerThread * blockIdx.y determines filter batch of B_Y * filtersPerThread * * images: (numImgColors, imgPixels, numImages) with stride given * filters: (numFilterColors, filterPixels, numFilters) if conv * (numModules, numFilterColors, filterPixels, numFilters) otherwise * * targets: (numFilters, numModules, numImages) * * B_Y one of 4, 8, 16 * B_X one of 16, 32 * imgsPerThread one of 1, 2, 4 * filtersPerThread one of 1, 2, 4, 8 * colorCache: how many colors to put into shmem * * numFilters should be divisible by B_Y * filtersPerThread * numImages be divisible by B_X * imgsPerThread * numFilterColors should be divisible by colorCache. * numImgColors must be even. * numFilters must be divisible by numGroups. * * The imgSize here is the size of the actual image without the padding. * */ template <int B_Y, int B_X, int imgsPerThread, int filtersPerThread, int colorCache, bool scale, bool checkImgBounds> __global__ void filterActs_YxX_sparse(float* images, float* filters, float* targets, const int numImages, const int numFilters, const int imgSize, const int filterSize, const int paddingStart, const int moduleStride, const int numModulesX, const int imgStride, const int numImgColors, const int numGroups, const float scaleTargets, const float scaleOutputs, const bool conv) { __shared__ float shFilters[B_Y*colorCache][B_Y * filtersPerThread]; // pre-load B_Y pixels from B_Y*filtersPerThread filters __shared__ float shImages[B_Y*colorCache][B_X * imgsPerThread]; // pre-load B_Y pixels from B_X*imgsPerThread images const int imgPixels = imgSize * imgSize; const int filterPixels = filterSize * filterSize; const int numFilterColors = numImgColors / numGroups; const int blocksPerModule = numFilters / (B_Y*filtersPerThread); const int moduleIdx = blockIdx.y / blocksPerModule; const int blockFilterIdx = filtersPerThread * B_Y * (blockIdx.y % blocksPerModule); const int numFiltersPerGroup = numFilters / numGroups; const int blockGroupIdx = blockFilterIdx / numFiltersPerGroup; const int numModules = numModulesX * numModulesX; const int blockColorIdx = numFilterColors * blockGroupIdx; const int tidx = threadIdx.y * B_X + threadIdx.x; const int imgLoadModPosY = paddingStart + (moduleIdx / numModulesX) * moduleStride; const int imgLoadModPosX = paddingStart + (moduleIdx % numModulesX) * moduleStride; const int shFilterLoadY = tidx / (B_Y * filtersPerThread); const int shFilterLoadX = tidx % (B_Y * filtersPerThread); const int myImgIdx = blockIdx.x * B_X * imgsPerThread + threadIdx.x; images += blockColorIdx * imgPixels * imgStride + myImgIdx; filters +=blockFilterIdx + shFilterLoadY * numFilters + shFilterLoadX; if (!conv) { filters += moduleIdx * numFilterColors * filterPixels * numFilters; } targets += moduleIdx * numImages + (blockFilterIdx + threadIdx.y) * numImages * numModules + myImgIdx; float prod[filtersPerThread][imgsPerThread]; #pragma unroll for(int f = 0; f < filtersPerThread; f++) { #pragma unroll for(int g = 0; g < imgsPerThread; g++) { prod[f][g] = 0; } } // __shared__ int imgPos[] for (int oc = 0; oc < numFilterColors; oc += colorCache) { // oc stands for outer color (loop) for (int p = 0; p < filterPixels; p += B_Y) { /* * Load B_Y pixels from B_Y*filtersPerThread filters */ if (shFilterLoadY < B_Y) { #pragma unroll for (int p2 = 0; p2 < B_Y; p2 += B_X/filtersPerThread) { if (p + p2 + shFilterLoadY < filterPixels) { #pragma unroll for (int c = 0; c < colorCache; c++) { shFilters[shFilterLoadY + p2 + c * B_Y][shFilterLoadX] = filters[((oc+c) * filterPixels + p + p2) * numFilters]; } } else { #pragma unroll for (int c = 0; c < colorCache; c++) { shFilters[shFilterLoadY + p2 + c * B_Y][shFilterLoadX] = 0; } } } } /* * Load B_Y pixels from B_X*imgsPerThread images */ const int pixIdx = p + threadIdx.y; if (pixIdx < filterPixels) { const int x = imgLoadModPosX + pixIdx % filterSize; const int y = imgLoadModPosY + pixIdx / filterSize; if (y >= 0 && y < imgSize && x >= 0 && x < imgSize) { float* m = &images[imgStride * (oc * imgPixels + y * imgSize + x)]; #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkImgBounds || myImgIdx + i * B_X < numImages) { #pragma unroll for (int c = 0; c < colorCache; c++) { shImages[threadIdx.y + c * B_Y][threadIdx.x + i * B_X] = m[c * imgStride * imgPixels + i * B_X]; } } else { #pragma unroll for (int c = 0; c < colorCache; c++) { shImages[threadIdx.y + c * B_Y][threadIdx.x + i * B_X] = 0; } } } } else { // Padding #pragma unroll for (int i = 0; i < imgsPerThread; i++) { #pragma unroll for (int c = 0; c < colorCache; c++) { shImages[threadIdx.y + c * B_Y][threadIdx.x + i * B_X] = 0; } } } } __syncthreads(); #pragma unroll for (int i = 0; i < B_Y*colorCache; i++) { #pragma unroll for(int f = 0; f < filtersPerThread; f++) { #pragma unroll for(int g = 0; g < imgsPerThread; g++) { prod[f][g] += shImages[i][g * B_X + threadIdx.x] * shFilters[i][threadIdx.y + f * B_Y]; } } } __syncthreads(); } } if (scale) { #pragma unroll for (int g = 0; g < imgsPerThread; g++) { if (!checkImgBounds || myImgIdx + g * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { targets[g * B_X + f * B_Y * numImages * numModules] = scaleTargets * targets[g * B_X + f * B_Y * numImages * numModules] + scaleOutputs * prod[f][g]; } } } } else { #pragma unroll for (int g = 0; g < imgsPerThread; g++) { if (!checkImgBounds || myImgIdx + g * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { targets[g * B_X + f * B_Y * numImages * numModules] = scaleOutputs * prod[f][g]; } } } } } /* * Block size: 16x16. * blockIdx.x determines case in batches of 16*imgsPerThread. * blockIdx.y determines 4x4 image region in target image. * * threadIdx.x determines case. * threadIdx.y determines pixel. * * hidActs: (numFilters, numModules, numImages) * filters: (numColors, filterPixels, numFilters) if conv * (numModules, numColors, filterPixels, numFilters) otherwise * targets: (numColors, imgPixels, numImages) * * Each block reconstructs one 4x4 pixels from 16*imgsPerThread cases. * * Number of filters must be divisible by 16. * Number of images must be divisible by 16*imgsPerThread if checkCaseBounds is false. * 16 * imgsPerThread must be divisible by 32. * * This version loads 32 cases at a time, so it gets full coalescing on that load. * It only loads 16 weights at a time, so those aren't fully coalesced. * This version conserves shared memory by loading 16 filters at a time rather than 32. */ template <int imgsPerThread, int numColors, bool scale, bool checkCaseBounds, bool conv> __global__ void img_acts_color(const float* hidActs, const float* filters, float* targets, const int numModulesX, const int numImages, const int numFilters, const int filterSize, const int imgSize, const int paddingStart, const int moduleStride, const float scaleTargets, const float scaleOutputs) { __shared__ float shFilters[numColors*16][16 + 1]; __shared__ float shHidActs[16][16*imgsPerThread]; const int blockCaseIdx = blockIdx.x * 16*imgsPerThread; const int numRegionsX = DIVUP(imgSize, 4); const int blockRegionIdx = blockIdx.y; const int blockRegionIdxX = blockRegionIdx % numRegionsX; const int blockRegionIdxY = blockRegionIdx / numRegionsX; const int blockRegionLeft = blockRegionIdxX * 4; const int blockRegionTop = blockRegionIdxY * 4; const int pxYInRegion = threadIdx.y / 4, pxXInRegion = threadIdx.y % 4; const int pxY = blockRegionTop + pxYInRegion; const int pxX = blockRegionLeft + pxXInRegion; const int pxIdx = pxY * imgSize + pxX; const bool isPxInImg = pxY < imgSize && pxX < imgSize; const uint numModules = numModulesX * numModulesX; const int filterPixels = filterSize * filterSize; const int imgPixels = imgSize * imgSize; const int tidx = threadIdx.y * 16 + threadIdx.x; const int loadY = tidx / 32, loadX = tidx % 32; hidActs += blockCaseIdx + loadY * numImages * numModulesX * numModulesX + loadX; filters += threadIdx.x; targets += pxIdx * numImages + blockCaseIdx + threadIdx.x; float prod[numColors][imgsPerThread]; #pragma unroll for (int c = 0; c < numColors; c++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[c][i] = 0; } } const int startY = blockRegionTop - paddingStart < filterSize ? 0 : 1 + (blockRegionTop - paddingStart - filterSize) / moduleStride; const int endY = MIN(numModulesX, 1 + (blockRegionTop + 3 - paddingStart) / moduleStride); const int startX = blockRegionLeft - paddingStart < filterSize ? 0 : 1 + (blockRegionLeft - paddingStart - filterSize) / moduleStride; const int endX = MIN(numModulesX, 1 + (blockRegionLeft + 3 - paddingStart) / moduleStride); float* shilterLoad = &shFilters[threadIdx.y][threadIdx.x]; float* shHidActLoad = &shHidActs[loadY][loadX]; for (int my = startY; my < endY; my++) { const int moduleTop = paddingStart + my * moduleStride; const int pxInModuleY = pxY - moduleTop; for (int mx = startX; mx < endX; mx++) { const int moduleIdx = my * numModulesX + mx; const int moduleLeft = paddingStart + mx * moduleStride; const int pxInModuleX = pxX - moduleLeft; const bool isPxInModule = pxInModuleY >= 0 && pxInModuleY < filterSize && pxInModuleX >= 0 && pxInModuleX < filterSize; const int pxIdxInModule = pxInModuleY * filterSize + pxInModuleX; for (int f = 0; f < numFilters; f += 16) { // multiply with 16 filters at a time // Now the threads split up into half-warps, and each half-warp decides if it's interested. const float* hLoad = &hidActs[(moduleIdx + f * numModules) * numImages]; #pragma unroll for (int i = 0; i < imgsPerThread * 16; i += 32) { if (!checkCaseBounds || blockCaseIdx + i + loadX < numImages) { #pragma unroll for (int j = 0; j < 16; j += 8) { // load 16 rows of imgsPerThread*16 cols, 8 * 32 elements at a time. shHidActLoad[j * 16 * imgsPerThread + i] = hLoad[j * numModules * numImages + i]; } } else { #pragma unroll for (int j = 0; j < 16; j += 8) { // load 16 rows of imgsPerThread*16 cols, 8 * 32 elements at a time. shHidActLoad[j * 16 * imgsPerThread + i] = 0; } } } if (isPxInImg && isPxInModule) { // This half-warp is interested, so it's going to load the weights from this module to its pixel. // Not fully coalesced read :( // But taking out this read entirely only reduces the runtime by ~2.8%, so it isn't costing me much. const float* fLoad = conv ? &filters[pxIdxInModule * numFilters + f] : &filters[(moduleIdx * numColors * filterPixels + pxIdxInModule) * numFilters + f]; #pragma unroll for (int c = 0; c < numColors; c++) { shilterLoad[c * 16 * (16 + 1)] = fLoad[c * filterPixels * numFilters]; } } __syncthreads(); // Do some actual computation if (isPxInImg && isPxInModule) { #pragma unroll for (int c = 0; c < numColors; c++) { #pragma unroll for (int w = 0; w < 16; w++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[c][i] += shFilters[threadIdx.y + c * 16][w] * shHidActs[w][threadIdx.x + i * 16]; } } } } __syncthreads(); } } } // Not fully coalesced write :(... shmem (and fully coalesced) version is actually slightly slower, though if (isPxInImg) { if (scale) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || blockCaseIdx + threadIdx.x + i * 16 < numImages) { #pragma unroll for (int c = 0; c < numColors; c++) { targets[c * imgPixels * numImages + i * 16] = scaleTargets * targets[c * imgPixels * numImages + i * 16] + scaleOutputs * prod[c][i]; } } } } else { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || blockCaseIdx + threadIdx.x + i * 16 < numImages) { #pragma unroll for (int c = 0; c < numColors; c++) { targets[c * imgPixels * numImages + i * 16] = scaleOutputs * prod[c][i]; } } } } } } /* * Block size: 16x16. * blockIdx.x determines case in batches of 16*imgsPerThread, also color in batches of colorsPerThread. * In essence, blockIdx.x.x = 1..numImages/(16*imgsPerThread) * blockIdx.x.y = 1..numImgColors/colorsPerThread * blockIdx.y determines 4x4 image region in target image. * * threadIdx.x determines case. * threadIdx.y determines pixel. * * hidActs: (numFilters, numModules, numImages) * filters: (numFilterColors, filterPixels, numFilters) if conv * (numModules, numFilterColors, filterPixels, numFilters) otherwise * targets: (numImageColors, imgPixels, numImages) * * Each block reconstructs one 4x4 pixels from 16*imgsPerThread cases. * * numImages must be divisible by 16*imgsPerThread if checkCaseBounds is false. * 16 * imgsPerThread must be divisible by 32. * numImageColors/numGroups must be divisible by colorsPerThread. * * This version loads 32 cases at a time, so it gets full coalescing on that load. * It only loads 16 weights at a time, so those aren't fully coalesced. * This version conserves shared memory by loading 16 filters at a time rather than 32. * * To be used when there are 4-16 color channels. */ template <int imgsPerThread, int colorsPerThread, bool scale, bool checkCaseBounds, bool conv> __global__ void img_acts_mediumcolor(const float* hidActs, const float* filters, float* targets, const int numModulesX, const int numImages, const int numFilters, const int filterSize, const int imgSize, const int paddingStart, const int moduleStride, const int numImgColors, const int numGroups, const float scaleTargets, const float scaleOutputs) { __shared__ float shFilters[colorsPerThread*16][16 + 1]; __shared__ float shHidActs[16][16*imgsPerThread]; const int numImgBlocks = DIVUP(numImages,16*imgsPerThread); const int blockCaseIdx = (blockIdx.x % numImgBlocks) * 16*imgsPerThread; const int imgColorIdx = (blockIdx.x / numImgBlocks) * colorsPerThread; // color idx globally const int numFilterColors = numImgColors / numGroups; const int blockGroupIdx = imgColorIdx / numFilterColors; const int filterColorIdx = imgColorIdx % numFilterColors; // color idx within group const int numFiltersPerGroup = numFilters / numGroups; const int blockFilterIdx = blockGroupIdx * numFiltersPerGroup; const int numRegionsX = DIVUP(imgSize, 4); const int blockRegionIdx = blockIdx.y; const int blockRegionIdxX = blockRegionIdx % numRegionsX; const int blockRegionIdxY = blockRegionIdx / numRegionsX; const int blockRegionLeft = blockRegionIdxX * 4; const int blockRegionTop = blockRegionIdxY * 4; const int pxYInRegion = threadIdx.y / 4, pxXInRegion = threadIdx.y % 4; const int pxY = blockRegionTop + pxYInRegion; const int pxX = blockRegionLeft + pxXInRegion; const int pxIdx = pxY * imgSize + pxX; const bool isPxInImg = pxY < imgSize && pxX < imgSize; // const uint numModules = numModulesX * numModulesX; const int filterPixels = filterSize * filterSize; const int imgPixels = imgSize * imgSize; const int tidx = threadIdx.y * 16 + threadIdx.x; const int loadY = tidx / 32, loadX = tidx % 32; hidActs += blockCaseIdx + (blockFilterIdx + loadY) * numImages * numModulesX * numModulesX + loadX; filters += blockFilterIdx + filterColorIdx * filterPixels * numFilters + threadIdx.x; targets += imgColorIdx * imgPixels * numImages + pxIdx * numImages + blockCaseIdx + threadIdx.x; float prod[colorsPerThread][imgsPerThread]; #pragma unroll for (int c = 0; c < colorsPerThread; c++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[c][i] = 0; } } const int startY = blockRegionTop - paddingStart < filterSize ? 0 : 1 + (blockRegionTop - paddingStart - filterSize) / moduleStride; const int endY = MIN(numModulesX, 1 + (blockRegionTop + 3 - paddingStart) / moduleStride); const int startX = blockRegionLeft - paddingStart < filterSize ? 0 : 1 + (blockRegionLeft - paddingStart - filterSize) / moduleStride; const int endX = MIN(numModulesX, 1 + (blockRegionLeft + 3 - paddingStart) / moduleStride); float* shFilterLoad = &shFilters[threadIdx.y][threadIdx.x]; float* shHidActLoad = &shHidActs[loadY][loadX]; for (int my = startY; my < endY; my++) { const int moduleTop = paddingStart + my * moduleStride; const int pxInModuleY = pxY - moduleTop; for (int mx = startX; mx < endX; mx++) { const int moduleIdx = my * numModulesX + mx; const int moduleLeft = paddingStart + mx * moduleStride; const int pxInModuleX = pxX - moduleLeft; const bool isPxInModule = pxInModuleY >= 0 && pxInModuleY < filterSize && pxInModuleX >= 0 && pxInModuleX < filterSize; const int pxIdxInModule = pxInModuleY * filterSize + pxInModuleX; for (int f = 0; f < numFiltersPerGroup; f += 16) { // multipply with 16 filters at a time // Now the threads split up into half-warps, and each half-warp decides if it's interested. const float* hLoad = &hidActs[(moduleIdx + f * numModulesX * numModulesX) * numImages]; #pragma unroll for (int i = 0; i < imgsPerThread * 16; i += 32) { if (!checkCaseBounds || blockCaseIdx + loadX + i < numImages) { #pragma unroll for (int j = 0; j < 16; j += 8) { // load 16 rows of imgsPerThread*16 cols, 8 * 32 elements at a time. shHidActLoad[j * 16 * imgsPerThread + i] = hLoad[j * numModulesX * numModulesX * numImages + i]; } } else { #pragma unroll for (int j = 0; j < 16; j += 8) { // load 16 rows of imgsPerThread*16 cols, 8 * 32 elements at a time. shHidActLoad[j * 16 * imgsPerThread + i] = 0; } } } if (isPxInImg && isPxInModule) { // This half-warp is interested, so it's going to load the weights from this module to its pixel. // Not fully coalesced read :( // But taking out this read entirely only reduces the runtime by ~2.8%, so it isn't costing me much. const float* fLoad = conv ? &filters[pxIdxInModule * numFilters + f] : &filters[moduleIdx * numFilterColors * filterPixels * numFilters + pxIdxInModule * numFilters + f]; #pragma unroll for (int c = 0; c < colorsPerThread; c++) { shFilterLoad[c * 16 * (16 + 1)] = fLoad[c * filterPixels * numFilters]; } } __syncthreads(); // Do some actual computation if (isPxInImg && isPxInModule) { #pragma unroll for (int c = 0; c < colorsPerThread; c++) { #pragma unroll for (int w = 0; w < 16; w++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[c][i] += shFilters[threadIdx.y + c * 16][w] * shHidActs[w][threadIdx.x + i * 16]; } } } } __syncthreads(); } } } // Not fully coalesced write :(... shmem (and fully coalesced) version is actually slightly slower, though if (isPxInImg) { if (scale) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || blockCaseIdx + threadIdx.x + i * 16 < numImages) { #pragma unroll for (int c = 0; c < colorsPerThread; c++) { targets[c * imgPixels * numImages + i * 16] = scaleTargets * targets[c * imgPixels * numImages + i * 16] + scaleOutputs * prod[c][i]; } } } } else { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || blockCaseIdx + threadIdx.x + i * 16 < numImages) { #pragma unroll for (int c = 0; c < colorsPerThread; c++) { targets[c * imgPixels * numImages + i * 16] = scaleOutputs * prod[c][i]; } } } } } } /* * Block size: B_YxB_X. * blockIdx.x determines case in batches of B_X*imgsPerThread, also color in batches of B_Y*colorsPerThread. * In essence, blockIdx.x.x = 1..numImages/(B_X*imgsPerThread) * blockIdx.x.y = 1..numImgColors/(B_Y*colorsPerThread) * blockIdx.y determines image pixel in target image. * * threadIdx.x determines case. * threadIdx.y determines color. * * hidActs: (numFilters, numModules, numImages) * filters: (numFilterColors, filterPixels, numFilters) if conv * (numModules, numFilterColors, filterPixels, numFilters) otherwise * targets: (numImageColors, imgPixels, numImages) * * Each block reconstructs one B_Y*colorsPerThread colors from 1 pixel from B_X*imgsPerThread cases. * * numImages must be divisible by B_X*imgsPerThread if checkCaseBounds is false. * numFiltersPerGroup must be divisible by 16. * * B_X * imgsPerThread must be divisible by 32. * numFilterColors must be divisible by B_Y*colorsPerThread. * B_X*B_Y must be divisible by 32. * * This version loads 32 cases at a time, so it gets full coalescing on that load. * It only loads 16 weights at a time, so those aren't fully coalesced. * This version conserves shared memory by loading 16 filters at a time rather than 32. * * To be used when there are >= 16 color channels. */ template <int B_Y, int B_X, int imgsPerThread, int colorsPerThread, bool scale, bool checkCaseBounds, bool conv> __global__ void conv_img_acts_manycolor(const float* hidActs, const float* filters, float* targets, const int numModulesX, const int numImages, const int numFilters, const int filterSize, const int imgSize, const int paddingStart, const int moduleStride, const int numImgColors, const int numGroups, const float scaleTargets, const float scaleOutputs) { __shared__ float shFilters[colorsPerThread*B_Y][16 + 1]; // TODO: perhaps reconsider this 16 __shared__ float shHidActs[16][B_X*imgsPerThread]; const int numImgBlocks = DIVUP(numImages,B_X*imgsPerThread); const int blockCaseIdx = (blockIdx.x % numImgBlocks) * B_X*imgsPerThread; const int imgColorIdx = (blockIdx.x / numImgBlocks) * B_Y*colorsPerThread; // color idx globally const int numFilterColors = numImgColors / numGroups; const int blockGroupIdx = imgColorIdx / numFilterColors; const int filterColorIdx = imgColorIdx % numFilterColors; // color idx within group const int numFiltersPerGroup = numFilters / numGroups; const int blockFilterIdx = blockGroupIdx * numFiltersPerGroup; const int blockPixelIdx = blockIdx.y; const int blockPixelIdxX = blockPixelIdx % imgSize; const int blockPixelIdxY = blockPixelIdx / imgSize; const int filterPixels = filterSize * filterSize; const int imgPixels = imgSize * imgSize; const int tidx = threadIdx.y * B_X + threadIdx.x; const int hidActLoadY = tidx / 32, hidActLoadX = tidx % 32; const int filtersLoadY = tidx / 16, filtersLoadX = tidx % 16; const int numModules = numModulesX * numModulesX; hidActs += blockCaseIdx + (blockFilterIdx + hidActLoadY) * numImages * numModules + hidActLoadX; filters += blockFilterIdx + (filterColorIdx + filtersLoadY) * filterPixels * numFilters + filtersLoadX; targets += (imgColorIdx + threadIdx.y) * imgPixels * numImages + blockPixelIdx * numImages + blockCaseIdx + threadIdx.x; float prod[colorsPerThread][imgsPerThread]; #pragma unroll for (int c = 0; c < colorsPerThread; c++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[c][i] = 0; } } const int startY = blockPixelIdxY - paddingStart < filterSize ? 0 : 1 + (blockPixelIdxY - paddingStart - filterSize) / moduleStride; const int endY = MIN(numModulesX, 1 + (blockPixelIdxY - paddingStart) / moduleStride); const int startX = blockPixelIdxX - paddingStart < filterSize ? 0 : 1 + (blockPixelIdxX - paddingStart - filterSize) / moduleStride; const int endX = MIN(numModulesX, 1 + (blockPixelIdxX - paddingStart) / moduleStride); float* shFilterLoad = &shFilters[filtersLoadY][filtersLoadX]; float* shHidActLoad = &shHidActs[hidActLoadY][hidActLoadX]; for (int my = startY; my < endY; my++) { const int moduleTop = paddingStart + my * moduleStride; const int pxInFilterY = blockPixelIdxY - moduleTop; for (int mx = startX; mx < endX; mx++) { const int moduleIdx = my * numModulesX + mx; const int moduleLeft = paddingStart + mx * moduleStride; const int pxInFilterX = blockPixelIdxX - moduleLeft; const int pxIdxInFilter = pxInFilterY * filterSize + pxInFilterX; for (int f = 0; f < numFiltersPerGroup; f += 16) { // multiply with 16 filters at a time const float* hLoad = &hidActs[(moduleIdx + f * numModules) * numImages]; #pragma unroll for (int i = 0; i < imgsPerThread * B_X; i += 32) { if (!checkCaseBounds || blockCaseIdx + hidActLoadX + i < numImages) { #pragma unroll for (int j = 0; j < 16; j += B_X*B_Y/32) { // load 16 rows of imgsPerThread*16 cols, 8 * 32 elements at a time. shHidActLoad[j * B_X * imgsPerThread + i] = hLoad[j * numModules * numImages + i]; } } else { #pragma unroll for (int j = 0; j < 16; j += B_X*B_Y/32) { // load 16 rows of imgsPerThread*16 cols, 8 * 32 elements at a time. shHidActLoad[j * B_X * imgsPerThread + i] = 0; } } } const float* fLoad = conv ? &filters[pxIdxInFilter * numFilters + f] : &filters[moduleIdx * numFilterColors * filterPixels * numFilters + pxIdxInFilter * numFilters + f]; #pragma unroll for (int i = 0; i < colorsPerThread*B_Y; i+= B_X*B_Y/16) { if ((colorsPerThread*B_Y) % (B_X*B_Y/16) == 0 || i + filtersLoadY < colorsPerThread*B_Y) { shFilterLoad[i * (16 + 1)] = fLoad[i * filterPixels * numFilters]; } } __syncthreads(); // Do some actual computation #pragma unroll for (int c = 0; c < colorsPerThread; c++) { #pragma unroll for (int w = 0; w < 16; w++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[c][i] += shFilters[c * B_Y + threadIdx.y][w] * shHidActs[w][threadIdx.x + i * B_X]; } } } __syncthreads(); } } } if (scale) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || blockCaseIdx + threadIdx.x + i * B_X < numImages) { #pragma unroll for (int c = 0; c < colorsPerThread; c++) { targets[c * B_Y * imgPixels * numImages + i * B_X] = scaleTargets * targets[c * B_Y * imgPixels * numImages + i * B_X] + scaleOutputs * prod[c][i]; } } } } else { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || blockCaseIdx + threadIdx.x + i * B_X < numImages) { #pragma unroll for (int c = 0; c < colorsPerThread; c++) { targets[c * B_Y * imgPixels * numImages + i * B_X] = scaleOutputs * prod[c][i]; } } } } } /* * Each block computes weight gradients for B_Y * pixelsPerThread pixels and B_X filters * threadIdx.x determines filter * threadIdx.y determines pixel in filter * * blockIdx.x determines filter batch of B_X, module batch of partialSum * blockIdx.y determines pixel batch of B_Y * pixelsPerThread * * Number of filters must be divisible by B_X * Number of images (cases) should be divisible by preloadCases if checkCaseBounds is false. * * images: (numColors, imgPixels, numImages), with stride given * hidActs: (numFilters, numModules, numImages) * * targets: (numModules/partialSum, numColors, filterPixels, numFilters) * * B_Y * B_X should be divisible by preloadCases. * preloadCases one of 16, 32. * B_X one of 4, 8, 16, 32 * B_Y arbitrary (satisfying divisibility constraints) * numModules must be divisible by partialSum * * After adding pixelsPerThread, register usage went from 20 to 23 (when pixelsPerThread = 1)... * so the compiler is messing up here somehow. It's unable to optimize that case away. */ template <int B_Y, int B_X, int pixelsPerThread, int preloadCases, int numColors, bool scale, bool checkCaseBounds> __global__ void conv_weight_acts_c(float* images, float* hidActs, float* targets, const int numImages, const int numFilters, const int numModulesX, const int imgSize, const int filterSize, const int paddingStart, const int moduleStride, const int imgStride, const int partialSum, const float scaleTargets, const float scaleOutputs) { __shared__ float shImages[pixelsPerThread * B_Y * numColors][preloadCases]; // preload preloadCases cases of B_Y * pixelsPerThread pixels __shared__ float shHidActs[B_X][preloadCases + 1]; // preload preloadCases cases of B_X hidActs const int tidx = B_X * threadIdx.y + threadIdx.x; const int loadY = tidx / preloadCases, loadX = tidx % preloadCases; const int filterPixels = filterSize * filterSize; const int imgPixels = imgSize * imgSize; const int filterBlocksPerModule = numFilters / B_X; const int outputModuleIdx = blockIdx.x / filterBlocksPerModule; const int moduleIdx = partialSum * outputModuleIdx; const int blockFilterIdx = B_X * (blockIdx.x % filterBlocksPerModule); // const int moduleStride = (imgSize - filterSize + 1) / numModulesX; const int numModules = numModulesX * numModulesX; const int blockPixelOffset = blockIdx.y * B_Y * pixelsPerThread; images += loadX; hidActs += moduleIdx * numImages + blockFilterIdx * numImages * numModules + loadY * numImages * numModules + loadX; targets += (outputModuleIdx * numFilters) * filterPixels * numColors + blockPixelOffset * numFilters + blockFilterIdx + threadIdx.y * numFilters + threadIdx.x; float* shImgLoad = &shImages[loadY][loadX]; float* shHidActLoad = &shHidActs[loadY][loadX]; float prod[numColors][pixelsPerThread]; #pragma unroll for (int c = 0; c < numColors; c++) { #pragma unroll for (int p = 0; p < pixelsPerThread; p++) { prod[c][p] = 0; } } __shared__ int pxDivs[B_Y*pixelsPerThread]; if (tidx < B_Y * pixelsPerThread) { pxDivs[tidx] = (((blockPixelOffset + tidx) / filterSize) << 16) + ((blockPixelOffset + tidx) % filterSize); } __syncthreads(); for (int m = moduleIdx; m < moduleIdx + partialSum; m++) { const int imgLoadModPosY = paddingStart + (m / numModulesX) * moduleStride; const int imgLoadModPosX = paddingStart + (m % numModulesX) * moduleStride; for (int caseIdx = 0; caseIdx < numImages; caseIdx += preloadCases) { if (loadY < B_Y * pixelsPerThread) { /* * As long as B_Y * B_X is divisible by preloadCases this will loop the right * number of times. * * This will load some imgGrads from filter pixels that don't exit (it'll set those to 0), * but the code does not produce any output for those pixels (see last lines). */ // #pragma unroll for (int y = 0; y < B_Y * pixelsPerThread; y += (B_X * B_Y) / preloadCases) { // Make sure number of rows in the array is divisible by number of rows filled per iteration if ((B_Y * pixelsPerThread) % (B_X * B_Y / preloadCases) == 0 || y + loadY < B_Y * pixelsPerThread) { const int pxIdx = loadY + y; // pixel idx in filter if (pxIdx + blockPixelOffset < filterPixels && (!checkCaseBounds || caseIdx + loadX < numImages)) { const int pxY = imgLoadModPosY + HI16(pxDivs[pxIdx]); // pixel x,y coords in image const int pxX = imgLoadModPosX + LO16(pxDivs[pxIdx]); if (pxY >= 0 && pxY < imgSize && pxX >= 0 && pxX < imgSize) { const int pixIdx = (pxY * imgSize + pxX) * imgStride; #pragma unroll for (int c = 0; c < numColors; c++) { shImgLoad[(y + c * pixelsPerThread * B_Y) * preloadCases] = images[caseIdx + c * imgPixels * imgStride + pixIdx]; } } else { #pragma unroll for (int c = 0; c < numColors; c++) { shImgLoad[(y + c * pixelsPerThread * B_Y) * preloadCases] = 0; } } } else { #pragma unroll for (int c = 0; c < numColors; c++) { shImgLoad[(y + c * pixelsPerThread * B_Y) * preloadCases] = 0; } } } } } if (loadY < B_X && (!checkCaseBounds || caseIdx + loadX < numImages)) { #pragma unroll for (int y = 0; y < B_X; y += (B_X * B_Y) / preloadCases) { // Make sure number of rows in the array is divisible by number of rows filled per iteration if (B_X % (B_X * B_Y / preloadCases) == 0 || y + loadY < B_X) { shHidActLoad[y * (preloadCases + 1)] = hidActs[caseIdx + y * numImages * numModules]; } } } __syncthreads(); #pragma unroll for (int p = 0; p < pixelsPerThread; p++) { #pragma unroll for (int i = 0; i < preloadCases; i++) { #pragma unroll for (int c = 0; c < numColors; c++) { prod[c][p] += shImages[threadIdx.y + p * B_Y + c * pixelsPerThread * B_Y][i] * shHidActs[threadIdx.x][i]; } } } __syncthreads(); } hidActs += numImages; } if (scale) { #pragma unroll for (int p = 0; p < pixelsPerThread; p++) { if (blockPixelOffset + p * B_Y + threadIdx.y < filterPixels) { #pragma unroll for (int c = 0; c < numColors; c++) { targets[p * B_Y * numFilters + c * filterPixels * numFilters] = scaleTargets * targets[p * B_Y * numFilters + c * filterPixels * numFilters] + scaleOutputs * prod[c][p]; } } } } else { #pragma unroll for (int p = 0; p < pixelsPerThread; p++) { if (blockPixelOffset + p * B_Y + threadIdx.y < filterPixels) { #pragma unroll for (int c = 0; c < numColors; c++) { targets[p * B_Y * numFilters + c * filterPixels * numFilters] = scaleOutputs * prod[c][p]; } } } } } /* * Each block computes weight gradients for B_Y pixels and B_X * filtersPerThread filters * threadIdx.x determines filter * threadIdx.y determines pixel in filter * * blockIdx.x determines filter batch of B_X * filtersPerThread, module batch of partialSum * blockIdx.y determines pixel, color batch of B_Y * colorsPerThread * In essence, blockIdx.y.x = 0...numFilterColors / colorsPerThread * blockIdx.y.y = 0...DIVUP(numPixels, B_Y) * ============ * CONSTRAINTS: * ============ * numFilters/numGroups must be divisible by B_X * filtersPerThread * numImgColors/numGroups must be divisible by colorsPerThread * numFilters must be divisible by numGroups * numImgColors must be divisible by numGroups * Number of images (cases) should be divisible by preloadCases if checkCaseBounds is false. * * images: (numImgColors, imgPixels, numImages), with stride given * hidActs: (numFilters, numModules, numImages) * * targets: (numModules/partialSum, numFilterColors, filterPixels, numFilters) * * B_Y * B_X should be divisible by preloadCases. * preloadCases one of 16, 32. * B_X one of 4, 8, 16, 32 * B_Y arbitrary (satisfying divisibility constraints) * * This routine is especially fast when numFilters >= 32. That's when it should be used. */ template <int B_Y, int B_X, int filtersPerThread, int colorsPerThread, int preloadCases, bool scale, bool checkCaseBounds> __global__ void conv_weight_acts_mc_mf(float* images, float* hidActs, float* targets, const int numImages, const int numFilters, const int numModulesX, const int imgSize, const int filterSize, const int paddingStart, const int moduleStride, const int imgStride, const int numImgColors, const int numGroups, const int partialSum, const float scaleTargets, const float scaleOutputs) { __shared__ float shImages[colorsPerThread * B_Y][preloadCases]; // preload preloadCases cases of B_Y * pixelsPerThread pixels __shared__ float shHidActs[filtersPerThread * B_X][preloadCases + 1]; // preload preloadCases cases of B_X hidacts const int tidx = B_X * threadIdx.y + threadIdx.x; const int loadY = tidx / preloadCases, loadX = tidx % preloadCases; const int filterPixels = filterSize * filterSize; const int imgPixels = imgSize * imgSize; const int numFilterBlocks = numFilters / (B_X * filtersPerThread); const int outputModuleIdx = blockIdx.x / numFilterBlocks; const int moduleIdx = partialSum * outputModuleIdx; const int blockFilterIdx = filtersPerThread * B_X * (blockIdx.x % numFilterBlocks); const int numModules = numModulesX * numModulesX; const int numFiltersPerGroup = numFilters / numGroups; const int blockGroupIdx = blockFilterIdx / numFiltersPerGroup; const int numFilterColors = numImgColors / numGroups; const int blockPixelOffset = (blockIdx.y / (numFilterColors/colorsPerThread)) * B_Y; const int filterColorIdx = (blockIdx.y % (numFilterColors/colorsPerThread)) * colorsPerThread; const int imgColorIdx = filterColorIdx + blockGroupIdx * numFilterColors; images += imgColorIdx * imgPixels * imgStride + loadX; hidActs += moduleIdx * numImages + blockFilterIdx * numImages * numModules + loadY * numImages * numModules + loadX; targets += outputModuleIdx * numFilters * filterPixels * numFilterColors + filterColorIdx * filterPixels * numFilters + blockPixelOffset * numFilters + blockFilterIdx + threadIdx.y * numFilters + threadIdx.x; float* shHidActLoad = &shHidActs[loadY][loadX]; float* shImgLoad = &shImages[loadY][loadX]; float prod[colorsPerThread][filtersPerThread]; #pragma unroll for (int c = 0; c < colorsPerThread; c++) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { prod[c][f] = 0; } } // This avoids doing a division in an inner loop __shared__ int pxDivs[B_Y]; if (tidx < B_Y) { pxDivs[tidx] = (((blockPixelOffset + tidx) / filterSize) << 16) + (blockPixelOffset + tidx) % filterSize; } __syncthreads(); for (int m = moduleIdx; m < moduleIdx + partialSum; m++) { const int imgLoadModPosY = paddingStart + (m / numModulesX) * moduleStride; const int imgLoadModPosX = paddingStart + (m % numModulesX) * moduleStride; for (int caseIdx = 0; caseIdx < numImages; caseIdx += preloadCases) { if (loadY < B_Y) { /* * As long as B_Y * B_X is divisible by preloadCases this will loop the right * number of times. * * This will load some images from filter pixels that don't exist (it'll set those to 0), * but the code does not produce any output for those pixels (see last lines). */ // #pragma unroll for (int y = 0; y < B_Y; y += (B_X * B_Y) / preloadCases) { // Make sure number of rows in the array is divisible by number of rows filled per iteration if (B_Y % (B_X * B_Y / preloadCases) == 0 || y + loadY < B_Y) { const int pxIdx = loadY + y; // pixel idx in filter if (pxIdx + blockPixelOffset < filterPixels && (!checkCaseBounds || caseIdx + loadX < numImages)) { const int pxY = imgLoadModPosY + HI16(pxDivs[pxIdx]);//pxIdx / filterSize; // pixel x,y coords in image const int pxX = imgLoadModPosX + LO16(pxDivs[pxIdx]); if (pxY >= 0 && pxY < imgSize && pxX >= 0 && pxX < imgSize) { const int pixIdx = (pxY * imgSize + pxX) * imgStride; // pixel idx in image #pragma unroll for (int c = 0; c < colorsPerThread; c++) { shImgLoad[(y + c * B_Y) * preloadCases] = images[caseIdx + c * imgPixels * imgStride + pixIdx]; } } else { #pragma unroll for (int c = 0; c < colorsPerThread; c++) { shImgLoad[(y + c * B_Y) * preloadCases] = 0; } } } else { #pragma unroll for (int c = 0; c < colorsPerThread; c++) { shImgLoad[(y + c * B_Y) * preloadCases] = 0; } } } } } if (loadY < B_X * filtersPerThread && (!checkCaseBounds || caseIdx + loadX < numImages)) { #pragma unroll for (int y = 0; y < B_X * filtersPerThread; y += (B_X * B_Y) / preloadCases) { // Make sure number of rows in the array is divisible by number of rows filled per iteration if ((B_X * filtersPerThread) % (B_X * B_Y / preloadCases) == 0 || y + loadY < B_X * filtersPerThread) { shHidActLoad[y * (preloadCases + 1)] = hidActs[caseIdx + y * numImages * numModules]; } } } __syncthreads(); #pragma unroll for (int c = 0; c < colorsPerThread; c++) { #pragma unroll for (int i = 0; i < preloadCases; i++) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { prod[c][f] += shImages[threadIdx.y + c * B_Y][i] * shHidActs[threadIdx.x + f * B_X][i]; } } } __syncthreads(); } hidActs += numImages; } if (blockPixelOffset + threadIdx.y < filterPixels) { if (scale) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { #pragma unroll for (int c = 0; c < colorsPerThread; c++) { targets[c * filterPixels * numFilters + f * B_X] = scaleTargets * targets[c * filterPixels * numFilters + f * B_X] + scaleOutputs * prod[c][f]; } } } else { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { #pragma unroll for (int c = 0; c < colorsPerThread; c++) { targets[c * filterPixels * numFilters + f * B_X] = scaleOutputs * prod[c][f]; } } } } } template<class Agg, int B_X, int imgsPerThread, int filtersPerThread, bool checkCaseBounds> __global__ void kLocalPool2(float* imgs, float* target, const int imgSize, const int numFilters, const int numImages, const int subsX, const int startX, const int outputsX, Agg agg) { __shared__ float shImgs[filtersPerThread][B_X*imgsPerThread]; const int numImgBlocks = DIVUP(numImages,B_X*imgsPerThread); const int numFilterBlocks = numFilters/(filtersPerThread); const int blockOutputX = 4*(blockIdx.x / numImgBlocks); const int blockOutputY = 4*(blockIdx.y / numFilterBlocks); const int blockImgIdx = (blockIdx.x % numImgBlocks) * B_X * imgsPerThread; const int blockFilterIdx = (blockIdx.y % numFilterBlocks) * filtersPerThread; // const int blockOutputIdx = blockOutputY * outputsX + blockOutputX; const int numOutputs = outputsX * outputsX; const int imgPixels = imgSize * imgSize; const int tidx = threadIdx.y * B_X + threadIdx.x; const int loadY = tidx / 32, loadX = tidx % 32; const int myX = threadIdx.y % 4; const int myY = threadIdx.y / 4; const int myOutputIdxY = blockOutputY + myY; const int myOutputIdxX = blockOutputX + myX; const int myOutputIdx = myOutputIdxY * outputsX + myOutputIdxX; const int startImgPxX = startX + blockOutputX; const int startImgPxY = startX + blockOutputY; const int endImgPxX = startImgPxX + subsX; const int endImgPxY = startImgPxY + subsX; const int myStartImgPxY = startImgPxY + myY; const int myStartImgPxX = startImgPxX + myX; const int myEndImgPxY = endImgPxY + myY; const int myEndImgPxX = endImgPxX + myX; const int loopStartY = MAX(startImgPxY, 0); const int loopStartX = MAX(startImgPxX, 0); const int loopEndY = MIN(imgSize, endImgPxY + 3); const int loopEndX = MIN(imgSize, endImgPxX + 3); const int imgIdx = blockImgIdx + threadIdx.x; imgs += (blockFilterIdx + loadY) * imgPixels * numImages + blockImgIdx + loadX; target += (blockFilterIdx * numOutputs + myOutputIdx) * numImages + imgIdx; float prod[filtersPerThread][imgsPerThread]; #pragma unroll for (int f = 0; f < filtersPerThread; f++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[f][i] = agg.getBaseValue(); } } for (int y = loopStartY; y < loopEndY; y++) { const bool isInY = y >= myStartImgPxY && y < myEndImgPxY ; for (int x = loopStartX; x < loopEndX; x++) { // Load a pixel const int px = y * imgSize + x; #pragma unroll for (int ly = 0; ly < filtersPerThread; ly += B_X/2) { if (filtersPerThread % (B_X/2) == 0 || ly + loadY < filtersPerThread) { #pragma unroll for (int lx = 0; lx < B_X*imgsPerThread; lx += 32) { if (!checkCaseBounds || lx + loadX + blockImgIdx < numImages) { shImgs[ly + loadY][lx + loadX] = imgs[(ly * imgPixels + px) * numImages + lx]; } } } } __syncthreads(); // Is this pixel in my region? if (isInY && x >= myStartImgPxX && x < myEndImgPxX) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { prod[f][i] = agg(prod[f][i], shImgs[f][threadIdx.x + i * B_X]); } } } } __syncthreads(); } } if (myOutputIdxY < outputsX && myOutputIdxX < outputsX) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { target[f * numOutputs * numImages + i * B_X] = agg.output(prod[f][i]); } } } } } /* * Block size B_YxB_X * blockIdx.x determines output.x, image idx in batches of B_X*imgsPerThread * blockIdx.y determines output.y, filter idx in batches of B_Y*filtersPerThread * * So each block does one output for some number of images/filters. * * threadIdx.x determines img idx * threadIdx.y determines filter idx * * imgs: (numFilters, imgPixels, numImages) * target: (numFilters, numOutputs, numImages) * * numImages must be divisible by B_X*imgsPerThread if checkCaseBounds is false */ template<class Agg, int B_Y, int B_X, int imgsPerThread, int filtersPerThread, bool checkCaseBounds> __global__ void kLocalPool(float* imgs, float* target, const int imgSize, const int numFilters, const int numImages, const int subsX, const int startX, const int strideX, const int outputsX, Agg agg) { const int numImgBlocks = DIVUP(numImages,B_X*imgsPerThread); const int numFilterBlocks = DIVUP(numFilters, B_Y*filtersPerThread); const int outputIdxX = blockIdx.x / numImgBlocks; const int outputIdxY = blockIdx.y / numFilterBlocks; const int blockImgIdx = (blockIdx.x % numImgBlocks) * B_X * imgsPerThread; const int blockFilterIdx = (blockIdx.y % numFilterBlocks) * B_Y * filtersPerThread; const int myFilterIdx = (blockFilterIdx + threadIdx.y*filtersPerThread); if (myFilterIdx >= numFilters) { return; } const int outputIdx = outputIdxY * outputsX + outputIdxX; const int numOutputs = outputsX * outputsX; const int imgPixels = imgSize * imgSize; const int startImgPxX = startX + outputIdxX * strideX; const int startImgPxY = startX + outputIdxY * strideX; const int imgIdx = blockImgIdx + threadIdx.x; imgs += myFilterIdx * imgPixels * numImages + imgIdx; target += (myFilterIdx * numOutputs + outputIdx) * numImages + imgIdx; float prod[filtersPerThread][imgsPerThread]; #pragma unroll for (int f = 0; f < filtersPerThread; f++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[f][i] = agg.getBaseValue(); } } const int loopStartY = MAX(0, startImgPxY); const int loopStartX = MAX(0, startImgPxX); const int loopEndY = MIN(imgSize, startImgPxY + subsX); const int loopEndX = MIN(imgSize, startImgPxX + subsX); for (int y = loopStartY; y < loopEndY; y++) { for (int x = loopStartX; x < loopEndX; x++) { const int imgPx = y * imgSize + x; #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { prod[f][i] = agg(prod[f][i], imgs[(f * imgPixels + imgPx) * numImages + i * B_X]); } } } } } #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { target[f * numOutputs * numImages + i * B_X] = agg.output(prod[f][i]); } } } } /* * Block size B_YxB_X * blockIdx.x determines pixel.x, image idx in batches of B_X*imgsPerThread * blockIdx.y determines pixel.y, filter idx in batches of B_Y*filtersPerThread * * So each block does one output pixel for some number of images/filters. * * threadIdx.x determines img idx * threadIdx.y determines filter idx * * imgs: (numFilters, imgPixels, numImages) * maxGrads: (numFilters, numOutputs, numImages) * rMaxActs: (numFilters, numOutputs, numImages) * target: (numFilters, imgPixels, numImages) * * numImages must be divisible by B_X*imgsPerThread * numFilters must be divisible by B_Y*filtersPerThread */ template<int B_Y, int B_X, int imgsPerThread, int filtersPerThread, bool add, bool checkCaseBounds> __global__ void kLocalMaxUndo(float* imgs, float* maxGrads, float* maxActs, float* target, const int imgSize, const int numFilters, const int numImages, const int subsX, const int startX, const int strideX, const int outputsX, const float scaleTargets, const float scaleOutputs) { __shared__ float shImgs[B_Y*filtersPerThread][B_X*imgsPerThread]; const int numImgBlocks = DIVUP(numImages,B_X*imgsPerThread); const int blockPxX = blockIdx.x / numImgBlocks; const int blockPxY = blockIdx.y / (numFilters/(B_Y*filtersPerThread)); const int blockImgIdx = (blockIdx.x % numImgBlocks) * B_X * imgsPerThread; const int blockFilterIdx = (blockIdx.y % (numFilters/(B_Y*filtersPerThread))) * B_Y * filtersPerThread; const int blockPx = blockPxY * imgSize + blockPxX; const int numOutputs = outputsX * outputsX; const int imgPixels = imgSize * imgSize; const int startOutputY = blockPxY - startX < subsX ? 0 : 1 + (blockPxY - startX - subsX) / strideX; const int endOutputY = MIN(outputsX, 1 + (blockPxY - startX) / strideX); const int startOutputX = blockPxX - startX < subsX ? 0 : 1 + (blockPxX - startX - subsX) / strideX; const int endOutputX = MIN(outputsX, 1 + (blockPxX - startX) / strideX); const int imgIdx = blockImgIdx + threadIdx.x; imgs += ((blockFilterIdx + threadIdx.y) * imgPixels + blockPx) * numImages + imgIdx; maxGrads += ((blockFilterIdx + threadIdx.y) * numOutputs) * numImages + imgIdx; maxActs += ((blockFilterIdx + threadIdx.y) * numOutputs) * numImages + imgIdx; target += ((blockFilterIdx + threadIdx.y) * imgPixels + blockPx) * numImages + imgIdx; float prod[filtersPerThread][imgsPerThread]; #pragma unroll for (int f = 0; f < filtersPerThread; f++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[f][i] = 0; } } if (blockPxX >= startX && blockPxX < startX + strideX * (outputsX-1) + subsX && blockPxY >= startX && blockPxY < startX + strideX * (outputsX-1) + subsX) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { shImgs[threadIdx.y + B_Y * f][threadIdx.x + B_X * i] = imgs[f * B_Y * imgPixels * numImages + i * B_X]; } } } for (int my = startOutputY; my < endOutputY; my++) { for (int mx = startOutputX; mx < endOutputX; mx++) { const int outputIdx = my * outputsX + mx; #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { const float ma = maxActs[(f * B_Y * numOutputs + outputIdx) * numImages + i * B_X]; const float mg = maxGrads[(f * B_Y * numOutputs + outputIdx) * numImages + i * B_X]; const float img = shImgs[threadIdx.y + B_Y * f][threadIdx.x + B_X * i]; prod[f][i] += (img == ma) * mg; } } } } } } if (!add) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { target[f * B_Y * imgPixels * numImages + i * B_X] = prod[f][i]; } } } } else { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { target[f * B_Y * imgPixels * numImages + i * B_X] = scaleTargets * target[f * B_Y * imgPixels * numImages + i * B_X] + scaleOutputs * prod[f][i]; } } } } } /* * Block size B_YxB_X * blockIdx.x determines output.x, image idx in batches of B_X*imgsPerThread * blockIdx.y determines output.y, filter idx in batches of B_Y*filtersPerThread * * So each block does one output for some number of images/filters. * * threadIdx.x determines img idx * threadIdx.y determines filter idx * * imgs: (numFilters, imgPixels, numImages) * rnd : (numFilters, imgPixels, numImages) * target: (numFilters, numOutputs, numImages) * * numImages must be divisible by B_X*imgsPerThread if checkCaseBounds is false */ template<class Agg, int B_Y, int B_X, int imgsPerThread, int filtersPerThread, bool checkCaseBounds> __global__ void kLocalProbPool(float* imgs, float* rnd, float* target, const int imgSize, const int numFilters, const int numImages, const int subsX, const int startX, const int strideX, const int outputsX, Agg agg) { const int numImgBlocks = DIVUP(numImages,B_X*imgsPerThread); const int numFilterBlocks = DIVUP(numFilters, B_Y*filtersPerThread); const int outputIdxX = blockIdx.x / numImgBlocks; const int outputIdxY = blockIdx.y / numFilterBlocks; const int blockImgIdx = (blockIdx.x % numImgBlocks) * B_X * imgsPerThread; const int blockFilterIdx = (blockIdx.y % numFilterBlocks) * B_Y * filtersPerThread; const int myFilterIdx = (blockFilterIdx + threadIdx.y*filtersPerThread); if (myFilterIdx >= numFilters) { return; } const int outputIdx = outputIdxY * outputsX + outputIdxX; const int numOutputs = outputsX * outputsX; const int imgPixels = imgSize * imgSize; const int startImgPxX = startX + outputIdxX * strideX; const int startImgPxY = startX + outputIdxY * strideX; const int imgIdx = blockImgIdx + threadIdx.x; imgs += myFilterIdx * imgPixels * numImages + imgIdx; rnd += myFilterIdx * imgPixels * numImages + imgIdx; target += (myFilterIdx * numOutputs + outputIdx) * numImages + imgIdx; float prod[filtersPerThread][imgsPerThread]; float rnd_used[filtersPerThread][imgsPerThread]; #pragma unroll for (int f = 0; f < filtersPerThread; f++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[f][i] = agg.getBaseValue(); rnd_used[f][i] = agg.getBaseValue(); } } const int loopStartY = MAX(0, startImgPxY); const int loopStartX = MAX(0, startImgPxX); const int loopEndY = MIN(imgSize, startImgPxY + subsX); const int loopEndX = MIN(imgSize, startImgPxX + subsX); for (int y = loopStartY; y < loopEndY; y++) { for (int x = loopStartX; x < loopEndX; x++) { const int imgPx = y * imgSize + x; #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { const int loc = (f * imgPixels + imgPx) * numImages + i * B_X; const int res = agg(prod[f][i], imgs[loc], rnd_used[f][i], rnd[loc]); prod[f][i] = res == 0 ? prod[f][i] : imgs[loc]; rnd_used[f][i] = res == 0 ? rnd_used[f][i] : rnd[loc]; } } } } } #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { target[f * numOutputs * numImages + i * B_X] = agg.output(prod[f][i]); } } } } /* * Block size 16xB_X * blockIdx.x determines 4x4 pixel.x region, image idx in batches of B_X*imgsPerThread * blockIdx.y determines 4x4 pixel.y region, filter idx in batches of filtersPerThread * * So each block does a 4x4 region for some number of images/filters. * * threadIdx.x determines img idx * threadIdx.y determines pixel idx * * imgs: (numFilters, imgPixels, numImages) * target: (numFilters, numOutputs, numImages) * * B_X one of 8, 16, 32 * imgsPerThread one of 1, 2, 4, 8, 16 * * B_XximgsPerThread MUST be divisible by 32. * Number of filters MUST be divisible by filtersPerThread. * * numImages must be divisible by B_X*imgsPerThread if checkCaseBounds is false * * Final write-out will not be fully coalesced unless B_X is 32. But there's a lot more * reading than writing here, and the reading is all coalesced, so it should be OK. * * To be used when the stride is 1 and the pooling region is fairly large. */ template<class Agg, int B_X, int imgsPerThread, int filtersPerThread, bool checkCaseBounds> __global__ void kLocalProbPool2(float* imgs, float* rnd, float* target, const int imgSize, const int numFilters, const int numImages, const int subsX, const int startX, const int outputsX, Agg agg) { __shared__ float shImgs[filtersPerThread][B_X*imgsPerThread]; __shared__ float shRnd[filtersPerThread][B_X*imgsPerThread]; const int numImgBlocks = DIVUP(numImages,B_X*imgsPerThread); const int numFilterBlocks = numFilters/(filtersPerThread); const int blockOutputX = 4*(blockIdx.x / numImgBlocks); const int blockOutputY = 4*(blockIdx.y / numFilterBlocks); const int blockImgIdx = (blockIdx.x % numImgBlocks) * B_X * imgsPerThread; const int blockFilterIdx = (blockIdx.y % numFilterBlocks) * filtersPerThread; // const int blockOutputIdx = blockOutputY * outputsX + blockOutputX; const int numOutputs = outputsX * outputsX; const int imgPixels = imgSize * imgSize; const int tidx = threadIdx.y * B_X + threadIdx.x; const int loadY = tidx / 32, loadX = tidx % 32; const int myX = threadIdx.y % 4; const int myY = threadIdx.y / 4; const int myOutputIdxY = blockOutputY + myY; const int myOutputIdxX = blockOutputX + myX; const int myOutputIdx = myOutputIdxY * outputsX + myOutputIdxX; const int startImgPxX = startX + blockOutputX; const int startImgPxY = startX + blockOutputY; const int endImgPxX = startImgPxX + subsX; const int endImgPxY = startImgPxY + subsX; const int myStartImgPxY = startImgPxY + myY; const int myStartImgPxX = startImgPxX + myX; const int myEndImgPxY = endImgPxY + myY; const int myEndImgPxX = endImgPxX + myX; const int loopStartY = MAX(startImgPxY, 0); const int loopStartX = MAX(startImgPxX, 0); const int loopEndY = MIN(imgSize, endImgPxY + 3); const int loopEndX = MIN(imgSize, endImgPxX + 3); const int imgIdx = blockImgIdx + threadIdx.x; imgs += (blockFilterIdx + loadY) * imgPixels * numImages + blockImgIdx + loadX; rnd += (blockFilterIdx + loadY) * imgPixels * numImages + blockImgIdx + loadX; target += (blockFilterIdx * numOutputs + myOutputIdx) * numImages + imgIdx; float prod[filtersPerThread][imgsPerThread]; float rnd_used[filtersPerThread][imgsPerThread]; #pragma unroll for (int f = 0; f < filtersPerThread; f++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[f][i] = agg.getBaseValue(); rnd_used[f][i] = agg.getBaseValue(); } } for (int y = loopStartY; y < loopEndY; y++) { const bool isInY = y >= myStartImgPxY && y < myEndImgPxY ; for (int x = loopStartX; x < loopEndX; x++) { // Load a pixel const int px = y * imgSize + x; #pragma unroll for (int ly = 0; ly < filtersPerThread; ly += B_X/2) { if (filtersPerThread % (B_X/2) == 0 || ly + loadY < filtersPerThread) { #pragma unroll for (int lx = 0; lx < B_X*imgsPerThread; lx += 32) { if (!checkCaseBounds || lx + loadX + blockImgIdx < numImages) { shImgs[ly + loadY][lx + loadX] = imgs[(ly * imgPixels + px) * numImages + lx]; shRnd[ly + loadY][lx + loadX] = rnd[(ly * imgPixels + px) * numImages + lx]; } } } } __syncthreads(); // Is this pixel in my region? if (isInY && x >= myStartImgPxX && x < myEndImgPxX) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { const int loc = threadIdx.x + i * B_X; const int res = agg(prod[f][i], shImgs[f][loc], rnd_used[f][i], shRnd[f][loc]); prod[f][i] = res == 0 ? prod[f][i] : shImgs[f][loc]; rnd_used[f][i] = res == 0 ? rnd_used[f][i] : shRnd[f][loc]; } } } } __syncthreads(); } } if (myOutputIdxY < outputsX && myOutputIdxX < outputsX) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { target[f * numOutputs * numImages + i * B_X] = agg.output(prod[f][i]); } } } } } /* * Block size 16xB_X * blockIdx.x determines 4x4 pixel.x region, image idx in batches of B_X*imgsPerThread * blockIdx.y determines 4x4 pixel.y region, filter idx in batches of filtersPerThread * * So each block does 4x4 region for some number of images/filters. * * threadIdx.x determines img idx * threadIdx.y determines pixel idx * * outGrads: (numFilters, imgPixels, numImages) * denoms: (numFilters, imgPixels, numImages) * inputs: (numFilters, imgPixels, numImages) * acts: (numFilters, imgPixels, numImages) * target: (numFilters, imgPixels, numImages) * * B_X one of 8, 16, 32 * imgsPerThread one of 1, 2, 4, 8, 16 * * B_XximgsPerThread MUST be divisible by 32. * Number of filters MUST be divisible by filtersPerThread. * * numImages must be divisible by B_X*imgsPerThread if checkCaseBounds is false * numFilters must be divisible by filtersPerThread * * Final write-out will not be fully coalesced unless B_X is 32. But there's a lot more * reading than writing here, and the reading is all coalesced, so it should be OK. */ template<int B_X, int imgsPerThread, int filtersPerThread, bool add, bool checkCaseBounds> __global__ void kRNormUndo2(float* outGrads, float* denoms, float* inputs, float* acts, float* target, const int imgSize, const int numFilters, const int numImages, const int sizeX, const float powScale, const float scaleTargets, const float scaleOutputs) { __shared__ float shActs[filtersPerThread][B_X*imgsPerThread]; const int imgPixels = imgSize * imgSize; const int numImgBlocks = DIVUP(numImages, B_X*imgsPerThread); const int numFilterBlocks = numFilters/(filtersPerThread); const int blockPxX = 4*(blockIdx.x / numImgBlocks); const int blockPxY = 4*(blockIdx.y / numFilterBlocks); const int blockImgIdx = (blockIdx.x % numImgBlocks) * B_X * imgsPerThread; const int blockFilterIdx = (blockIdx.y % numFilterBlocks) * filtersPerThread; const int tidx = threadIdx.y * B_X + threadIdx.x; const int loadY = tidx / 32, loadX = tidx % 32; const int startPxX = MAX(0, -DIVUP(sizeX,2) + blockPxX + 1); const int startPxY = MAX(0, -DIVUP(sizeX,2) + blockPxY + 1); const int endPxX = MIN(imgSize, blockPxX + sizeX/2 + 4); const int endPxY = MIN(imgSize, blockPxY + sizeX/2 + 4); const int myPxX = blockPxX + threadIdx.y % 4; const int myPxY = blockPxY + threadIdx.y / 4; const int myPxIdx = myPxY * imgSize + myPxX; // const bool doWork = myPxX < imgSize && myPxY < imgSize; const int myStartPxY = -DIVUP(sizeX,2) + myPxY + 1; const int myStartPxX = -DIVUP(sizeX,2) + myPxX + 1; const int myEndPxY = myPxY + sizeX/2 + 1; const int myEndPxX = myPxX + sizeX/2 + 1; const int imgIdx = blockImgIdx + threadIdx.x; acts += (blockFilterIdx + loadY) * imgPixels * numImages + blockImgIdx + loadX; denoms += (blockFilterIdx * imgPixels + myPxIdx) * numImages + imgIdx; inputs += (blockFilterIdx * imgPixels + myPxIdx) * numImages + imgIdx; outGrads += (blockFilterIdx * imgPixels + myPxIdx) * numImages + imgIdx; target += (blockFilterIdx * imgPixels + myPxIdx) * numImages + imgIdx; float prod[filtersPerThread][imgsPerThread]; #pragma unroll for (int f = 0; f < filtersPerThread; f++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[f][i] = 0; } } for (int y = startPxY; y < endPxY; y++) { const bool isInY = y >= myStartPxY && y < myEndPxY; for (int x = startPxX; x < endPxX; x++) { const int px = y * imgSize + x; // All the threads load a pixel from memory #pragma unroll for (int ly = 0; ly < filtersPerThread; ly += B_X/2) { if (filtersPerThread % (B_X/2) == 0 || ly + loadY < filtersPerThread) { #pragma unroll for (int lx = 0; lx < B_X*imgsPerThread; lx += 32) { if (!checkCaseBounds || lx + loadX + blockImgIdx < numImages) { shActs[ly + loadY][lx + loadX] = acts[(ly * imgPixels + px) * numImages + lx]; } } } } __syncthreads(); // Each row of threads decides if it's interested in this pixel if (isInY && x >= myStartPxX && x < myEndPxX) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { prod[f][i] += shActs[f][threadIdx.x + i * B_X]; } } } } __syncthreads(); } } acts -= (loadY * imgPixels - myPxIdx) * numImages + loadX; acts += threadIdx.x; if (myPxX < imgSize && myPxY < imgSize) { if (!add) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { const float out = outGrads[f * imgPixels * numImages + i * B_X]; const float den = denoms[f * imgPixels * numImages + i * B_X]; const float inp = inputs[f * imgPixels * numImages + i * B_X]; prod[f][i] = inp * prod[f][i] + out * __powf(den, -powScale); target[f * imgPixels * numImages + i * B_X] = prod[f][i]; } } } } else { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { const float out = outGrads[f * imgPixels * numImages + i * B_X]; const float den = denoms[f * imgPixels * numImages + i * B_X]; const float inp = inputs[f * imgPixels * numImages + i * B_X]; prod[f][i] = inp * prod[f][i] + out * __powf(den, -powScale); target[f * imgPixels * numImages + i * B_X] = scaleTargets * target[f * imgPixels * numImages + i * B_X] + scaleOutputs * prod[f][i]; } } } } } } /* * Block size B_YxB_X * blockIdx.x determines pixel.x, image idx in batches of B_X*imgsPerThread * blockIdx.y determines pixel.y, filter idx in batches of B_Y*filtersPerThread * * So each block does one output pixel for some number of images/filters. * * threadIdx.x determines img idx * threadIdx.y determines filter idx * * outGrads: (numFilters, imgPixels, numImages) * denoms: (numFilters, imgPixels, numImages) * inputs: (numFilters, imgPixels, numImages) * acts: (numFilters, imgPixels, numImages) * target: (numFilters, imgPixels, numImages) * * numImages must be divisible by B_X*imgsPerThread * numFilters must be divisible by B_Y*filtersPerThread * * TODO: this isn't really ideal */ template<int B_Y, int B_X, int imgsPerThread, int filtersPerThread, bool add, bool checkCaseBounds> __global__ void kRNormUndo(float* outGrads, float* denoms, float* inputs, float* acts, float* target, const int imgSize, const int numFilters, const int numImages, const int sizeX, const float powScale, const float scaleTargets, const float scaleOutputs) { const int numImgBlocks = DIVUP(numImages,B_X*imgsPerThread); const int numFilterBlocks = numFilters/(B_Y*filtersPerThread); const int blockPxX = blockIdx.x / numImgBlocks; const int blockPxY = blockIdx.y / numFilterBlocks; const int blockImgIdx = (blockIdx.x % numImgBlocks) * B_X * imgsPerThread; const int blockFilterIdx = (blockIdx.y % numFilterBlocks) * B_Y * filtersPerThread; const int blockPx = blockPxY * imgSize + blockPxX; const int imgPixels = imgSize * imgSize; const int startY = MAX(0, blockPxY + sizeX/2 - sizeX + 1); const int startX = MAX(0, blockPxX + sizeX/2 - sizeX + 1); const int endY = MIN(imgSize, blockPxY + sizeX/2 + 1); const int endX = MIN(imgSize, blockPxX + sizeX/2 + 1); const int imgIdx = blockImgIdx + threadIdx.x; acts += ((blockFilterIdx + threadIdx.y) * imgPixels) * numImages + imgIdx; inputs += ((blockFilterIdx + threadIdx.y) * imgPixels + blockPx) * numImages + imgIdx; denoms += ((blockFilterIdx + threadIdx.y) * imgPixels + blockPx) * numImages + imgIdx; outGrads += ((blockFilterIdx + threadIdx.y) * imgPixels + blockPx) * numImages + imgIdx; target += ((blockFilterIdx + threadIdx.y) * imgPixels + blockPx) * numImages + imgIdx; float prod[filtersPerThread][imgsPerThread]; #pragma unroll for (int f = 0; f < filtersPerThread; f++) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { prod[f][i] = 0; } } for (int sy = startY; sy < endY; sy++) { for (int sx = startX; sx < endX; sx++) { const int outPx = sy * imgSize + sx; #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { prod[f][i] += acts[(f * B_Y * imgPixels + outPx) * numImages + i * B_X]; } } } } } // outGrads += blockPx * numImages; if (!add) { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { const float inp = inputs[(f * B_Y * imgPixels) * numImages + i * B_X]; const float out = outGrads[(f * B_Y * imgPixels) * numImages + i * B_X]; const float den = denoms[(f * B_Y * imgPixels) * numImages + i * B_X]; prod[f][i] = inp * prod[f][i] + out * __powf(den, -powScale); target[f * B_Y * imgPixels * numImages + i * B_X] = prod[f][i]; } } } } else { #pragma unroll for (int i = 0; i < imgsPerThread; i++) { if (!checkCaseBounds || imgIdx + i * B_X < numImages) { #pragma unroll for (int f = 0; f < filtersPerThread; f++) { const float inp = inputs[(f * B_Y * imgPixels) * numImages + i * B_X]; const float out = outGrads[(f * B_Y * imgPixels) * numImages + i * B_X]; const float den = denoms[(f * B_Y * imgPixels) * numImages + i * B_X]; prod[f][i] = inp * prod[f][i] + out * __powf(den, -powScale); target[f * B_Y * imgPixels * numImages + i * B_X] = scaleTargets * target[f * B_Y * imgPixels * numImages + i * B_X] + scaleOutputs * prod[f][i]; } } } } } /* * acts := -2 x scale x acts x outGrads / denoms */ template<int B_X, int eltsPerThread> __global__ void kRNormUndoPrelims(float* acts, float* denoms, float* outGrads, const uint numElements, const float scale) { const uint e = B_X * blockIdx.x * eltsPerThread + threadIdx.x; const uint numThreads = B_X * gridDim.x; for (uint i = e; i < numElements; i += numThreads*eltsPerThread) { #pragma unroll for (uint k = 0; k < eltsPerThread; k++) { if (i + k * B_X < numElements) { acts[i + k * B_X] = __fdividef(scale*outGrads[i + k * B_X] * acts[i + k * B_X], denoms[i + k * B_X]); } } } }
the_stack
namespace PyCA { namespace Splatting{ inline __device__ void atomicSplat(int* d_wd, float mass, float x, float y, float z, int w, int h, int l) { int xInt = int(x); int yInt = int(y); int zInt = int(z); if (x < 0 && x != xInt) --xInt; if (y < 0 && y != yInt) --yInt; if (z < 0 && z != zInt) --zInt; float dx = 1.f - (x - xInt); float dy = 1.f - (y - yInt); float dz = 1.f - (z - zInt); int nid = (zInt * h + yInt) * w + xInt; int dist; if (isInside3D(xInt, yInt, zInt, w, h, l)){ dist = S2p20(mass * dx * dy * dz); atomicAdd(&d_wd[nid],dist); } if (isInside3D(xInt + 1, yInt, zInt, w, h, l)){ dist = S2p20(mass * (1.f-dx) * dy * dz); atomicAdd(&d_wd[nid + 1], dist); } if (isInside3D(xInt, yInt+1, zInt, w, h, l)){ dist = S2p20(mass * dx * (1.f - dy) * dz); atomicAdd(&d_wd[nid + w], dist); } if (isInside3D(xInt+1, yInt+1, zInt, w, h, l)){ dist = S2p20(mass * (1.f -dx) * (1.f - dy) * dz); atomicAdd(&d_wd[nid + w + 1], dist); } nid += w*h; if (isInside3D(xInt, yInt, zInt + 1, w, h, l)){ dist = S2p20(mass * dx * dy * (1.f - dz)); atomicAdd(&d_wd[nid],dist); } if (isInside3D(xInt + 1, yInt, zInt+1, w, h, l)){ dist = S2p20(mass * (1.f-dx) * dy * (1.f -dz)); atomicAdd(&d_wd[nid + 1], dist); } if (isInside3D(xInt, yInt+1, zInt+1, w, h, l)){ dist = S2p20(mass * dx * (1.f - dy) * (1.f -dz)); atomicAdd(&d_wd[nid + w], dist); } if (isInside3D(xInt+1, yInt+1, zInt+1, w, h, l)){ dist = S2p20(mass * (1.f -dx) * (1.f - dy) * (1.f -dz)); atomicAdd(&d_wd[nid + w + 1], dist); } } //////////////////////////////////////////////////////////////////////////////// /// Splat mass along with weight vector /// d_wd = sum dist * d_w (weighted distance) //////////////////////////////////////////////////////////////////////////////// inline __device__ void atomicSplat(int* d_wd, int* d_ww, float mass, float x, float y, float z, int w, int h, int l) { int xInt = int(x); int yInt = int(y); int zInt = int(z); if (x < 0 && x != xInt) --xInt; if (y < 0 && y != yInt) --yInt; if (z < 0 && z != zInt) --zInt; float dx = 1.f - (x - xInt); float dy = 1.f - (y - yInt); float dz = 1.f - (z - zInt); int nid = (zInt * h + yInt) * w + xInt; int dist, ww; if (isInside3D(xInt, yInt, zInt, w, h, l)){ dist = S2p20(mass * dx * dy * dz); ww = S2p20(dx * dy * dz); atomicAdd(&d_wd[nid],dist); atomicAdd(&d_ww[nid],ww); } if (isInside3D(xInt + 1, yInt, zInt, w, h, l)){ dist = S2p20(mass * (1.f-dx) * dy * dz); ww = S2p20((1.f-dx) * dy * dz); atomicAdd(&d_wd[nid + 1], dist); atomicAdd(&d_ww[nid + 1], ww); } if (isInside3D(xInt, yInt+1, zInt, w, h, l)){ dist = S2p20(mass * dx * (1.f - dy) * dz); ww = S2p20(dx * (1.f - dy) * dz); atomicAdd(&d_wd[nid + w], dist); atomicAdd(&d_ww[nid + w], ww); } if (isInside3D(xInt+1, yInt+1, zInt, w, h, l)){ dist = S2p20(mass * (1.f -dx) * (1.f - dy) * dz); ww = S2p20((1.f -dx) * (1.f - dy) * dz); atomicAdd(&d_wd[nid + w + 1], dist); atomicAdd(&d_ww[nid + w + 1], ww); } nid += w*h; if (isInside3D(xInt, yInt, zInt + 1, w, h, l)){ dist = S2p20(mass * dx * dy * (1.f - dz)); ww = S2p20(dx * dy * (1.f - dz)); atomicAdd(&d_wd[nid], dist); atomicAdd(&d_ww[nid], ww); } if (isInside3D(xInt + 1, yInt, zInt+1, w, h, l)){ dist = S2p20(mass * (1.f-dx) * dy * (1.f -dz)); ww = S2p20((1.f-dx) * dy * (1.f -dz)); atomicAdd(&d_wd[nid + 1], dist); atomicAdd(&d_ww[nid + 1], ww); } if (isInside3D(xInt, yInt+1, zInt+1, w, h, l)){ dist = S2p20(mass * dx * (1.f - dy) * (1.f -dz)); ww = S2p20(dx * (1.f - dy) * (1.f -dz)); atomicAdd(&d_wd[nid + w], dist); atomicAdd(&d_ww[nid + w], ww); } if (isInside3D(xInt+1, yInt+1, zInt+1, w, h, l)){ dist = S2p20(mass * (1.f -dx) * (1.f - dy) * (1.f -dz)); ww = S2p20((1.f -dx) * (1.f - dy) * (1.f -dz)); atomicAdd(&d_wd[nid + w + 1], dist); atomicAdd(&d_ww[nid + w + 1], ww); } } //////////////////////////////////////////////////////////////////////////////// /// Vector version: Splat both the function p_u to the neighbor point to the grid /// d_wd = sum dist * d_w (weighted distance) //////////////////////////////////////////////////////////////////////////////// inline __device__ void atomicSplat(int* d_wd, int* d_wd1, int* d_wd2, float mass, float mass1, float mass2, float x, float y, float z, int w, int h, int l) { int xInt = int(x); int yInt = int(y); int zInt = int(z); if (x < 0 && x != xInt) --xInt; if (y < 0 && y != yInt) --yInt; if (z < 0 && z != zInt) --zInt; float dx = 1.f - (x - xInt); float dy = 1.f - (y - yInt); float dz = 1.f - (z - zInt); int nid = (zInt * h + yInt) * w + xInt; int dist; float weight; if (isInside3D(xInt, yInt, zInt, w, h, l)){ weight = dx * dy * dz; dist = S2p20(mass * weight); atomicAdd(&d_wd[nid],dist); dist = S2p20(mass1 * weight); atomicAdd(&d_wd1[nid],dist); dist = S2p20(mass2 * weight); atomicAdd(&d_wd2[nid],dist); } if (isInside3D(xInt + 1, yInt, zInt, w, h, l)){ weight = (1.f-dx) * dy * dz; dist = S2p20(mass * weight); atomicAdd(&d_wd[nid + 1], dist); dist = S2p20(mass1 * weight); atomicAdd(&d_wd1[nid + 1], dist); dist = S2p20(mass2 * weight); atomicAdd(&d_wd2[nid + 1], dist); } if (isInside3D(xInt, yInt+1, zInt, w, h, l)){ weight = dx * (1.f - dy) * dz; dist = S2p20(mass * weight); atomicAdd(&d_wd[nid + w], dist); dist = S2p20(mass1 * weight); atomicAdd(&d_wd1[nid + w], dist); dist = S2p20(mass2 * weight); atomicAdd(&d_wd2[nid + w], dist); } if (isInside3D(xInt+1, yInt+1, zInt, w, h, l)){ weight = (1.f -dx) * (1.f - dy) * dz; dist = S2p20(mass * weight); atomicAdd(&d_wd[nid + w + 1], dist); dist = S2p20(mass1 * weight); atomicAdd(&d_wd1[nid + w + 1], dist); dist = S2p20(mass2 * weight); atomicAdd(&d_wd2[nid + w + 1], dist); } nid += w*h; if (isInside3D(xInt, yInt, zInt + 1, w, h, l)){ weight = dx * dy * (1.f - dz); dist = S2p20(mass * weight); atomicAdd(&d_wd[nid],dist); dist = S2p20(mass1 * weight); atomicAdd(&d_wd1[nid],dist); dist = S2p20(mass2 * weight); atomicAdd(&d_wd2[nid],dist); } if (isInside3D(xInt + 1, yInt, zInt+1, w, h, l)){ weight = (1.f-dx) * dy * (1.f -dz); dist = S2p20(mass * weight); atomicAdd(&d_wd[nid + 1], dist); dist = S2p20(mass1 * weight); atomicAdd(&d_wd1[nid + 1], dist); dist = S2p20(mass2 * weight); atomicAdd(&d_wd2[nid + 1], dist); } if (isInside3D(xInt, yInt+1, zInt+1, w, h, l)){ weight = dx * (1.f - dy) * (1.f -dz); dist = S2p20(mass * weight); atomicAdd(&d_wd[nid + w], dist); dist = S2p20(mass1 * weight); atomicAdd(&d_wd1[nid + w], dist); dist = S2p20(mass2 * weight); atomicAdd(&d_wd2[nid + w], dist); } if (isInside3D(xInt+1, yInt+1, zInt+1, w, h, l)){ weight = (1.f -dx) * (1.f - dy) * (1.f -dz); dist = S2p20(mass * weight); atomicAdd(&d_wd[nid + w + 1], dist); dist = S2p20(mass1 * weight); atomicAdd(&d_wd1[nid + w + 1], dist); dist = S2p20(mass2 * weight); atomicAdd(&d_wd2[nid + w + 1], dist); } } #if __CUDA_ARCH__ >= 200 inline __device__ void atomicSplatFloat(float* d_wd, float mass, float x, float y, float z, int w, int h, int l) { int xInt = int(x); int yInt = int(y); int zInt = int(z); if (x < 0 && x != xInt) --xInt; if (y < 0 && y != yInt) --yInt; if (z < 0 && z != zInt) --zInt; float dx = 1.f - (x - float(xInt)); float dy = 1.f - (y - float(yInt)); float dz = 1.f - (z - float(zInt)); int nid = (zInt * h + yInt) * w + xInt; float ww; if (isInside3D(xInt, yInt, zInt, w, h, l)){ ww = dx * dy * dz; atomicAdd(&d_wd[nid], mass*ww); } if (isInside3D(xInt + 1, yInt, zInt, w, h, l)){ ww = (1.f-dx) * dy * dz; atomicAdd(&d_wd[nid + 1], mass*ww); } if (isInside3D(xInt, yInt + 1, zInt, w, h, l)){ ww = dx * (1.f - dy) * dz; atomicAdd(&d_wd[nid + w], mass*ww); } if (isInside3D(xInt+1, yInt+1, zInt, w, h, l)){ ww = (1.f -dx) * (1.f - dy) * dz; atomicAdd(&d_wd[nid + w + 1], mass*ww); } nid += w*h; if (isInside3D(xInt, yInt, zInt + 1, w, h, l)){ ww = dx * dy * (1.f - dz); atomicAdd(&d_wd[nid], mass*ww); } if (isInside3D(xInt + 1, yInt, zInt+1, w, h, l)){ ww = (1.f-dx) * dy * (1.f -dz); atomicAdd(&d_wd[nid + 1], mass*ww); } if (isInside3D(xInt, yInt+1, zInt+1, w, h, l)){ ww = dx * (1.f - dy) * (1.f -dz); atomicAdd(&d_wd[nid + w], mass*ww); } if (isInside3D(xInt+1, yInt+1, zInt+1, w, h, l)){ ww = (1.f -dx) * (1.f - dy) * (1.f -dz); atomicAdd(&d_wd[nid + w + 1], mass*ww); } } //////////////////////////////////////////////////////////////////////////////// /// Splat mass along with weight vector /// d_wd = sum dist * d_w (weighted distance) //////////////////////////////////////////////////////////////////////////////// inline __device__ void atomicSplatFloat(float* d_wd, float* d_ww, float mass, float x, float y, float z, int w, int h, int l) { int xInt = int(x); int yInt = int(y); int zInt = int(z); if (x < 0 && x != xInt) --xInt; if (y < 0 && y != yInt) --yInt; if (z < 0 && z != zInt) --zInt; float dx = 1.f - (x - float(xInt)); float dy = 1.f - (y - float(yInt)); float dz = 1.f - (z - float(zInt)); int nid = (zInt * h + yInt) * w + xInt; float ww; if (isInside3D(xInt, yInt, zInt, w, h, l)){ ww = dx * dy * dz; atomicAdd(&d_wd[nid], mass*ww); atomicAdd(&d_ww[nid], ww); } if (isInside3D(xInt + 1, yInt, zInt, w, h, l)){ ww = (1.f-dx) * dy * dz; atomicAdd(&d_wd[nid + 1], mass*ww); atomicAdd(&d_ww[nid + 1], ww); } if (isInside3D(xInt, yInt + 1, zInt, w, h, l)){ ww = dx * (1.f - dy) * dz; atomicAdd(&d_wd[nid + w], mass*ww); atomicAdd(&d_ww[nid + w], ww); } if (isInside3D(xInt+1, yInt+1, zInt, w, h, l)){ ww = (1.f -dx) * (1.f - dy) * dz; atomicAdd(&d_wd[nid + w + 1], mass*ww); atomicAdd(&d_ww[nid + w + 1], ww); } nid += w*h; if (isInside3D(xInt, yInt, zInt + 1, w, h, l)){ ww = dx * dy * (1.f - dz); atomicAdd(&d_wd[nid], mass*ww); atomicAdd(&d_ww[nid], ww); } if (isInside3D(xInt + 1, yInt, zInt+1, w, h, l)){ ww = (1.f-dx) * dy * (1.f -dz); atomicAdd(&d_wd[nid + 1], mass*ww); atomicAdd(&d_ww[nid + 1], ww); } if (isInside3D(xInt, yInt+1, zInt+1, w, h, l)){ ww = dx * (1.f - dy) * (1.f -dz); atomicAdd(&d_wd[nid + w], mass*ww); atomicAdd(&d_ww[nid + w], ww); } if (isInside3D(xInt+1, yInt+1, zInt+1, w, h, l)){ ww = (1.f -dx) * (1.f - dy) * (1.f -dz); atomicAdd(&d_wd[nid + w + 1], mass*ww); atomicAdd(&d_ww[nid + w + 1], ww); } } #endif }// end namespace Splatting } // end namespace PyCA #endif // __GSPLAT_CUH
the_stack
namespace megdnn { namespace cuda { namespace relayout_format { namespace internal { using namespace memory; struct LayoutType { static constexpr uint32_t NCHWx = 0; static constexpr uint32_t NHWC = 1; }; template < typename Type_, int pack_size_, int chan_blk_, int width_, int size_nbits_, uint32_t layout_type_ = LayoutType::NCHWx> class TensorIteratorOverChannel; template < typename Type_, int pack_size_, int chan_blk_, int width_, int size_nbits_, uint32_t layout_type_> class TensorIteratorOverChannel { public: using Type = Type_; static constexpr int pack_size = pack_size_; static constexpr int chan_blk = chan_blk_; static constexpr int width = width_; static constexpr int size_nbits = size_nbits_; static constexpr int elements_in_type = chan_blk * width * size_nbits / (8 * sizeof(Type)); static constexpr int lane_size_in_type = (width * pack_size * size_nbits) / (8 * sizeof(Type)); static constexpr int pack_size_in_type = (pack_size * size_nbits) >= (8 * sizeof(Type)) ? (pack_size * size_nbits / (8 * sizeof(Type))) : (width * pack_size * size_nbits / (8 * sizeof(Type))); static constexpr int pack_size_in_byte = pack_size_in_type * sizeof(Type); using AccessType = array_wrapper<Type, pack_size_in_type>; using Fragment = array_wrapper<Type, elements_in_type>; MEGDNN_HOST TensorIteratorOverChannel() : pointer{nullptr}, chan_stride_in_elements{0}, channel{0} {} MEGDNN_HOST TensorIteratorOverChannel( Type* pointer_, int chan_stride_in_elements_, int channel_, int, int) : pointer{pointer_}, chan_stride_in_elements{chan_stride_in_elements_}, channel{channel_} {} MEGDNN_DEVICE __forceinline__ void initialize(int c_idx, int hw_idx) { pointer += (c_idx / pack_size) * chan_stride_in_elements + hw_idx * pack_size * size_nbits / (8 * sizeof(Type)); channel -= c_idx; } MEGDNN_DEVICE __forceinline__ void add_pointer_offset(size_t offset_in_type) { pointer += offset_in_type; } MEGDNN_DEVICE __forceinline__ void load(Fragment& frag, int zero_point) { AccessType* frag_ptr = reinterpret_cast<AccessType*>(&frag); Type* pointer_ = pointer; #pragma unroll for (int i = 0; i < chan_blk; i += pack_size) { #pragma unroll for (int j = 0; j < lane_size_in_type / pack_size_in_type; j++) { int frag_idx = i / pack_size * (lane_size_in_type / pack_size_in_type) + j; bool guard = i < channel; global_load<AccessType, pack_size_in_byte>( frag_ptr[frag_idx], reinterpret_cast<void*>(pointer_ + j * pack_size_in_type), guard, zero_point); } pointer_ += chan_stride_in_elements; } } MEGDNN_DEVICE __forceinline__ void store(const Fragment& frag) { const AccessType* frag_ptr = reinterpret_cast<const AccessType*>(&frag); Type* pointer_ = pointer; #pragma unroll for (int i = 0; i < chan_blk; i += pack_size) { #pragma unroll for (int j = 0; j < lane_size_in_type / pack_size_in_type; j++) { int frag_idx = i / pack_size * (lane_size_in_type / pack_size_in_type) + j; bool guard = i < channel; global_store<AccessType, pack_size_in_byte>( frag_ptr[frag_idx], reinterpret_cast<void*>(pointer_ + j * pack_size_in_type), guard); } pointer_ += chan_stride_in_elements; } } MEGDNN_DEVICE __forceinline__ void advance() { pointer += (chan_blk / pack_size) * chan_stride_in_elements; channel -= chan_blk; } private: Type* pointer; int chan_stride_in_elements; int channel; }; template <typename Type_, int pack_size_, int chan_blk_, int width_, int size_nbits_> class TensorIteratorOverChannel< Type_, pack_size_, chan_blk_, width_, size_nbits_, LayoutType::NHWC> { public: using Type = Type_; static constexpr int pack_size = pack_size_; static constexpr int chan_blk = chan_blk_; static constexpr int width = width_; static constexpr int size_nbits = size_nbits_; static constexpr int elements_in_type = chan_blk * width * size_nbits / (8 * sizeof(Type)); static constexpr int pack_size_in_type = pack_size * size_nbits / (8 * sizeof(Type)); static constexpr int pack_size_in_byte = pack_size_in_type * sizeof(Type); using AccessType = array_wrapper<Type, pack_size_in_type>; using Fragment = array_wrapper<Type, elements_in_type>; MEGDNN_HOST TensorIteratorOverChannel() : pointer{nullptr}, hw_stride_in_elements{0}, channel{0} {} MEGDNN_HOST TensorIteratorOverChannel( Type* pointer_, int hw_stride_in_elements_, int channel_, int, int) : pointer{pointer_}, hw_stride_in_elements{hw_stride_in_elements_}, channel{channel_} {} MEGDNN_DEVICE __forceinline__ void initialize(int c_idx, int hw_idx) { pointer += c_idx * size_nbits / (8 * sizeof(Type)) + hw_idx * hw_stride_in_elements; channel -= c_idx; } MEGDNN_DEVICE __forceinline__ void add_pointer_offset(size_t offset_in_type) { pointer += offset_in_type; } MEGDNN_DEVICE __forceinline__ void load(Fragment& frag, int zero_point) { AccessType* frag_ptr = reinterpret_cast<AccessType*>(&frag); Type* pointer_ = pointer; #pragma unroll for (int i = 0; i < width; ++i) { #pragma unroll for (int j = 0; j < chan_blk; j += pack_size) { int frag_idx = i * (chan_blk / pack_size) + (j / pack_size); bool guard = j < channel; global_load<AccessType, pack_size_in_byte>( frag_ptr[frag_idx], reinterpret_cast<void*>( pointer_ + j * size_nbits / (8 * sizeof(Type))), guard, zero_point); } pointer_ += hw_stride_in_elements; } } MEGDNN_DEVICE __forceinline__ void store(const Fragment& frag) { const AccessType* frag_ptr = reinterpret_cast<const AccessType*>(&frag); Type* pointer_ = pointer; #pragma unroll for (int i = 0; i < width; ++i) { #pragma unroll for (int j = 0; j < chan_blk; j += pack_size) { int frag_idx = i * (chan_blk / pack_size) + (j / pack_size); bool guard = j < channel; global_store<AccessType, pack_size_in_byte>( frag_ptr[frag_idx], reinterpret_cast<void*>( pointer_ + j * size_nbits / (8 * sizeof(Type))), guard); } pointer_ += hw_stride_in_elements; } } MEGDNN_DEVICE __forceinline__ void advance() { pointer += chan_blk * size_nbits / (8 * sizeof(Type)); channel -= chan_blk; } private: Type* pointer; int hw_stride_in_elements; int channel; }; template < typename Type_, int pack_size_, int chan_blk_, int width_, int size_nbits_, uint32_t layout_type_ = LayoutType::NCHWx> class MaskedTensorIteratorOverChannel; template < typename Type_, int pack_size_, int chan_blk_, int width_, int size_nbits_, uint32_t layout_type_> class MaskedTensorIteratorOverChannel { public: using Type = Type_; static constexpr int pack_size = pack_size_; static constexpr int chan_blk = chan_blk_; static constexpr int width = width_; static constexpr int size_nbits = size_nbits_; static constexpr int elements_in_type = chan_blk * width * size_nbits / (8 * sizeof(Type)); static constexpr int lane_size_in_type = (width * pack_size * size_nbits) / (8 * sizeof(Type)); static constexpr int pack_size_in_type = (pack_size * size_nbits) >= (8 * sizeof(Type)) ? (pack_size * size_nbits / (8 * sizeof(Type))) : (width * pack_size * size_nbits / (8 * sizeof(Type))); static constexpr int pack_size_in_byte = pack_size_in_type * sizeof(Type); static constexpr int accesses = elements_in_type / pack_size_in_type; static constexpr int mask_size = (accesses + 32 - 1) / 32; using AccessType = array_wrapper<Type, pack_size_in_type>; using Fragment = array_wrapper<Type, elements_in_type>; MEGDNN_HOST MaskedTensorIteratorOverChannel() : pointer{nullptr}, chan_stride_in_elements{0}, channel{0} {} MEGDNN_HOST MaskedTensorIteratorOverChannel( Type* pointer_, int chan_stride_in_elements_, int channel_, int bound_, int div_) : pointer{pointer_}, chan_stride_in_elements{chan_stride_in_elements_}, channel{channel_}, bound{bound_}, div{uint32_t(div_)} {} MEGDNN_DEVICE __forceinline__ void initialize(int c_idx, int hw_idx) { pointer += (c_idx / pack_size) * chan_stride_in_elements; channel -= c_idx; int w[lane_size_in_type / pack_size_in_type]; #pragma unroll for (int i = 0; i < mask_size; ++i) { mask[i] = 0; } #pragma unroll for (int j = 0; j < lane_size_in_type / pack_size_in_type; j++) { int offset = hw_idx + j; int h = (int)((uint32_t)(offset) / div); w[j] = (int)((uint32_t)(offset) % div); stride[j] = (h * bound + w[j]) * pack_size * size_nbits / (8 * sizeof(Type)); } #pragma unroll for (int i = 0; i < chan_blk; i += pack_size) { #pragma unroll for (int j = 0; j < lane_size_in_type / pack_size_in_type; j++) { bool guard = (i < channel) && (w[j] < bound); int index = (i / pack_size) * (lane_size_in_type / pack_size_in_type) + j; int mask_index = (index >> 5); int mask_shift = (index & 0x1f); mask[mask_index] |= (guard << mask_shift); } } } MEGDNN_DEVICE __forceinline__ void add_pointer_offset(size_t offset_in_type) { pointer += offset_in_type; } MEGDNN_DEVICE __forceinline__ void load(Fragment& frag, int zero_point) { AccessType* frag_ptr = reinterpret_cast<AccessType*>(&frag); Type* pointer_ = pointer; #pragma unroll for (int i = 0; i < chan_blk; i += pack_size) { #pragma unroll for (int j = 0; j < lane_size_in_type / pack_size_in_type; j++) { int frag_idx = i / pack_size * (lane_size_in_type / pack_size_in_type) + j; int mask_index = (frag_idx >> 5); int mask_shift = (frag_idx & 0x1f); bool guard = (mask[mask_index] & (1 << mask_shift)); global_load<AccessType, pack_size_in_byte>( frag_ptr[frag_idx], reinterpret_cast<void*>(pointer_ + stride[j]), guard, zero_point); } pointer_ += chan_stride_in_elements; } } MEGDNN_DEVICE __forceinline__ void store(const Fragment& frag) { const AccessType* frag_ptr = reinterpret_cast<const AccessType*>(&frag); Type* pointer_ = pointer; #pragma unroll for (int i = 0; i < chan_blk; i += pack_size) { #pragma unroll for (int j = 0; j < lane_size_in_type / pack_size_in_type; j++) { int frag_idx = i / pack_size * (lane_size_in_type / pack_size_in_type) + j; int mask_index = (frag_idx >> 5); int mask_shift = (frag_idx & 0x1f); bool guard = (mask[mask_index] & (1 << mask_shift)); global_store<AccessType, pack_size_in_byte>( frag_ptr[frag_idx], reinterpret_cast<void*>(pointer_ + stride[j]), guard); } pointer_ += chan_stride_in_elements; } } MEGDNN_DEVICE __forceinline__ void advance() { pointer += (chan_blk / pack_size) * chan_stride_in_elements; channel -= chan_blk; } private: Type* pointer; int chan_stride_in_elements; int channel; int bound; Uint32Fastdiv div; uint32_t mask[mask_size]; size_t stride[lane_size_in_type / pack_size_in_type]; }; template <typename Type_, int pack_size_, int chan_blk_, int width_, int size_nbits_> class MaskedTensorIteratorOverChannel< Type_, pack_size_, chan_blk_, width_, size_nbits_, LayoutType::NHWC> { public: using Type = Type_; static constexpr int pack_size = pack_size_; static constexpr int chan_blk = chan_blk_; static constexpr int width = width_; static constexpr int size_nbits = size_nbits_; static constexpr int elements_in_type = chan_blk * width * size_nbits / (8 * sizeof(Type)); static constexpr int lane_size_in_type = (width * pack_size * size_nbits) / (8 * sizeof(Type)); static constexpr int pack_size_in_type = pack_size * size_nbits / (8 * sizeof(Type)); static constexpr int pack_size_in_byte = pack_size_in_type * sizeof(Type); static constexpr int accesses = elements_in_type / pack_size_in_type; static constexpr int mask_size = (accesses + 32 - 1) / 32; using AccessType = array_wrapper<Type, pack_size_in_type>; using Fragment = array_wrapper<Type, elements_in_type>; MEGDNN_HOST MaskedTensorIteratorOverChannel() : pointer{nullptr}, hw_stride_in_elements{0}, channel{0} {} MEGDNN_HOST MaskedTensorIteratorOverChannel( Type* pointer_, int hw_stride_in_elements_, int channel_, int bound_, int div_) : pointer{pointer_}, hw_stride_in_elements{hw_stride_in_elements_}, channel{channel_}, bound{bound_}, div{uint32_t(div_)} {} MEGDNN_DEVICE __forceinline__ void initialize(int c_idx, int hw_idx) { pointer += c_idx * size_nbits / (8 * sizeof(Type)); channel -= c_idx; #pragma unroll for (int i = 0; i < mask_size; ++i) { mask[i] = 0; } #pragma unroll for (int i = 0; i < width; ++i) { int offset = hw_idx + i; int h = (int)((uint32_t)(offset) / div); int w = (int)((uint32_t)(offset) % div); stride[i] = (h * bound + w) * hw_stride_in_elements; #pragma unroll for (int j = 0; j < chan_blk; j += pack_size) { bool guard = (j < channel) && (w < bound); int index = i * (chan_blk / pack_size) + (j / pack_size); int mask_index = (index >> 5); int mask_shift = (index & 0x1f); mask[mask_index] |= (guard << mask_shift); } } } MEGDNN_DEVICE __forceinline__ void add_pointer_offset(size_t offset_in_type) { pointer += offset_in_type; } MEGDNN_DEVICE __forceinline__ void load(Fragment& frag, int zero_point) { AccessType* frag_ptr = reinterpret_cast<AccessType*>(&frag); #pragma unroll for (int i = 0; i < width; ++i) { Type* pointer_ = pointer + stride[i]; #pragma unroll for (int j = 0; j < chan_blk; j += pack_size) { int frag_idx = i * (chan_blk / pack_size) + (j / pack_size); int mask_index = (frag_idx >> 5); int mask_shift = (frag_idx & 0x1f); bool guard = (mask[mask_index] & (1 << mask_shift)); global_load<AccessType, pack_size_in_byte>( frag_ptr[frag_idx], reinterpret_cast<void*>( pointer_ + j * size_nbits / (8 * sizeof(Type))), guard, zero_point); } } } MEGDNN_DEVICE __forceinline__ void store(const Fragment& frag) { const AccessType* frag_ptr = reinterpret_cast<const AccessType*>(&frag); #pragma unroll for (int i = 0; i < width; ++i) { Type* pointer_ = pointer + stride[i]; #pragma unroll for (int j = 0; j < chan_blk; j += pack_size) { int frag_idx = i * (chan_blk / pack_size) + (j / pack_size); int mask_index = (frag_idx >> 5); int mask_shift = (frag_idx & 0x1f); bool guard = (mask[mask_index] & (1 << mask_shift)); global_store<AccessType, pack_size_in_byte>( frag_ptr[frag_idx], reinterpret_cast<void*>( pointer_ + j * size_nbits / (8 * sizeof(Type))), guard); } } } MEGDNN_DEVICE __forceinline__ void advance() { pointer += chan_blk * size_nbits / (8 * sizeof(Type)); channel -= chan_blk; } private: Type* pointer; int hw_stride_in_elements; int channel; int bound; Uint32Fastdiv div; uint32_t mask[mask_size]; size_t stride[width]; }; template < bool padding_, typename Type_, int pack_size_, int chan_blk_, int width_, int size_nbits_, uint32_t layout_type_ = LayoutType::NCHWx> struct TensorIteratorPolicy; template < typename Type_, int pack_size_, int chan_blk_, int width_, int size_nbits_, uint32_t layout_type_> struct TensorIteratorPolicy< true, Type_, pack_size_, chan_blk_, width_, size_nbits_, layout_type_> { using TensorIterator = MaskedTensorIteratorOverChannel< Type_, pack_size_, chan_blk_, width_, size_nbits_, layout_type_>; }; template < typename Type_, int pack_size_, int chan_blk_, int width_, int size_nbits_, uint32_t layout_type_> struct TensorIteratorPolicy< false, Type_, pack_size_, chan_blk_, width_, size_nbits_, layout_type_> { using TensorIterator = TensorIteratorOverChannel< Type_, pack_size_, chan_blk_, width_, size_nbits_, layout_type_>; }; template < typename SrcIterator_, typename DstIterator_, typename Transpose_, typename CudaPostProcess_> struct RelayoutProblem { using SrcIterator = SrcIterator_; using DstIterator = DstIterator_; using Transpose = Transpose_; using CudaPostProcess = CudaPostProcess_; MEGDNN_STATIC_ASSERT( SrcIterator::chan_blk == DstIterator::chan_blk, "channel block mismatch"); MEGDNN_STATIC_ASSERT( SrcIterator::width == DstIterator::width, "width block mismatch"); MEGDNN_STATIC_ASSERT( SrcIterator::size_nbits == DstIterator::size_nbits, "size in bits of elements mismatch"); static constexpr int pack_chan = SrcIterator::chan_blk; static constexpr int pack_width = SrcIterator::width; using DnnSrcType = typename CudaPostProcess::SrcType; using DnnDstType = typename CudaPostProcess::DstType; struct Param { SrcIterator src_iterator; DstIterator dst_iterator; CudaPostProcess post_process; int n_stride_src; int n_stride_dst; int batch_size; int channels; int hw; int zero_point; MEGDNN_HOST MEGDNN_DEVICE Param(SrcIterator src_iterator_, DstIterator dst_iterator_, CudaPostProcess post_process_, int n_stride_src_, int n_stride_dst_, int batch_size_, int channels_, int hw_, int zero_point_) : src_iterator{src_iterator_}, dst_iterator{dst_iterator_}, post_process{post_process_}, n_stride_src{n_stride_src_}, n_stride_dst{n_stride_dst_}, batch_size{batch_size_}, channels{channels_}, hw{hw_}, zero_point{zero_point_} {} }; }; template <typename RelayoutProblem_> __global__ void relayout_kern(typename RelayoutProblem_::Param param) { using SrcIterator = typename RelayoutProblem_::SrcIterator; using DstIterator = typename RelayoutProblem_::DstIterator; static constexpr int pack_chan = RelayoutProblem_::pack_chan; static constexpr int pack_width = RelayoutProblem_::pack_width; const int thread_idx = blockIdx.x * blockDim.x + threadIdx.x; const int thread_offset = thread_idx * pack_width; const int hw_idx = (thread_offset % param.hw); const int nc_blks = thread_offset / param.hw; const int c_blks = (param.channels + pack_chan - 1) / pack_chan; const int n_idx = nc_blks / c_blks; const int c_blk_idx = nc_blks % c_blks; const int c_idx = c_blk_idx * pack_chan; if (n_idx < param.batch_size) { const int src_offset = n_idx * param.n_stride_src; const int dst_offset = n_idx * param.n_stride_dst; param.src_iterator.add_pointer_offset(src_offset); param.dst_iterator.add_pointer_offset(dst_offset); param.src_iterator.initialize(c_idx, hw_idx); param.dst_iterator.initialize(c_idx, hw_idx); typename SrcIterator::Fragment src_frag; typename DstIterator::Fragment dst_frag; int zp = make_zero<SrcIterator::size_nbits>(param.zero_point); param.src_iterator.load(src_frag, zp); RelayoutProblem_::Transpose::trans( reinterpret_cast<typename SrcIterator::Fragment&>(dst_frag), src_frag, param.post_process); param.dst_iterator.store(dst_frag); } } } // namespace internal } // namespace relayout_format } // namespace cuda } // namespace megdnn
the_stack
#include "deviceCode.h" #include "constants.h" #include <optix_device.h> #include <owl/common/math/random.h> #include <owl/common/math/LinearSpace.h> __constant__ LaunchParams optixLaunchParams; typedef owl::common::LCG<4> Random; typedef owl::RayT<0, 3> RadianceRay; typedef owl::RayT<1, 3> ShadowRay; typedef owl::RayT<2, 3> OutlineShadowRay; inline __device__ vec3f missColor(const RadianceRay &ray) { const vec2i pixelID = owl::getLaunchIndex(); const vec3f rayDir = normalize(ray.direction); const float t = 0.5f*(rayDir.y + 1.0f); const vec3f c = (1.0f - t)*vec3f(1.0f, 1.0f, 1.0f) + t * vec3f(0.5f, 0.7f, 1.0f); return c; } OPTIX_MISS_PROGRAM(miss)() { /* nothing to do */ } OPTIX_MISS_PROGRAM(miss_shadow)() { float &vis = owl::getPRD<float>(); vis = 1.f; } typedef enum { /*! ray could get properly bounced, and is still alive */ rayGotBounced, /*! ray didn't hit anything, and went into the environment */ rayDidntHitAnything } ScatterEvent; struct PerRayData { Random random; struct { ScatterEvent scatterEvent; vec3f scattered_origin; vec3f scattered_direction; vec3f attenuation; vec3f directLight; float hitDistance; } out; }; template <typename RayT, int Mask> inline __device__ RayT makeRay(const vec3f &origin, const vec3f &direction, float tmin, float tmax) { if (optixLaunchParams.enableClipping) { const float eps = 0.01f * optixLaunchParams.brickScale; const float clipZ = optixLaunchParams.clipHeight * optixLaunchParams.brickScale; const float t = (clipZ - origin.z) / direction.z; if (direction.z < 0.f) { tmin = owl::max(tmin, t-eps); } else { tmax = owl::min(tmax, t+eps); } } return RayT(origin, direction, tmin, tmax, Mask); } inline __device__ RadianceRay makeRadianceRay(const vec3f &origin, const vec3f &direction, float tmin, float tmax) { return makeRay<RadianceRay, VISIBILITY_RADIANCE>(origin, direction, tmin, tmax); } inline __device__ ShadowRay makeShadowRay(const vec3f &origin, const vec3f &direction, float tmin, float tmax) { return makeRay<ShadowRay, VISIBILITY_SHADOW>(origin, direction, tmin, tmax); } inline __device__ OutlineShadowRay makeOutlineShadowRay(const vec3f &origin, const vec3f &direction, float tmin, float tmax) { return makeRay<OutlineShadowRay, VISIBILITY_OUTLINE>(origin, direction, tmin, tmax); } inline __device__ vec3f tracePrimaryRay(const RayGenData &self, RadianceRay &ray, PerRayData &prd) { if (optixLaunchParams.enableToonOutline) { prd.out.hitDistance = 1e10f; } prd.out.scatterEvent = rayDidntHitAnything; owl::traceRay(optixLaunchParams.world, ray, prd, OPTIX_RAY_FLAG_CULL_BACK_FACING_TRIANGLES); if (prd.out.scatterEvent == rayDidntHitAnything) { return missColor(ray); } else { // ray is still alive, and got properly bounced ray = makeRadianceRay(prd.out.scattered_origin, prd.out.scattered_direction, 0.f, // rely on hitP offset along normal 1e10f); } return prd.out.directLight; } inline __device__ vec3f traceBounces(const RayGenData &self, RadianceRay &ray, PerRayData &prd) { vec3f attenuation = prd.out.attenuation; vec3f directLight = 0.f; constexpr int MaxDepth = 2; /* iterative version of recursion, up to max depth */ for (int depth=1;depth<MaxDepth;depth++) { prd.out.scatterEvent = rayDidntHitAnything; owl::traceRay(/*accel to trace against*/ optixLaunchParams.world, /*the ray to trace*/ ray, /*prd*/prd, OPTIX_RAY_FLAG_CULL_BACK_FACING_TRIANGLES); if (prd.out.scatterEvent == rayDidntHitAnything) /* ray got 'lost' to the environment - 'light' it with miss shader */ return directLight + attenuation * missColor(ray); else { // ray is still alive, and got properly bounced attenuation *= prd.out.attenuation; directLight += prd.out.directLight; ray = makeRadianceRay(/* origin : */ prd.out.scattered_origin, /* direction: */ prd.out.scattered_direction, /* tmin : */ 0.f, // rely on hitP offset along normal /* tmax : */ 1e10f); } } // recursion did not terminate - cancel it but return direct lighting from any previous bounce return directLight; } // returns a visibility term (1 for unshadowed) inline __device__ float traceShadowRay(const OptixTraversableHandle &traversable, ShadowRay &ray) { float vis = 0.f; owl::traceRay(traversable, ray, vis, OPTIX_RAY_FLAG_DISABLE_ANYHIT | OPTIX_RAY_FLAG_TERMINATE_ON_FIRST_HIT | OPTIX_RAY_FLAG_DISABLE_CLOSESTHIT); return vis; } // returns a visibility term (1 for unshadowed) inline __device__ float traceOutlineShadowRay(const OptixTraversableHandle &traversable, OutlineShadowRay &ray) { float vis = 0.f; owl::traceRay(traversable, ray, vis, OPTIX_RAY_FLAG_DISABLE_ANYHIT | OPTIX_RAY_FLAG_CULL_FRONT_FACING_TRIANGLES | OPTIX_RAY_FLAG_TERMINATE_ON_FIRST_HIT | OPTIX_RAY_FLAG_DISABLE_CLOSESTHIT); return vis; } OPTIX_RAYGEN_PROGRAM(simpleRayGen)() { const RayGenData &self = owl::getProgramData<RayGenData>(); const vec2i pixelID = owl::getLaunchIndex(); const vec2i fbSize = optixLaunchParams.fbSize; const int fbIndex = pixelID.x+fbSize.x*pixelID.y; PerRayData prd; prd.random.init(fbIndex, optixLaunchParams.frameID); // Note: measured to be faster to keep the loop over subpixels at the launch level, // not inside raygen. Maybe a long tail effect? constexpr int NUM_SAMPLES_PER_PIXEL = 1; vec3f accumColor = 0.f; for (int sampleID=0;sampleID<NUM_SAMPLES_PER_PIXEL;sampleID++) { const vec2f pixelSample(prd.random(), prd.random()); const vec2f screen = (vec2f(pixelID)+pixelSample) / vec2f(fbSize); const vec3f rayDir = normalize(self.camera.dir_00 + screen.u * self.camera.dir_du + screen.v * self.camera.dir_dv); RadianceRay ray = makeRadianceRay(self.camera.pos, rayDir, 0.f, 1e30f); vec3f color = tracePrimaryRay(self, ray, prd); float visibility = 1.f; if (optixLaunchParams.enableToonOutline) { // Feature size control for outlines const float outlineDepthBias = 5*optixLaunchParams.brickScale; const float firstHitDistance = prd.out.hitDistance; // Note: dependency on primary ray OutlineShadowRay outlineShadowRay = makeOutlineShadowRay(self.camera.pos, rayDir, 0.f, firstHitDistance-outlineDepthBias); visibility = traceOutlineShadowRay(optixLaunchParams.world, outlineShadowRay); } // Note: measurable speedup from tracing bounce rays unconditionally without // checking visibility first. if (prd.out.scatterEvent == rayGotBounced) { color += traceBounces(self, ray, prd); } accumColor += color*visibility; } vec4f rgba {accumColor / NUM_SAMPLES_PER_PIXEL, 1.0f}; if (optixLaunchParams.frameID > 0) { // Blend with accum buffer const vec4f accum = optixLaunchParams.fbAccumBuffer[fbIndex]; rgba += float(optixLaunchParams.frameID) * accum; rgba /= (optixLaunchParams.frameID+1.f); } optixLaunchParams.fbAccumBuffer[fbIndex] = (float4)rgba; optixLaunchParams.fbPtr[fbIndex] = owl::make_rgba(rgba); } inline __device__ float2 squareToDisk(float u1, float u2) { // Uniformly sample disk. const float r = sqrtf( u1 ); const float phi = 2.0f*M_PIf * u2; float2 p = {r * cosf( phi ), r * sinf( phi )}; return p; } inline __device__ vec3f cosineSampleHemisphere(float u1, float u2) { float2 p = squareToDisk(u1, u2); // Project up to hemisphere. return vec3f(p.x, p.y, sqrtf( fmaxf( 0.0f, 1.0f - p.x*p.x - p.y*p.y ) )); } inline __device__ vec3f sunlight(const vec3f &hit_P_offset, const vec3f &Ng, Random &random) { const vec3f lightDir = optixLaunchParams.sunDirection; const float NdotL = dot(Ng, lightDir); if (NdotL <= 0.f) { return 0.f; // below horizon } // Build frame around light dir const owl::LinearSpace3f lightFrame = owl::common::frame(normalize(lightDir)); // jitter light direction slightly const float lightRadius = 0.01f; // should be ok as a constant since our scenes are normalized const vec3f lightCenter = hit_P_offset + lightFrame.vz; const float2 sample = squareToDisk(random(), random()); const vec3f jitteredPos = lightCenter + lightRadius*(sample.x*lightFrame.vx + sample.y*lightFrame.vy); const vec3f jitteredLightDir = jitteredPos - hit_P_offset; // no need to normalize ShadowRay shadowRay = makeShadowRay(hit_P_offset, jitteredLightDir, 0.f, 1e10f); float vis = traceShadowRay(optixLaunchParams.world, shadowRay); return vis * optixLaunchParams.sunColor * NdotL; } inline __device__ vec3f scatterLambertian(const vec3f &Ng, Random &random) { const owl::LinearSpace3f shadingFrame = owl::common::frame(Ng); vec3f scatteredDirectionInShadingFrame = cosineSampleHemisphere(random(), random()); vec3f scatteredDirection = shadingFrame.vx * scatteredDirectionInShadingFrame.x + shadingFrame.vy * scatteredDirectionInShadingFrame.y + shadingFrame.vz * scatteredDirectionInShadingFrame.z; return scatteredDirection; } // Common reflectance function for all geometry inline __device__ void shade(const vec3f &Ng, const vec3f &color) { PerRayData &prd = owl::getPRD<PerRayData>(); const vec3f dir = optixGetWorldRayDirection(); const vec3f org = optixGetWorldRayOrigin(); const float hit_t = optixGetRayTmax(); const vec3f hit_P = org + hit_t * dir; const float shadowBias = 0.01f * fminf(1.f, optixLaunchParams.brickScale); const vec3f hit_P_offset = hit_P + shadowBias*Ng; // bias along normal to help with shadow acne // Direct const vec3f directLight = sunlight(hit_P_offset, Ng, prd.random); // Bounce vec3f scatteredDirection = scatterLambertian(Ng, prd.random); prd.out.directLight = directLight*color; prd.out.attenuation = color; prd.out.scatterEvent = rayGotBounced; prd.out.scattered_direction = scatteredDirection; prd.out.scattered_origin = hit_P_offset; if (optixLaunchParams.enableToonOutline) { prd.out.hitDistance = length(hit_P - org); } } inline __device__ void shadeTriangleOnBrick(unsigned int brickID) { const TrianglesGeomData &self = owl::getProgramData<TrianglesGeomData>(); // Compute normal for triangle const int primID = optixGetPrimitiveIndex(); const vec3i index = self.index[primID]; const vec3f &A = self.vertex[index.x]; const vec3f &B = self.vertex[index.y]; const vec3f &C = self.vertex[index.z]; const vec3f Nbox = normalize(cross(B-A,C-A)); const vec3f Ng = normalize(vec3f(optixTransformNormalFromObjectToWorldSpace(Nbox))); // Get brick color const int ci = self.colorIndexPerBrick[brickID]; uchar4 col = self.colorPalette[ci]; const vec3f color = vec3f(col.x, col.y, col.z) * (1.0f/255.0f); shade(Ng, color); } OPTIX_CLOSEST_HIT_PROGRAM(TriangleMesh)() { const TrianglesGeomData &self = owl::getProgramData<TrianglesGeomData>(); unsigned int brickID = optixGetPrimitiveIndex() / self.primCountPerBrick; shadeTriangleOnBrick(brickID); } OPTIX_CLOSEST_HIT_PROGRAM(InstancedTriangleMesh)() { unsigned int brickID = optixGetInstanceId(); shadeTriangleOnBrick(brickID); } OPTIX_BOUNDS_PROGRAM(VoxGeom)(const void *geomData, box3f &primBounds, const int primID) { const VoxGeomData &self = *(const VoxGeomData*)geomData; uchar4 indices = self.prims[primID]; vec3f boxmin( indices.x, indices.y, indices.z ); vec3f boxmax( 1+indices.x, 1+indices.y, 1+indices.z ); if (self.enableToonOutline) { // bloat the box slightly const vec3f boxcenter (indices.x + 0.5f, indices.y + 0.5f, indices.z + 0.5f); boxmin = boxcenter + OUTLINE_SCALE*(boxmin-boxcenter); boxmax = boxcenter + OUTLINE_SCALE*(boxmax-boxcenter); } primBounds = box3f(boxmin, boxmax); } namespace { // temp swizzles inline __device__ vec2f yz(vec3f v) { return vec2f(v.y, v.z); } inline __device__ vec2f zx(vec3f v) { return vec2f(v.z, v.x); } inline __device__ vec2f xy(vec3f v) { return vec2f(v.x, v.y); } inline __device__ vec3f yzx(vec3f v) { return vec3f(v.y, v.z, v.x); } inline __device__ vec3i zxy(vec3i v) { return vec3i(v.z, v.x, v.y); } } // Ray-box intersection with normals from Majercik et al 2018 OPTIX_INTERSECT_PROGRAM(VoxGeomMajercik)() { // convert indices to 3d box const int primID = optixGetPrimitiveIndex(); const VoxGeomData &self = owl::getProgramData<VoxGeomData>(); uchar4 indices = self.prims[primID]; vec3f boxCenter(indices.x+0.5, indices.y+0.5, indices.z+0.5); // Translate ray to local box space const vec3f rayOrigin = vec3f(optixGetObjectRayOrigin()) - boxCenter; const vec3f rayDirection = optixGetObjectRayDirection(); // assume no rotation const vec3f invRayDirection = vec3f(1.0f) / rayDirection; // Negated sign function const vec3f sgn( rayDirection.x > 0.f ? -1 : 1, rayDirection.y > 0.f ? -1 : 1, rayDirection.z > 0.f ? -1 : 1); const vec3f boxRadius(0.5f, 0.5f, 0.5f); vec3f distanceToPlane = boxRadius*sgn - rayOrigin; distanceToPlane *= invRayDirection; const bool testX = distanceToPlane.x >= 0.f && owl::all_less_than(owl::abs(yz(rayOrigin) + yz(rayDirection)*distanceToPlane.x), yz(boxRadius)); const bool testY = distanceToPlane.y >= 0.f && owl::all_less_than(owl::abs(zx(rayOrigin) + zx(rayDirection)*distanceToPlane.y), zx(boxRadius)); const bool testZ = distanceToPlane.z >= 0.f && owl::all_less_than(owl::abs(xy(rayOrigin) + xy(rayDirection)*distanceToPlane.z), xy(boxRadius)); const vec3b test(testX, testY, testZ); if ( test.x || test.y || test.z ) { // hit the box float distance = test.x ? distanceToPlane.x : (test.y ? distanceToPlane.y : distanceToPlane.z); const float ray_tmax = optixGetRayTmax(); const float ray_tmin = optixGetRayTmin(); if (distance > ray_tmin && distance < ray_tmax) { // closer than existing hit // Since N is something like [0,-1,0], encode it as sign (1 bit) and 3 components (3 bits): 000...SNNN // This lets it fit in one attribute. int signOfN = (sgn.x*test.x + sgn.y*test.y + sgn.z*test.z) > 0 ? 1 : 0; int packedN = (signOfN << 3) | (test.z << 2) | (test.y << 1) | test.x; optixReportIntersection(distance, 0, packedN); } } } // Use the "efficient slabs" method for shadow rays where we don't need normals. template <bool IsOutline> inline __device__ void intersectVoxGeomShadow() { const VoxGeomData &self = owl::getProgramData<VoxGeomData>(); // Per-brick outline control if (IsOutline && !self.enableToonOutline) { return; } // convert indices to 3d box const int primID = optixGetPrimitiveIndex(); uchar4 indices = self.prims[primID]; vec3f boxCenter(indices.x+0.5, indices.y+0.5, indices.z+0.5); // Translate ray to local box space const vec3f rayOrigin = vec3f(optixGetObjectRayOrigin()) - boxCenter; const vec3f rayDirection = optixGetObjectRayDirection(); // assume no rotation const vec3f invRayDirection = vec3f(1.0f) / rayDirection; const float ray_tmax = optixGetRayTmax(); const float ray_tmin = optixGetRayTmin(); constexpr float radius = IsOutline ? 0.5f*OUTLINE_SCALE : 0.5f; const vec3f boxRadius(radius, radius, radius); vec3f t0 = (-boxRadius - rayOrigin) * invRayDirection; vec3f t1 = ( boxRadius - rayOrigin) * invRayDirection; float tnear = reduce_max(owl::min(t0, t1)); float tfar = reduce_min(owl::max(t0, t1)); float distance = IsOutline ? tfar : (tnear > 0.f ? tnear : tfar); if (tnear <= tfar && distance > ray_tmin && distance < ray_tmax) { optixReportIntersection( distance, 0); } } OPTIX_INTERSECT_PROGRAM(VoxGeomShadow)() { return intersectVoxGeomShadow</*IsOutline=*/ false>(); } OPTIX_INTERSECT_PROGRAM(VoxGeomOutlineShadow)() { return intersectVoxGeomShadow</*IsOutline=*/ true>(); } inline __device__ vec3f unpackNormal(int packedN) { const int sgnN = (packedN >> 3) ? 1 : -1; const float3 Nbox = make_float3( sgnN * ( packedN & 1), sgnN * ((packedN >> 1) & 1), sgnN * ((packedN >> 2) & 1)); return Nbox; } OPTIX_CLOSEST_HIT_PROGRAM(VoxGeom)() { // Get normal for whichever face we hit const int packedN = optixGetAttribute_0(); const vec3f Nbox = unpackNormal(packedN); const vec3f Ng = normalize(vec3f(optixTransformNormalFromObjectToWorldSpace(Nbox))); // Get brick color const int primID = optixGetPrimitiveIndex(); const VoxGeomData &self = owl::getProgramData<VoxGeomData>(); const int ci = self.prims[primID].w; uchar4 col = self.colorPalette[ci]; const vec3f color = vec3f(col.x, col.y, col.z) * (1.0f/255.0f); shade(Ng, color); } // Experiment with "blocks" (small grids) of bricks OPTIX_BOUNDS_PROGRAM(VoxBlockGeom)(const void *geomData, box3f &primBounds, const int primID) { const VoxBlockGeomData &self = *(const VoxBlockGeomData*)geomData; uchar3 indices = self.prims[primID]; vec3f boxmin( indices.x, indices.y, indices.z ); vec3f boxmax = boxmin + vec3f(BLOCKLEN); // Not obvious how to do toon outline for blocks /* if (self.enableToonOutline) { ... } */ primBounds = box3f(boxmin, boxmax); } __device__ inline bool intersectRayBox(const vec3f _rayOrigin, const vec3f rayDirection, vec3f boxCenter, vec3f boxRadius, float &tnear, float &tfar, vec3i &axismask) { // Translate ray to local box space const vec3f rayOrigin = _rayOrigin - boxCenter; const vec3f invRayDirection = vec3f(1.0f) / rayDirection; vec3f t0 = (-boxRadius - rayOrigin) * invRayDirection; vec3f t1 = ( boxRadius - rayOrigin) * invRayDirection; vec3f tnearPerAxis = owl::min(t0, t1); tnear = reduce_max(tnearPerAxis); tfar = reduce_min(owl::max(t0, t1)); axismask = vec3i(owl::ge(tnearPerAxis, vec3f(tnear))); return tnear <= tfar; } template <bool IsShadowRay> inline __device__ void intersectVoxBlockGeom() { // convert indices to 3d box const int primID = optixGetPrimitiveIndex(); const VoxBlockGeomData &self = owl::getProgramData<VoxBlockGeomData>(); const uchar3 blockOrigin = self.prims[primID]; const vec3f blockRadius(0.5f*BLOCKLEN); const vec3f blockCenter = vec3f(blockOrigin.x, blockOrigin.y, blockOrigin.z) + blockRadius; const vec3f rayOrigin = optixGetObjectRayOrigin(); const vec3f rayDirection = optixGetObjectRayDirection(); const float rayTmin = optixGetRayTmin(); const float rayTmax = optixGetRayTmax(); const vec3f blockOrigin3f(blockOrigin.x, blockOrigin.y, blockOrigin.z); // Intersect ray with block float tnear; // initial t as ray enters block, updated during DDA vec3i axismask(0); // initial axis mask (==abs(N)), updated during DDA float tfar; if (!intersectRayBox(rayOrigin, rayDirection, blockCenter, blockRadius, tnear, tfar, axismask)) { return; // Ray line misses block (without considering ray span) } tnear = max(tnear, rayTmin); tfar = min(tfar, rayTmax); if (tnear > tfar) return; // Set up DDA for the block grid // Constants during traversal const vec3i blockDim(BLOCKLEN); const vec3f sgn( rayDirection.x > 0.f ? 1 : -1, rayDirection.y > 0.f ? 1 : -1, rayDirection.z > 0.f ? 1 : -1); const vec3f invRayDirection = vec3f(1.0f) / rayDirection; const vec3f deltaT = sgn * invRayDirection; const vec3i step (sgn.x, sgn.y, sgn.z); const vec3i exitCell ( sgn.x < 0 ? -1 : blockDim.x, sgn.y < 0 ? -1 : blockDim.y, sgn.z < 0 ? -1 : blockDim.z); const int brickOffset = primID*blockDim.x*blockDim.y*blockDim.z; // Things that change during traversal // Current cell in grid const vec3f pos = rayOrigin + tnear*rayDirection - blockOrigin3f; vec3i cell = owl::clamp(vec3i(pos), vec3i(0), blockDim-vec3i(1)); // T values where the ray crosses into the next "slab" along the x,y,z axes // Version from: https://www.shadertoy.com/view/MdBGRm const vec3f corner = owl::max(sgn, vec3f(0.f)); vec3f nextCrossingT = vec3f(tnear) + (vec3f(cell.x, cell.y, cell.z) + corner - pos) * invRayDirection; // Color at entry cell, provided the ray started outside the block. Updated during DDA. // Note: we ignore the case where a ray starts inside an opaque cell (probably due to shadow bias). int brickIdx = brickOffset + cell.x + cell.y*blockDim.x + cell.z*blockDim.x*blockDim.y; int colorIdx = tnear > rayTmin ? self.colorIndices[brickIdx] : -1; // DDA traversal // Note: profiling shows small gain from using a fixed size loop here even though we always break. // Theoretical length of diagonal: blocklen*sqrt(3). Had to increase this empirically. constexpr int MaxNumSteps = BLOCKLEN*3; for (int i = 0; i < MaxNumSteps; ++i) { if (colorIdx > 0) { // previous t-crossing is the intersection t const vec3f ct = nextCrossingT - deltaT; tnear = owl::reduce_max(ct); //if (tnear >= rayTmax) break; // Can be skipped for our scenes. if (IsShadowRay) { optixReportIntersection(tnear, 0); } else { int signOfNormal = owl::any(owl::lt(sgn*vec3f(axismask), vec3f(0.f))); int packedNormal = (signOfNormal << 3) | (axismask.z << 2) | (axismask.y << 1) | axismask.x; optixReportIntersection(tnear, 0, packedNormal, colorIdx); } break; } // Advance to next cell along ray // Version from: https://www.shadertoy.com/view/MdBGRm vec3i cp = vec3i(owl::lt(nextCrossingT, yzx(nextCrossingT))); axismask = cp * (vec3i(1) - zxy(cp)); cell += step * axismask; if (cell*axismask == exitCell*axismask) { break; } nextCrossingT += deltaT*vec3f(axismask); brickIdx = brickOffset + cell.x + cell.y*blockDim.x + cell.z*blockDim.x*blockDim.y; colorIdx = self.colorIndices[brickIdx]; } } OPTIX_INTERSECT_PROGRAM(VoxBlockGeom)() { intersectVoxBlockGeom</*IsShadow=*/ false>(); } OPTIX_INTERSECT_PROGRAM(VoxBlockGeomShadow)() { intersectVoxBlockGeom</*IsShadow=*/ true>(); } OPTIX_CLOSEST_HIT_PROGRAM(VoxBlockGeom)() { // Get normal for whichever face we hit const int packedN = optixGetAttribute_0(); const vec3f Nbox = unpackNormal(packedN); const vec3f Ng = normalize(vec3f(optixTransformNormalFromObjectToWorldSpace(Nbox))); // Get brick color const VoxBlockGeomData &self = owl::getProgramData<VoxBlockGeomData>(); const int ci = optixGetAttribute_1(); uchar4 col = self.colorPalette[ci]; const vec3f color = vec3f(col.x, col.y, col.z) * (1.0f/255.0f); shade(Ng, color); }
the_stack
#define SEP printf("-----------------------------------------------------------\n") void gendata(float *ax,float *ay,float *az, float *gx,float *gy,float *gz, float *charge,float *size,int natom,int ngrid) { int i; printf("Generating Data.. \n"); for (i=0; i<natom; i++) { ax[i] = ((float) rand() / (float) RAND_MAX); ay[i] = ((float) rand() / (float) RAND_MAX); az[i] = ((float) rand() / (float) RAND_MAX); charge[i] = ((float) rand() / (float) RAND_MAX); size[i] = ((float) rand() / (float) RAND_MAX); } for (i=0; i<ngrid; i++) { gx[i] = ((float) rand() / (float) RAND_MAX); gy[i] = ((float) rand() / (float) RAND_MAX); gz[i] = ((float) rand() / (float) RAND_MAX); } printf("Done generating inputs.\n\n"); } void print_total(float * arr, int ngrid){ int i; double accum = 0.0; for (i=0; i<ngrid; i++){ accum += arr[i]; } printf("Accumulated value: %1.7g\n",accum); } __global__ void mdh ( const int ngrid, const int natom, const int ngadj, const float *ax, const float *ay, const float *az, const float *gx, const float *gy, const float *gz, const float *charge, const float *size, const float xkappa, const float pre1, float *val) { extern __shared__ float shared[]; int lid = threadIdx.x; int lsize = blockDim.x; int igrid = blockIdx.x * lsize + lid; float4 v = make_float4(0.0f); float4 lgx = reinterpret_cast<const float4*>(gx)[igrid]; float4 lgy = reinterpret_cast<const float4*>(gy)[igrid]; float4 lgz = reinterpret_cast<const float4*>(gz)[igrid]; for(int jatom = 0; jatom < natom; jatom+=lsize ) { if((jatom+lsize) > natom) lsize = natom - jatom; if((jatom + lid) < natom) { shared[lid * 5 ] = ax[jatom + lid]; shared[lid * 5 + 1] = ay[jatom + lid]; shared[lid * 5 + 2] = az[jatom + lid]; shared[lid * 5 + 3] = charge[jatom + lid]; shared[lid * 5 + 4] = size[jatom + lid]; } __syncthreads(); for(int i=0; i<lsize; i++) { float4 dx = lgx - shared[i * 5 ]; float4 dy = lgy - shared[i * 5 + 1]; float4 dz = lgz - shared[i * 5 + 2]; float4 dist = sqrtf(dx*dx + dy*dy + dz*dz); v += pre1 * (shared[i * 5 + 3] / dist) * expf( -xkappa * (dist - shared[i * 5 + 4])) / (1.0f + xkappa * shared[i * 5 + 4]); } __syncthreads(); } reinterpret_cast<float4*>(val)[ igrid ] = v; } __global__ void mdh2 ( const int ngrid, const int natom, const int ngadj, const float *ax, const float *ay, const float *az, const float *gx, const float *gy, const float *gz, const float *charge, const float *size, const float xkappa, const float pre1, float *val) { extern __shared__ float shared[]; int lid = threadIdx.x; int lsize = blockDim.x; int igrid = blockIdx.x * lsize + lid; float4 v = make_float4(0.0f); float4 lgx = reinterpret_cast<const float4*>(gx)[igrid]; float4 lgy = reinterpret_cast<const float4*>(gy)[igrid]; float4 lgz = reinterpret_cast<const float4*>(gz)[igrid]; for(int jatom = 0; jatom < natom; jatom+=lsize ) { if((jatom+lsize) > natom) lsize = natom - jatom; if((jatom + lid) < natom) { shared[lid ] = ax[jatom + lid]; shared[lid + lsize] = ay[jatom + lid]; shared[lid + 2*lsize] = az[jatom + lid]; shared[lid + 3*lsize] = charge[jatom + lid]; shared[lid + 4*lsize] = size[jatom + lid]; } __syncthreads(); for(int i=0; i<lsize; i++) { float4 dx = lgx - shared[i ]; float4 dy = lgy - shared[i + lsize]; float4 dz = lgz - shared[i + 2*lsize]; float4 dist = sqrtf( dx * dx + dy * dy + dz * dz ); v += pre1 * ( shared[i + 3*lsize] / dist ) * expf( -xkappa * (dist - shared[i + 4*lsize])) / (1.0f + xkappa * shared[i + 4*lsize]); } __syncthreads(); } reinterpret_cast<float4*>(val)[ igrid ] = v; } void run_gpu_kernel( const bool smem_strided_write, const int wgsize, const int itmax, const int ngrid, const int natom, const int ngadj, const float *ax, const float *ay, const float *az, const float *gx, const float *gy, const float *gz, const float *charge, const float *size, const float xkappa, const float pre1, float *val) { wkf_timerhandle timer = wkf_timer_create(); //Allocate memory for programs and kernels float* d_ax; cudaMalloc((void**)&d_ax, sizeof(float)*natom); cudaMemcpy(d_ax, ax, sizeof(float)*natom, cudaMemcpyHostToDevice); float* d_ay; cudaMalloc((void**)&d_ay, sizeof(float)*natom); cudaMemcpy(d_ay, ay, sizeof(float)*natom, cudaMemcpyHostToDevice); float* d_az; cudaMalloc((void**)&d_az, sizeof(float)*natom); cudaMemcpy(d_az, az, sizeof(float)*natom, cudaMemcpyHostToDevice); float* d_charge; cudaMalloc((void**)&d_charge, sizeof(float)*natom); cudaMemcpy(d_charge, charge, sizeof(float)*natom, cudaMemcpyHostToDevice); float* d_size; cudaMalloc((void**)&d_size, sizeof(float)*natom); cudaMemcpy(d_size, size, sizeof(float)*natom, cudaMemcpyHostToDevice); float* d_gx; cudaMalloc((void**)&d_gx, sizeof(float)*ngadj); cudaMemcpy(d_gx, gx, sizeof(float)*ngadj, cudaMemcpyHostToDevice); float* d_gy; cudaMalloc((void**)&d_gy, sizeof(float)*ngadj); cudaMemcpy(d_gy, gy, sizeof(float)*ngadj, cudaMemcpyHostToDevice); float* d_gz; cudaMalloc((void**)&d_gz, sizeof(float)*ngadj); cudaMemcpy(d_gz, gz, sizeof(float)*ngadj, cudaMemcpyHostToDevice); float* d_val; cudaMalloc((void**)&d_val, sizeof(float)*ngadj); wkf_timer_start(timer); // set work-item dimensions // scale number of work units by vector size dim3 grids (ngadj / 4 / wgsize); dim3 blocks (wgsize); for(int n = 0; n < itmax; n++) { if (smem_strided_write) mdh<<<grids, blocks, sizeof(float)*5*wgsize>>>( ngrid, natom, ngadj, d_ax, d_ay, d_az, d_gx, d_gy, d_gz, d_charge, d_size, xkappa, pre1, d_val ); else mdh2<<<grids, blocks, sizeof(float)*5*wgsize>>>( ngrid, natom, ngadj, d_ax, d_ay, d_az, d_gx, d_gy, d_gz, d_charge, d_size, xkappa, pre1, d_val ); } cudaDeviceSynchronize(); wkf_timer_stop(timer); double avg_kernel_time = wkf_timer_time(timer) / ((double) itmax); printf("Average kernel time on the device: %1.12g\n", avg_kernel_time); // read output image cudaMemcpy(val, d_val, sizeof(float)*ngrid, cudaMemcpyDeviceToHost); cudaFree(d_ax); cudaFree(d_ay); cudaFree(d_az); cudaFree(d_gx); cudaFree(d_gy); cudaFree(d_gz); cudaFree(d_val); cudaFree(d_size); cudaFree(d_charge); wkf_timer_destroy(timer); } // reference CPU kernel void run_cpu_kernel( const int ngrid, const int natom, const float *ax, const float *ay, const float *az, const float *gx, const float *gy, const float *gz, const float *charge, const float *size, const float xkappa, const float pre1, float *val) { #pragma omp parallel for for(int igrid=0;igrid<ngrid;igrid++){ float sum = 0.0f; #pragma omp parallel for simd reduction(+:sum) for(int iatom=0; iatom<natom; iatom++) { float dist = sqrtf((gx[igrid]-ax[iatom])*(gx[igrid]-ax[iatom]) + (gy[igrid]-ay[iatom])*(gy[igrid]-ay[iatom]) + (gz[igrid]-az[iatom])*(gz[igrid]-az[iatom])); sum += pre1*(charge[iatom]/dist)*expf(-xkappa*(dist-size[iatom])) / (1+xkappa*size[iatom]); } val[igrid] = sum; } } void usage() { printf("command line parameters:\n"); printf("Optional test flags:\n"); printf(" -itmax N loop test N times\n"); printf(" -wgsize set workgroup size\n"); } void getargs(int argc, const char **argv, int *itmax, int *wgsize) { int i; for (i=0; i<argc; i++) { if ((!strcmp(argv[i], "-itmax")) && ((i+1) < argc)) { i++; *itmax = atoi(argv[i]); } if ((!strcmp(argv[i], "-wgsize")) && ((i+1) < argc)) { i++; *wgsize = atoi(argv[i]); } } printf("Run parameters:\n"); printf(" kernel loop count: %d\n", *itmax); printf(" workgroup size: %d\n", *wgsize); } int main(int argc, const char **argv) { int itmax = 100; int wgsize = 256; getargs(argc, argv, &itmax, &wgsize); wkf_timerhandle timer = wkf_timer_create(); int natom = 5877; int ngrid = 134918; int ngadj = ngrid + (512 - (ngrid & 511)); float pre1 = 4.46184985145e19; float xkappa = 0.0735516324639; float *ax = (float*)calloc(natom, sizeof(float)); float *ay = (float*)calloc(natom, sizeof(float)); float *az = (float*)calloc(natom, sizeof(float)); float *charge = (float*)calloc(natom, sizeof(float)); float *size = (float*)calloc(natom, sizeof(float)); float *gx = (float*)calloc(ngadj, sizeof(float)); float *gy = (float*)calloc(ngadj, sizeof(float)); float *gz = (float*)calloc(ngadj, sizeof(float)); // host result float *val1 = (float*)calloc(ngadj, sizeof(float)); // device result float *val2 = (float*)calloc(ngadj, sizeof(float)); gendata(ax, ay, az, gx, gy, gz, charge, size, natom, ngrid); wkf_timer_start(timer); run_cpu_kernel(ngadj, natom, ax, ay, az, gx, gy, gz, charge, size, xkappa, pre1, val1); wkf_timer_stop(timer); SEP; print_total(val1, ngrid); printf("CPU Time: %1.12g\n", wkf_timer_time(timer)); SEP; wkf_timer_start(timer); run_gpu_kernel(true, wgsize, itmax, ngrid, natom, ngadj, ax, ay, az, gx, gy, gz, charge, size, xkappa, pre1, val2); wkf_timer_stop(timer); SEP; print_total(val2, ngrid); printf("GPU Time: %1.12g\n", wkf_timer_time(timer)); // Vec4 Optimized: SEP; wkf_timer_start(timer); run_gpu_kernel(false, wgsize, itmax, ngrid, natom, ngadj, ax, ay, az, gx, gy, gz, charge, size, xkappa, pre1, val2); wkf_timer_stop(timer); SEP; print_total(val2, ngrid); printf("GPU Time: %1.12g\n", wkf_timer_time(timer)); // Vec4 Optimized: SEP; free(ax); free(ay); free(az); free(charge); free(size); free(gx); free(gy); free(gz); free(val1); free(val2); wkf_timer_destroy(timer); return 0; }
the_stack
#include <thrust/device_ptr.h> #include <thrust/execution_policy.h> #include <thrust/fill.h> #include <thrust/for_each.h> #include <algorithm> #include <memory> namespace faiss { namespace gpu { template <typename T> void runAllPairwiseDistance( bool computeL2, GpuResources* res, cudaStream_t stream, Tensor<T, 2, true>& centroids, bool centroidsRowMajor, Tensor<float, 1, true>* centroidNorms, Tensor<T, 2, true>& queries, bool queriesRowMajor, Tensor<float, 2, true>& outDistances) { // The # of centroids in `centroids` based on memory layout auto numCentroids = centroids.getSize(centroidsRowMajor ? 0 : 1); // The # of queries in `queries` based on memory layout auto numQueries = queries.getSize(queriesRowMajor ? 0 : 1); // The dimensions of the vectors to consider auto dim = queries.getSize(queriesRowMajor ? 1 : 0); FAISS_ASSERT( (numQueries == 0 || numCentroids == 0) || dim == centroids.getSize(centroidsRowMajor ? 1 : 0)); FAISS_ASSERT(outDistances.getSize(0) == numQueries); FAISS_ASSERT(outDistances.getSize(1) == numCentroids); // If we're querying against a 0 sized set, just return empty results if (centroids.numElements() == 0) { thrust::fill( thrust::cuda::par.on(stream), outDistances.data(), outDistances.end(), Limits<float>::getMax()); return; } // L2: If ||c||^2 is not pre-computed, calculate it DeviceTensor<float, 1, true> cNorms; if (computeL2 && !centroidNorms) { cNorms = DeviceTensor<float, 1, true>( res, makeTempAlloc(AllocType::Other, stream), {numCentroids}); runL2Norm(centroids, centroidsRowMajor, cNorms, true, stream); centroidNorms = &cNorms; } // // Prepare norm vector ||q||^2; ||c||^2 is already pre-computed // DeviceTensor<float, 1, true> queryNorms( res, makeTempAlloc(AllocType::Other, stream), {(int)numQueries}); // ||q||^2 if (computeL2) { runL2Norm(queries, queriesRowMajor, queryNorms, true, stream); } // L2: distance is ||c||^2 - 2qc + ||q||^2, we compute -2qc // IP: just compute qc // (query id x dim) x (centroid id, dim)' = (query id, centroid id) runMatrixMult( outDistances, false, // not transposed queries, !queriesRowMajor, // transposed MM if col major centroids, centroidsRowMajor, // transposed MM if row major computeL2 ? -2.0f : 1.0f, 0.0f, res->getBlasHandleCurrentDevice(), stream); if (computeL2) { // Need to add ||q||^2 along rows // Need to add ||c||^2 along columns // FIXME: optimize with a dedicated kernel runSumAlongColumns(*centroidNorms, outDistances, stream); runSumAlongRows( queryNorms, outDistances, true, // L2 distances should not go below zero // due to roundoff error stream); } } template <typename T> void runDistance( bool computeL2, GpuResources* res, cudaStream_t stream, Tensor<T, 2, true>& centroids, bool centroidsRowMajor, Tensor<float, 1, true>* centroidNorms, Tensor<T, 2, true>& queries, bool queriesRowMajor, int k, Tensor<float, 2, true>& outDistances, Tensor<int, 2, true>& outIndices, bool ignoreOutDistances) { // The # of centroids in `centroids` based on memory layout auto numCentroids = centroids.getSize(centroidsRowMajor ? 0 : 1); // The # of queries in `queries` based on memory layout auto numQueries = queries.getSize(queriesRowMajor ? 0 : 1); // The dimensions of the vectors to consider auto dim = queries.getSize(queriesRowMajor ? 1 : 0); FAISS_ASSERT( (numQueries == 0 || numCentroids == 0) || dim == centroids.getSize(centroidsRowMajor ? 1 : 0)); FAISS_ASSERT(outDistances.getSize(0) == numQueries); FAISS_ASSERT(outIndices.getSize(0) == numQueries); FAISS_ASSERT(outDistances.getSize(1) == k); FAISS_ASSERT(outIndices.getSize(1) == k); // If we're querying against a 0 sized set, just return empty results if (centroids.numElements() == 0) { thrust::fill( thrust::cuda::par.on(stream), outDistances.data(), outDistances.end(), Limits<float>::getMax()); thrust::fill( thrust::cuda::par.on(stream), outIndices.data(), outIndices.end(), -1); return; } // L2: If ||c||^2 is not pre-computed, calculate it DeviceTensor<float, 1, true> cNorms; if (computeL2 && !centroidNorms) { cNorms = DeviceTensor<float, 1, true>( res, makeTempAlloc(AllocType::Other, stream), {numCentroids}); runL2Norm(centroids, centroidsRowMajor, cNorms, true, stream); centroidNorms = &cNorms; } // // Prepare norm vector ||q||^2; ||c||^2 is already pre-computed // DeviceTensor<float, 1, true> queryNorms( res, makeTempAlloc(AllocType::Other, stream), {(int)numQueries}); // ||q||^2 if (computeL2) { runL2Norm(queries, queriesRowMajor, queryNorms, true, stream); } // By default, aim to use up to 512 MB of memory for the processing, with // both number of queries and number of centroids being at least 512. int tileRows = 0; int tileCols = 0; chooseTileSize( numQueries, numCentroids, dim, sizeof(T), res->getTempMemoryAvailableCurrentDevice(), tileRows, tileCols); int numColTiles = utils::divUp(numCentroids, tileCols); // We can have any number of vectors to query against, even less than k, in // which case we'll return -1 for the index FAISS_ASSERT(k <= GPU_MAX_SELECTION_K); // select limitation // Temporary output memory space we'll use DeviceTensor<float, 2, true> distanceBuf1( res, makeTempAlloc(AllocType::Other, stream), {tileRows, tileCols}); DeviceTensor<float, 2, true> distanceBuf2( res, makeTempAlloc(AllocType::Other, stream), {tileRows, tileCols}); DeviceTensor<float, 2, true>* distanceBufs[2] = { &distanceBuf1, &distanceBuf2}; DeviceTensor<float, 2, true> outDistanceBuf1( res, makeTempAlloc(AllocType::Other, stream), {tileRows, numColTiles * k}); DeviceTensor<float, 2, true> outDistanceBuf2( res, makeTempAlloc(AllocType::Other, stream), {tileRows, numColTiles * k}); DeviceTensor<float, 2, true>* outDistanceBufs[2] = { &outDistanceBuf1, &outDistanceBuf2}; DeviceTensor<int, 2, true> outIndexBuf1( res, makeTempAlloc(AllocType::Other, stream), {tileRows, numColTiles * k}); DeviceTensor<int, 2, true> outIndexBuf2( res, makeTempAlloc(AllocType::Other, stream), {tileRows, numColTiles * k}); DeviceTensor<int, 2, true>* outIndexBufs[2] = { &outIndexBuf1, &outIndexBuf2}; auto streams = res->getAlternateStreamsCurrentDevice(); streamWait(streams, {stream}); int curStream = 0; bool interrupt = false; // Tile over the input queries for (int i = 0; i < numQueries; i += tileRows) { if (interrupt || InterruptCallback::is_interrupted()) { interrupt = true; break; } int curQuerySize = std::min(tileRows, numQueries - i); auto outDistanceView = outDistances.narrow(0, i, curQuerySize); auto outIndexView = outIndices.narrow(0, i, curQuerySize); auto queryView = queries.narrow(queriesRowMajor ? 0 : 1, i, curQuerySize); auto queryNormNiew = queryNorms.narrow(0, i, curQuerySize); auto outDistanceBufRowView = outDistanceBufs[curStream]->narrow(0, 0, curQuerySize); auto outIndexBufRowView = outIndexBufs[curStream]->narrow(0, 0, curQuerySize); // Tile over the centroids for (int j = 0; j < numCentroids; j += tileCols) { if (InterruptCallback::is_interrupted()) { interrupt = true; break; } int curCentroidSize = std::min(tileCols, numCentroids - j); int curColTile = j / tileCols; auto centroidsView = sliceCentroids( centroids, centroidsRowMajor, j, curCentroidSize); auto distanceBufView = distanceBufs[curStream] ->narrow(0, 0, curQuerySize) .narrow(1, 0, curCentroidSize); auto outDistanceBufColView = outDistanceBufRowView.narrow(1, k * curColTile, k); auto outIndexBufColView = outIndexBufRowView.narrow(1, k * curColTile, k); // L2: distance is ||c||^2 - 2qc + ||q||^2, we compute -2qc // IP: just compute qc // (query id x dim) x (centroid id, dim)' = (query id, centroid id) runMatrixMult( distanceBufView, false, // not transposed queryView, !queriesRowMajor, // transposed MM if col major centroidsView, centroidsRowMajor, // transposed MM if row major computeL2 ? -2.0f : 1.0f, 0.0f, res->getBlasHandleCurrentDevice(), streams[curStream]); if (computeL2) { // For L2 distance, we use this fused kernel that performs both // adding ||c||^2 to -2qc and k-selection, so we only need two // passes (one write by the gemm, one read here) over the huge // region of output memory // // If we aren't tiling along the number of centroids, we can // perform the output work directly if (tileCols == numCentroids) { // Write into the final output runL2SelectMin( distanceBufView, *centroidNorms, outDistanceView, outIndexView, k, streams[curStream]); if (!ignoreOutDistances) { // expand (query id) to (query id, k) by duplicating // along rows top-k ||c||^2 - 2qc + ||q||^2 in the form // (query id, k) runSumAlongRows( queryNormNiew, outDistanceView, true, // L2 distances should not go below zero // due to roundoff error streams[curStream]); } } else { auto centroidNormsView = centroidNorms->narrow(0, j, curCentroidSize); // Write into our intermediate output runL2SelectMin( distanceBufView, centroidNormsView, outDistanceBufColView, outIndexBufColView, k, streams[curStream]); if (!ignoreOutDistances) { // expand (query id) to (query id, k) by duplicating // along rows top-k ||c||^2 - 2qc + ||q||^2 in the form // (query id, k) runSumAlongRows( queryNormNiew, outDistanceBufColView, true, // L2 distances should not go below zero // due to roundoff error streams[curStream]); } } } else { // For IP, just k-select the output for this tile if (tileCols == numCentroids) { // Write into the final output runBlockSelect( distanceBufView, outDistanceView, outIndexView, true, k, streams[curStream]); } else { // Write into the intermediate output runBlockSelect( distanceBufView, outDistanceBufColView, outIndexBufColView, true, k, streams[curStream]); } } } // As we're finished with processing a full set of centroids, perform // the final k-selection if (tileCols != numCentroids) { // The indices are tile-relative; for each tile of k, we need to add // tileCols to the index runIncrementIndex( outIndexBufRowView, k, tileCols, streams[curStream]); runBlockSelectPair( outDistanceBufRowView, outIndexBufRowView, outDistanceView, outIndexView, computeL2 ? false : true, k, streams[curStream]); } curStream = (curStream + 1) % 2; } // Have the desired ordering stream wait on the multi-stream streamWait({stream}, streams); if (interrupt) { FAISS_THROW_MSG("interrupted"); } } template <typename T> void runL2Distance( GpuResources* res, cudaStream_t stream, Tensor<T, 2, true>& centroids, bool centroidsRowMajor, Tensor<float, 1, true>* centroidNorms, Tensor<T, 2, true>& queries, bool queriesRowMajor, int k, Tensor<float, 2, true>& outDistances, Tensor<int, 2, true>& outIndices, bool ignoreOutDistances = false) { runDistance<T>( true, // L2 res, stream, centroids, centroidsRowMajor, centroidNorms, queries, queriesRowMajor, k, outDistances, outIndices, ignoreOutDistances); } template <typename T> void runIPDistance( GpuResources* res, cudaStream_t stream, Tensor<T, 2, true>& centroids, bool centroidsRowMajor, Tensor<T, 2, true>& queries, bool queriesRowMajor, int k, Tensor<float, 2, true>& outDistances, Tensor<int, 2, true>& outIndices) { runDistance<T>( false, // IP res, stream, centroids, centroidsRowMajor, nullptr, // no centroid norms provided queries, queriesRowMajor, k, outDistances, outIndices, false); } // // Instantiations of the distance templates // void runAllPairwiseL2Distance( GpuResources* res, cudaStream_t stream, Tensor<float, 2, true>& vectors, bool vectorsRowMajor, Tensor<float, 1, true>* vectorNorms, Tensor<float, 2, true>& queries, bool queriesRowMajor, Tensor<float, 2, true>& outDistances) { runAllPairwiseDistance<float>( true, res, stream, vectors, vectorsRowMajor, vectorNorms, queries, queriesRowMajor, outDistances); } void runAllPairwiseL2Distance( GpuResources* res, cudaStream_t stream, Tensor<half, 2, true>& vectors, bool vectorsRowMajor, Tensor<float, 1, true>* vectorNorms, Tensor<half, 2, true>& queries, bool queriesRowMajor, Tensor<float, 2, true>& outDistances) { runAllPairwiseDistance<half>( true, res, stream, vectors, vectorsRowMajor, vectorNorms, queries, queriesRowMajor, outDistances); } void runAllPairwiseIPDistance( GpuResources* res, cudaStream_t stream, Tensor<float, 2, true>& vectors, bool vectorsRowMajor, Tensor<float, 2, true>& queries, bool queriesRowMajor, Tensor<float, 2, true>& outDistances) { runAllPairwiseDistance<float>( false, res, stream, vectors, vectorsRowMajor, nullptr, queries, queriesRowMajor, outDistances); } void runAllPairwiseIPDistance( GpuResources* res, cudaStream_t stream, Tensor<half, 2, true>& vectors, bool vectorsRowMajor, Tensor<half, 2, true>& queries, bool queriesRowMajor, Tensor<float, 2, true>& outDistances) { runAllPairwiseDistance<half>( false, res, stream, vectors, vectorsRowMajor, nullptr, queries, queriesRowMajor, outDistances); } void runL2Distance( GpuResources* res, cudaStream_t stream, Tensor<float, 2, true>& vectors, bool vectorsRowMajor, Tensor<float, 1, true>* vectorNorms, Tensor<float, 2, true>& queries, bool queriesRowMajor, int k, Tensor<float, 2, true>& outDistances, Tensor<int, 2, true>& outIndices, bool ignoreOutDistances) { runL2Distance<float>( res, stream, vectors, vectorsRowMajor, vectorNorms, queries, queriesRowMajor, k, outDistances, outIndices, ignoreOutDistances); } void runL2Distance( GpuResources* res, cudaStream_t stream, Tensor<half, 2, true>& vectors, bool vectorsRowMajor, Tensor<float, 1, true>* vectorNorms, Tensor<half, 2, true>& queries, bool queriesRowMajor, int k, Tensor<float, 2, true>& outDistances, Tensor<int, 2, true>& outIndices, bool ignoreOutDistances) { runL2Distance<half>( res, stream, vectors, vectorsRowMajor, vectorNorms, queries, queriesRowMajor, k, outDistances, outIndices, ignoreOutDistances); } void runIPDistance( GpuResources* res, cudaStream_t stream, Tensor<float, 2, true>& vectors, bool vectorsRowMajor, Tensor<float, 2, true>& queries, bool queriesRowMajor, int k, Tensor<float, 2, true>& outDistances, Tensor<int, 2, true>& outIndices) { runIPDistance<float>( res, stream, vectors, vectorsRowMajor, queries, queriesRowMajor, k, outDistances, outIndices); } void runIPDistance( GpuResources* res, cudaStream_t stream, Tensor<half, 2, true>& vectors, bool vectorsRowMajor, Tensor<half, 2, true>& queries, bool queriesRowMajor, int k, Tensor<float, 2, true>& outDistances, Tensor<int, 2, true>& outIndices) { runIPDistance<half>( res, stream, vectors, vectorsRowMajor, queries, queriesRowMajor, k, outDistances, outIndices); } } // namespace gpu } // namespace faiss
the_stack
static bool THCUNN_checkKeysValues(THCState *state, THCudaLongTensor* keys, THCTensor* values) { return THCudaLongTensor_size(state, keys, 0) == THCTensor_(nElement)(state, values) && THCTensor_(nDimension)(state, values) == 1 && THCudaLongTensor_nDimension(state, keys) == 1; } void THNN_(IndexLinear_updateOutput)( THCState *state, THCudaLongTensor *keys, long keysOffset, THCTensor *values, THCudaLongTensor *sizes, THCudaLongTensor *cumSumSizes, THCTensor *output, THCTensor *weight, THCTensor *bias, THCTensor *normalizedValues, int train) { // Make sure these inputs are contiguous to accelerate computations THArgCheck(THCudaLongTensor_isContiguous(state, keys), 1, "keys vector must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, values), 3, "values vector must be contiguous"); THArgCheck(THCudaLongTensor_isContiguous(state, sizes), 4, "sizes vector must be contiguous"); THArgCheck(THCudaLongTensor_isContiguous(state, cumSumSizes), 5, "cumSumSizes vector must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, output), 6, "output vector must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, weight), 7, "weight matrix must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, bias), 8, "bias vector must be contiguous"); THArgCheck(THCUNN_checkKeysValues(state, keys, values), 1, "Keys and values should have the same number of elements"); long batchSize = sizes->size[0]; long outDim = bias->size[0]; long wDim = weight->size[1]; long weightStride = weight->stride[0]; int maxNormalize = wDim - outDim; long keysSize = keys->size[0]; long nnzPerRow = divup(keysSize, batchSize); THCTensor_(resize2d)(state, output, batchSize, outDim); long *keysData = THCudaLongTensor_data (state, keys); real *valuesData = THCTensor_(data) (state, values); long *cumSumSizesData = THCudaLongTensor_data (state, cumSumSizes); real *biasData = THCTensor_(data) (state, bias); real *weightData = THCTensor_(data) (state, weight); real *outData = THCTensor_(data) (state, output); cudaStream_t stream = THCState_getCurrentStream(state); dim3 threads(THREADS_X, THREADS_Y); int blocks_x = divup(outDim, threads.x); int blocks_y = batchSize; int nnzPerBlock = ((outDim == 1 || batchSize == 1) ? THREADS_X : NNZ_PER_BLOCK_MAX); int blocks_z = divup(nnzPerRow, nnzPerBlock); dim3 blocks(blocks_x, blocks_y, blocks_z); if (blocks_z > 1) { THCudaCheck(cudaMemsetAsync(outData, 0, outDim * batchSize * sizeof(real), stream)); } real *normalizedValuesData = NULL; if (maxNormalize && train) { THCTensor_(resize1d)(state, normalizedValues, keysSize); normalizedValuesData = THCTensor_(data)(state, normalizedValues); updateOutput<real, true><<<blocks, threads, 0, stream>>> (outData, normalizedValuesData, valuesData, cumSumSizesData, keysData, batchSize, outDim, weightData, biasData, weightStride, keysOffset, maxNormalize, nnzPerBlock); } else { updateOutput<real, false><<<blocks, threads, 0, stream>>> (outData, normalizedValuesData, valuesData, cumSumSizesData, keysData, batchSize, outDim, weightData, biasData, weightStride, keysOffset, maxNormalize, nnzPerBlock); } } void THNN_(IndexLinear_accGradParameters)( THCState *state, THCudaLongTensor *keys, long keysOffset, THCTensor *values, THCudaLongTensor *sizes, THCudaLongTensor *cumSumSizes, THCTensor *gradOutput, THCTensor *gradWeight, THCTensor *gradBias, THCTensor *weight, THCTensor *bias, THCTensor* valuesBuffer, accreal weightDecay, accreal scale) { long keysSize = keys->size[0]; long batchSize = sizes->size[0]; long outDim = bias->size[0]; long wDim = weight->size[1]; int maxNormalize = wDim - outDim; // Make sure these inputs are contiguous to accelerate computations THArgCheck(THCudaLongTensor_isContiguous(state, keys), 1, "keys vector must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, values), 3, "values vector must be contiguous"); THArgCheck(THCudaLongTensor_isContiguous(state, sizes), 4, "sizes vector must be contiguous"); THArgCheck(THCudaLongTensor_isContiguous(state, cumSumSizes), 5, "cumSumSizes vector must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, gradOutput), 6, "gradOutput vector must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, gradWeight), 7, "gradWeight matrix must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, gradBias), 8, "gradBias vector must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, weight), 9, "weight matrix must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, bias), 10, "bias vector must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, valuesBuffer), 11, "valuesBuffer vector must be contiguous"); THArgCheck(THCUNN_checkKeysValues(state, keys, values), 1, "Keys and values should have the same number of elements"); THCTensor_(resize2d)(state, gradWeight, keysSize, outDim * (maxNormalize > 0 ? 2 : 1)); real *valuesData = THCTensor_(data) (state, values); long *cumSumSizesData = THCudaLongTensor_data (state, cumSumSizes); real *gradOutputData = THCTensor_(data) (state, gradOutput); real *gradBiasData = THCTensor_(data) (state, gradBias); real *gradWeightData = THCTensor_(data) (state, gradWeight); long gradWeightStride = gradWeight->stride[0]; cudaStream_t stream = THCState_getCurrentStream(state); dim3 threads(THREADS_X, THREADS_Y); int blocks_x = divup(outDim, threads.x); accGradBias<real, false><<<blocks_x, threads, 0, stream>>> (gradBiasData, gradOutputData, outDim, batchSize, scale, weightDecay); dim3 blocks(blocks_x, batchSize); accGradWeight<real><<<blocks, threads, 0, stream>>> (gradWeightData, gradOutputData, valuesData, cumSumSizesData, outDim, gradWeightStride, scale, weightDecay, maxNormalize); } void THNN_(IndexLinear_accUpdateGradParameters)( THCState *state, THCudaLongTensor *keys, long keysOffset, THCTensor *values, THCudaLongTensor *sizes, THCudaLongTensor *cumSumSizes, THCTensor *gradOutput, THCTensor *weight, THCTensor *bias, accreal weightDecay, accreal scale) { // Make sure these inputs are contiguous to accelerate computations THArgCheck(THCudaLongTensor_isContiguous(state, keys), 1, "keys vector must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, values), 3, "values vector must be contiguous"); THArgCheck(THCudaLongTensor_isContiguous(state, sizes), 4, "sizes vector must be contiguous"); THArgCheck(THCudaLongTensor_isContiguous(state, cumSumSizes), 5, "cumSumSizes vector must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, gradOutput), 6, "gradOutput vector must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, weight), 7, "weight matrix must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, bias), 8, "bias vector must be contiguous"); THArgCheck(THCUNN_checkKeysValues(state, keys, values), 1, "Keys and values should have the same number of elements"); long batchSize = sizes->size[0]; long outDim = bias->size[0]; long keysSize = keys->size[0]; long wDim = weight->size[1]; int maxNormalize = wDim - outDim; real *biasData = THCTensor_(data) (state, bias); real *weightData = THCTensor_(data) (state, weight); real *gradOutputData = THCTensor_(data) (state, gradOutput); real *valuesData = THCTensor_(data) (state, values); long *keysData = THCudaLongTensor_data (state, keys); long *cumSumSizesData = THCudaLongTensor_data (state, cumSumSizes); long weightStride = weight->stride[0]; cudaStream_t stream = THCState_getCurrentStream(state); dim3 threads(THREADS_X, THREADS_Y); int blocks_x = divup(outDim, threads.x); accGradBias<real, true><<<blocks_x, threads, 0, stream>>> (biasData, gradOutputData, outDim, batchSize, scale, weightDecay); long nnzPerRow = divup(keysSize, batchSize); int blocks_y = divup(nnzPerRow, REPEAT * threads.y); dim3 blocks(blocks_x, blocks_y); for (long batchId = 0; batchId < batchSize; batchId++) { accUpdateWeight<real><<<blocks, threads, 0, stream>>> (weightData, weightStride, gradOutputData, outDim, valuesData, cumSumSizesData, keysData, keysOffset, scale, weightDecay, maxNormalize, batchId); } } void THNN_(IndexLinear_updateParameters)( THCState *state, THCTensor *gradWeight, THCTensor *gradBias, THCTensor *weight, THCTensor *bias, THCudaLongTensor *runningKeys, THCudaLongTensor *cumSumSizes, long keysOffset, accreal weightDecay, accreal learningRate) { // Make sure these inputs are contiguous to accelerate computations THArgCheck(THCTensor_(isContiguous)(state, gradWeight), 1, "gradWeight matrix must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, gradBias), 2, "gradBias vector must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, weight), 3, "weight matrix must be contiguous"); THArgCheck(THCTensor_(isContiguous)(state, bias), 4, "bias vector must be contiguous"); THArgCheck(THCudaLongTensor_isContiguous(state, runningKeys), 5, "runningKeys vector must be contiguous"); THArgCheck(THCudaLongTensor_isContiguous(state, cumSumSizes), 6, "cumSumSizes vector must be contiguous"); long outDim = bias->size[0]; long wDim = weight->size[1]; int maxNormalize = wDim - outDim; long keysSize = runningKeys->size[0]; long batchSize = cumSumSizes->size[0]; THCTensor_(cadd)(state, bias, bias, -learningRate, gradBias); long gradWeightStride = gradWeight->stride[0]; long weightStride = weight->stride[0]; long *keysData = THCudaLongTensor_data (state, runningKeys); long *cumSumSizesData = THCudaLongTensor_data (state, cumSumSizes); real *gradWeightData = THCTensor_(data) (state, gradWeight); real *weightData = THCTensor_(data) (state, weight); dim3 threads(THREADS_X, THREADS_Y); long nnzPerRow = divup(keysSize, batchSize); int blocks_x = divup(outDim, threads.x); int blocks_y = divup(nnzPerRow, REPEAT * threads.y); dim3 blocks(blocks_x, blocks_y); cudaStream_t stream = THCState_getCurrentStream(state); for (long batchId = 0; batchId < batchSize; batchId++) { updateWeight<real><<<blocks, threads, 0, stream>>> (weightData, gradWeightData, keysData, cumSumSizesData, outDim, gradWeightStride, weightStride, keysOffset, learningRate, weightDecay, maxNormalize, batchId); } } #endif
the_stack
//Helper functions //Reorders data extern "C" __global__ void dataReorderR4(const int n_particles, real4 *source, real4 *destination, uint *permutation) { const int bid = blockIdx.y * gridDim.x + blockIdx.x; const int tid = threadIdx.y * blockDim.x + threadIdx.x; const int dim = blockDim.x * blockDim.y; int idx = bid * dim + tid; if (idx >= n_particles) return; int newIndex = permutation[idx]; destination[idx] = source[newIndex]; } extern "C" __global__ void dataReorderF2(const int n_particles, float2 *source, float2 *destination, uint *permutation) { const int bid = blockIdx.y * gridDim.x + blockIdx.x; const int tid = threadIdx.y * blockDim.x + threadIdx.x; const int dim = blockDim.x * blockDim.y; int idx = bid * dim + tid; if (idx >= n_particles) return; int newIndex = permutation[idx]; destination[idx] = source[newIndex]; } extern "C" __global__ void dataReorderI1(const int n_particles, int *source, int *destination, uint *permutation) { const int bid = blockIdx.y * gridDim.x + blockIdx.x; const int tid = threadIdx.y * blockDim.x + threadIdx.x; const int dim = blockDim.x * blockDim.y; int idx = bid * dim + tid; if (idx >= n_particles) return; int newIndex = permutation[idx]; destination[idx] = source[newIndex]; } //Convert a 64bit key uint2 key into a 96key with a permutation value build in extern "C" __global__ void convertKey64to96(uint4 *keys, uint4 *newKeys, const int N) { const int bid = blockIdx.y * gridDim.x + blockIdx.x; const int tid = threadIdx.y * blockDim.x + threadIdx.x; const int dim = blockDim.x * blockDim.y; int idx = bid * dim + tid; if (idx >= N) return; uint4 temp = keys[idx]; newKeys[idx] = (uint4){temp.x, temp.y, temp.z, idx}; } extern "C" __global__ void extractKeyAndPerm(uint4 *newKeys, uint4 *keys, uint *permutation, const int N) { const int bid = blockIdx.y * gridDim.x + blockIdx.x; const int tid = threadIdx.y * blockDim.x + threadIdx.x; const int dim = blockDim.x * blockDim.y; int idx = bid * dim + tid; if (idx >= N) return; uint4 temp = newKeys[idx]; keys[idx] = (uint4){temp.x, temp.y, temp.z, temp.w}; permutation[idx] = temp.w; } //Extract 1 of the 4 items of an uint4 key and move it into a 32bit array extern "C" __global__ void extractInt(uint4 *keys, uint *simpleKeys, const int N, int keyIdx) { const int bid = blockIdx.y * gridDim.x + blockIdx.x; const int tid = threadIdx.y * blockDim.x + threadIdx.x; const int dim = blockDim.x * blockDim.y; int idx = bid * dim + tid; if (idx >= N) return; uint4 temp = keys[idx]; int simpleTemp; if(keyIdx == 0) simpleTemp = temp.x; else if(keyIdx == 1) simpleTemp = temp.y; else if(keyIdx == 2) simpleTemp = temp.z; simpleKeys[idx] = simpleTemp; } //Create range of 0 to N extern "C" __global__ void fillSequence(uint *sequence, const int N) { const int bid = blockIdx.y * gridDim.x + blockIdx.x; const int tid = threadIdx.y * blockDim.x + threadIdx.x; const int dim = blockDim.x * blockDim.y; int idx = bid * dim + tid; if (idx >= N) return; sequence[idx] = idx; } //Reorder the data in the arrays according to a given permutation extern "C" __global__ void reOrderKeysValues(uint4 *keysSrc, uint4 *keysDest, uint *permutation, const int N) { const int bid = blockIdx.y * gridDim.x + blockIdx.x; const int tid = threadIdx.y * blockDim.x + threadIdx.x; const int dim = blockDim.x * blockDim.y; int idx = bid * dim + tid; if (idx >= N) return; int newIndex = permutation[idx]; keysDest[idx] = keysSrc[newIndex]; } extern "C" __global__ void sort_count(volatile uint2 *valid, int *counts, const int N, setupParams sParam, int bitIdx/*, int2 *blaat*/) { const int tid = threadIdx.x; const int bid = blockDim.y * blockIdx.x + threadIdx.y; int totalNumThreads = gridDim.x*blockDim.y*blockDim.x; //120*4*32 // gridDim.x * blockDim.y; //2D !!!! volatile __shared__ int shmemSC[128]; volatile __shared__ int shmemSCTEST[128]; //Determine the parameters and loop over the particles int jobSize = (N / 2) / totalNumThreads; int offSet = jobSize * bid; int count = 0; jobSize = sParam.jobs; if(bid < sParam.blocksWithExtraJobs) jobSize++; if(bid <= sParam.blocksWithExtraJobs) offSet = (sParam.jobs+1)*64*bid; else { offSet = sParam.blocksWithExtraJobs*(sParam.jobs+1)*64; offSet += (bid-sParam.blocksWithExtraJobs)*(sParam.jobs)*64; } offSet /= 2; //Divide by two since we do double loads (uint2) for(int i=0; i < jobSize; i++) { count += !(valid[offSet + tid].x & (1u<<bitIdx)); count += !(valid[offSet + tid].y & (1u<<bitIdx)); offSet += blockDim.x; } //Reduce to get the count of this block shmemSC[32*threadIdx.y + tid] = count; reduce_block2(tid, &shmemSC[32*threadIdx.y], count); //Save the values / count of the current block if(threadIdx.x == 0) counts[bid] = shmemSC[32*threadIdx.y]; //Block 0 handles any extra elements that couldn't be divided equally if(bid == 0) { //Here i use single element reads for ease of boundary conditions and steps count = 0; offSet = sParam.extraOffset; uint* valid2 = (uint*) valid; for(int i=0 ; i < sParam.extraElements; i += blockDim.x) { if((offSet + i + tid) < (N)) //Make sure we dont read more than there are items { count += !(valid2[offSet + i + tid] & (1u<<bitIdx)); } } //Reduce shmemSCTEST[tid] = count; __syncthreads(); if(tid < 16){ shmemSCTEST[tid] = count = count + shmemSCTEST[tid+16]; shmemSCTEST[tid] = count = count + shmemSCTEST[tid+8]; shmemSCTEST[tid] = count = count + shmemSCTEST[tid+4]; shmemSCTEST[tid] = count = count + shmemSCTEST[tid+2]; shmemSCTEST[tid] = count = count + shmemSCTEST[tid+1]; } //Save the count if(tid == 0) { counts[gridDim.x*blockDim.y] = shmemSCTEST[0]; } __syncthreads(); }//end if bid==0 }//end compact_count // __device__ __forceinline__ int testTest(volatile unsigned int tmp[], uint val, const int idx, long test) // { // tmp[idx-16] = 0; tmp[idx] = val; // // // Since we set half the array to 0 we don't need ifs! // tmp[idx] = val = tmp[idx - 1] + val; // tmp[idx] = val = tmp[idx - 2] + val; // tmp[idx] = val = tmp[idx - 4] + val; // tmp[idx] = val = tmp[idx - 8] + val; // tmp[idx] = val = tmp[idx - 16] + val; // // return (idx > 0) ? tmp[idx-1] : 0; // } /* For sorting it turns out that the stage kernels works faster than the non-staged Might depend on how much has to be sorted/moved, have to do timings in the actual code */ extern "C" __global__ void sort_move_stage_key_value(uint2 *valid, int *output, uint2 *srcValues, uint *valuesOut, int *counts, const int N, setupParams sParam, int bitIdx) { //Walk the values of this block const int tid = threadIdx.x; const int bid = blockDim.y * blockIdx.x + threadIdx.y; volatile __shared__ unsigned int shmemSMSKV[192]; volatile __shared__ int stage[64*4]; volatile __shared__ int stage_values[64*4]; //Determine the parameters and loop over the particles int jobSize, offSet; jobSize = sParam.jobs; if(bid < sParam.blocksWithExtraJobs) jobSize++; if(bid <= sParam.blocksWithExtraJobs) offSet = (sParam.jobs+1)*64*bid; else { offSet = sParam.blocksWithExtraJobs*(sParam.jobs+1)*64; offSet += (bid-sParam.blocksWithExtraJobs)*(sParam.jobs)*64; } int outputOffset = counts[bid]; //Get the start of the output offset of the invalid items //this is calculated as follows: //totalValidItems + startReadOffset - startOutputOffset //startReadOffset - startOutputOffset <- is the total number of invalid items from any blocks //before the current block int rightOutputOffset = counts[gridDim.x*blockDim.y+1]; rightOutputOffset = rightOutputOffset + offSet - outputOffset; offSet /= 2; //Divide by two since we do double loads (uint2) TODO what happens if offSet is uneven...? int curCount; int idx, ridx; outputOffset += threadIdx.x; rightOutputOffset += threadIdx.x; //Do per step the prefix scan to determine the output locations for(int i=0; i < jobSize; i++) { uint2 validBase = valid[offSet + tid]; uint2 valuesBase = srcValues[offSet + tid]; int value = !(validBase.x & (1u<<bitIdx)); value += !(validBase.y & (1u<<bitIdx)); idx = hillisSteele5(&shmemSMSKV[48*threadIdx.y+16], curCount, value, threadIdx.x); ridx = curCount + threadIdx.x*2 - idx; //lane*2 - idx , *2 since we read 2 items a time if(!(validBase.x & (1u<<bitIdx))) { stage[idx + threadIdx.y*64] = validBase.x; stage_values[idx++ + threadIdx.y*64] = valuesBase.x; } else { stage[ridx + threadIdx.y*64] = validBase.x; stage_values[ridx++ + threadIdx.y*64] = valuesBase.x; } if(!(validBase.y & (1u<<bitIdx))) { stage[idx + threadIdx.y*64] = validBase.y; stage_values[idx + threadIdx.y*64] = valuesBase.y; } else { stage[ridx + threadIdx.y*64] = validBase.y; stage_values[ridx + threadIdx.y*64] = valuesBase.y; } //Reuse value as index value = outputOffset; //Flush output, first 32 if(threadIdx.x >= curCount) value = rightOutputOffset-curCount; output[value] = stage [threadIdx.x + threadIdx.y*64]; valuesOut[value] = stage_values[threadIdx.x + threadIdx.y*64]; //2nd 32 value = outputOffset + blockDim.x; if(threadIdx.x + blockDim.x >= curCount) value = rightOutputOffset + blockDim.x - curCount; output[value] = stage [threadIdx.x + blockDim.x + threadIdx.y*64]; valuesOut[value] = stage_values[threadIdx.x + blockDim.x + threadIdx.y*64]; outputOffset += curCount; //Increase the output offset rightOutputOffset += 64 - curCount; //64 (32*2) since we do 2 items a time offSet += blockDim.x; //Step to the next N threads } //Block 0 handles any extra elements that couldn't be divided equally if(bid == 0) { //Here i use single element reads for ease of boundary conditions and steps offSet = sParam.extraOffset; outputOffset = counts[gridDim.x*blockDim.y]; rightOutputOffset = counts[gridDim.x*blockDim.y+1]; rightOutputOffset = rightOutputOffset + offSet - outputOffset; uint* valid2 = (uint*) valid; uint* srcValues2 = (uint*) srcValues; for(int i=0; i < sParam.extraElements; i += blockDim.x) { uint value = 0; uint srcValueItem = 0; if((offSet + i + tid) < (N)){ //Make sure we dont read more than there are items value = valid2[offSet + i + tid]; srcValueItem = srcValues2[offSet + i + tid]; } idx = hillisSteele5(&shmemSMSKV[48*threadIdx.y+16], curCount, !(value & (1u<<bitIdx)), threadIdx.x); ridx = threadIdx.x - idx; if((offSet + i + tid) < N) if(!(value & (1u<<bitIdx))) { output[idx + outputOffset] = value; valuesOut[idx + outputOffset] = srcValueItem; } else { output[ridx + rightOutputOffset] = value; valuesOut[ridx + rightOutputOffset] = srcValueItem; } outputOffset += curCount; //Increase the output offset rightOutputOffset += 32-curCount; //32 since we do only 1 at a time } }//end if bid==0 }//end sort_move_stage_key_value
the_stack
#include "cupoch/geometry/pointcloud.h" #include "cupoch/geometry/trianglemesh.h" #include "cupoch/utility/platform.h" #include "cupoch/visualization/shader/normal_shader.h" #include "cupoch/visualization/shader/shader.h" using namespace cupoch; using namespace cupoch::visualization; using namespace cupoch::visualization::glsl; namespace { struct copy_trianglemesh_functor { copy_trianglemesh_functor(const Eigen::Vector3f *vertices, const Eigen::Vector3f *vertex_normals, const int *triangles, const Eigen::Vector3f *triangle_normals, RenderOption::MeshShadeOption shade_option) : vertices_(vertices), vertex_normals_(vertex_normals), triangles_(triangles), triangle_normals_(triangle_normals), shade_option_(shade_option){}; const Eigen::Vector3f *vertices_; const Eigen::Vector3f *vertex_normals_; const int *triangles_; const Eigen::Vector3f *triangle_normals_; const RenderOption::MeshShadeOption shade_option_; __device__ thrust::tuple<Eigen::Vector3f, Eigen::Vector3f> operator()( size_t k) const { int i = k / 3; int vi = triangles_[k]; const auto &vertex = vertices_[vi]; return (shade_option_ == RenderOption::MeshShadeOption::FlatShade) ? thrust::make_tuple(vertex, triangle_normals_[i]) : thrust::make_tuple(vertex, vertex_normals_[vi]); } }; } // namespace bool NormalShader::Compile() { if (CompileShaders(normal_vertex_shader, NULL, normal_fragment_shader) == false) { PrintShaderWarning("Compiling shaders failed."); return false; } vertex_position_ = glGetAttribLocation(program_, "vertex_position"); vertex_normal_ = glGetAttribLocation(program_, "vertex_normal"); MVP_ = glGetUniformLocation(program_, "MVP"); V_ = glGetUniformLocation(program_, "V"); M_ = glGetUniformLocation(program_, "M"); return true; } void NormalShader::Release() { UnbindGeometry(true); ReleaseProgram(); } bool NormalShader::BindGeometry(const geometry::Geometry &geometry, const RenderOption &option, const ViewControl &view) { // If there is already geometry, we first unbind it. // We use GL_STATIC_DRAW. When geometry changes, we clear buffers and // rebind the geometry. Note that this approach is slow. If the geometry is // changing per frame, consider implementing a new ShaderWrapper using // GL_STREAM_DRAW, and replace UnbindGeometry() with Buffer Object // Streaming mechanisms. UnbindGeometry(); // Prepare data to be passed to GPU const size_t num_data_size = GetDataSize(geometry); // Create buffers and bind the geometry glGenBuffers(1, &vertex_position_buffer_); glBindBuffer(GL_ARRAY_BUFFER, vertex_position_buffer_); glBufferData(GL_ARRAY_BUFFER, num_data_size * sizeof(Eigen::Vector3f), 0, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); cudaSafeCall(cudaGraphicsGLRegisterBuffer(&cuda_graphics_resources_[0], vertex_position_buffer_, cudaGraphicsMapFlagsNone)); glGenBuffers(1, &vertex_normal_buffer_); glBindBuffer(GL_ARRAY_BUFFER, vertex_normal_buffer_); glBufferData(GL_ARRAY_BUFFER, num_data_size * sizeof(Eigen::Vector3f), 0, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); cudaSafeCall(cudaGraphicsGLRegisterBuffer(&cuda_graphics_resources_[1], vertex_normal_buffer_, cudaGraphicsMapFlagsNone)); Eigen::Vector3f *raw_points_ptr; Eigen::Vector3f *raw_normals_ptr; size_t n_bytes; cudaSafeCall(cudaGraphicsMapResources(2, cuda_graphics_resources_)); cudaSafeCall(cudaGraphicsResourceGetMappedPointer( (void **)&raw_points_ptr, &n_bytes, cuda_graphics_resources_[0])); cudaSafeCall(cudaGraphicsResourceGetMappedPointer( (void **)&raw_normals_ptr, &n_bytes, cuda_graphics_resources_[1])); thrust::device_ptr<Eigen::Vector3f> dev_points_ptr = thrust::device_pointer_cast(raw_points_ptr); thrust::device_ptr<Eigen::Vector3f> dev_normals_ptr = thrust::device_pointer_cast(raw_normals_ptr); if (PrepareBinding(geometry, option, view, dev_points_ptr, dev_normals_ptr) == false) { PrintShaderWarning("Binding failed when preparing data."); return false; } Unmap(2); bound_ = true; return true; } bool NormalShader::RenderGeometry(const geometry::Geometry &geometry, const RenderOption &option, const ViewControl &view) { if (PrepareRendering(geometry, option, view) == false) { PrintShaderWarning("Rendering failed during preparation."); return false; } glUseProgram(program_); glUniformMatrix4fv(MVP_, 1, GL_FALSE, view.GetMVPMatrix().data()); glUniformMatrix4fv(V_, 1, GL_FALSE, view.GetViewMatrix().data()); glUniformMatrix4fv(M_, 1, GL_FALSE, view.GetModelMatrix().data()); glEnableVertexAttribArray(vertex_position_); glBindBuffer(GL_ARRAY_BUFFER, vertex_position_buffer_); glVertexAttribPointer(vertex_position_, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(vertex_normal_); glBindBuffer(GL_ARRAY_BUFFER, vertex_normal_buffer_); glVertexAttribPointer(vertex_normal_, 3, GL_FLOAT, GL_FALSE, 0, NULL); glDrawArrays(draw_arrays_mode_, 0, draw_arrays_size_); glDisableVertexAttribArray(vertex_position_); glDisableVertexAttribArray(vertex_normal_); return true; } void NormalShader::UnbindGeometry(bool finalize) { if (bound_) { if (!finalize) { cudaSafeCall(cudaGraphicsUnregisterResource( cuda_graphics_resources_[0])); cudaSafeCall(cudaGraphicsUnregisterResource( cuda_graphics_resources_[1])); } glDeleteBuffers(1, &vertex_position_buffer_); glDeleteBuffers(1, &vertex_normal_buffer_); bound_ = false; } } bool NormalShaderForPointCloud::PrepareRendering( const geometry::Geometry &geometry, const RenderOption &option, const ViewControl &view) { if (geometry.GetGeometryType() != geometry::Geometry::GeometryType::PointCloud) { PrintShaderWarning("Rendering type is not geometry::PointCloud."); return false; } glEnable(GL_DEPTH_TEST); glDepthFunc(GLenum(option.GetGLDepthFunc())); glPointSize(GLfloat(option.point_size_)); return true; } bool NormalShaderForPointCloud::PrepareBinding( const geometry::Geometry &geometry, const RenderOption &option, const ViewControl &view, thrust::device_ptr<Eigen::Vector3f> &points, thrust::device_ptr<Eigen::Vector3f> &normals) { if (geometry.GetGeometryType() != geometry::Geometry::GeometryType::PointCloud) { PrintShaderWarning("Rendering type is not geometry::PointCloud."); return false; } const geometry::PointCloud &pointcloud = (const geometry::PointCloud &)geometry; if (pointcloud.HasPoints() == false) { PrintShaderWarning("Binding failed with empty pointcloud."); return false; } if (pointcloud.HasNormals() == false) { PrintShaderWarning("Binding failed with pointcloud with no normals."); return false; } thrust::copy(pointcloud.points_.begin(), pointcloud.points_.end(), points); thrust::copy(pointcloud.normals_.begin(), pointcloud.normals_.end(), normals); draw_arrays_mode_ = GL_POINTS; draw_arrays_size_ = GLsizei(pointcloud.points_.size()); return true; } size_t NormalShaderForPointCloud::GetDataSize( const geometry::Geometry &geometry) const { return ((const geometry::PointCloud &)geometry).points_.size(); } bool NormalShaderForTriangleMesh::PrepareRendering( const geometry::Geometry &geometry, const RenderOption &option, const ViewControl &view) { if (geometry.GetGeometryType() != geometry::Geometry::GeometryType::TriangleMesh) { PrintShaderWarning("Rendering type is not geometry::TriangleMesh."); return false; } if (option.mesh_show_back_face_) { glDisable(GL_CULL_FACE); } else { glEnable(GL_CULL_FACE); } glEnable(GL_DEPTH_TEST); glDepthFunc(GLenum(option.GetGLDepthFunc())); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if (option.mesh_show_wireframe_) { glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(1.0, 1.0); } else { glDisable(GL_POLYGON_OFFSET_FILL); } return true; } bool NormalShaderForTriangleMesh::PrepareBinding( const geometry::Geometry &geometry, const RenderOption &option, const ViewControl &view, thrust::device_ptr<Eigen::Vector3f> &points, thrust::device_ptr<Eigen::Vector3f> &normals) { if (geometry.GetGeometryType() != geometry::Geometry::GeometryType::TriangleMesh) { PrintShaderWarning("Rendering type is not geometry::TriangleMesh."); return false; } const geometry::TriangleMesh &mesh = (const geometry::TriangleMesh &)geometry; if (mesh.HasTriangles() == false) { PrintShaderWarning("Binding failed with empty triangle mesh."); return false; } if (mesh.HasTriangleNormals() == false || mesh.HasVertexNormals() == false) { PrintShaderWarning("Binding failed because mesh has no normals."); PrintShaderWarning("Call ComputeVertexNormals() before binding."); return false; } copy_trianglemesh_functor func( thrust::raw_pointer_cast(mesh.vertices_.data()), thrust::raw_pointer_cast(mesh.vertex_normals_.data()), (int *)(thrust::raw_pointer_cast(mesh.triangles_.data())), thrust::raw_pointer_cast(mesh.triangle_normals_.data()), option.mesh_shade_option_); thrust::transform( thrust::make_counting_iterator<size_t>(0), thrust::make_counting_iterator(mesh.triangles_.size() * 3), make_tuple_iterator(points, normals), func); draw_arrays_mode_ = GL_TRIANGLES; draw_arrays_size_ = GLsizei(mesh.triangles_.size() * 3); return true; } size_t NormalShaderForTriangleMesh::GetDataSize( const geometry::Geometry &geometry) const { return ((const geometry::TriangleMesh &)geometry).triangles_.size() * 3; }
the_stack
#include <stdlib.h> #include <stdio.h> #include <unordered_map> #include <vector> #include <cassert> #include <cuda_runtime.h> #include <cutensornet.h> #include <cutensor.h> #define HANDLE_ERROR(x) \ { const auto err = x; \ if( err != CUTENSORNET_STATUS_SUCCESS ) \ { printf("Error: %s in line %d\n", cutensornetGetErrorString(err), __LINE__); return err; } \ }; #define HANDLE_CUDA_ERROR(x) \ { const auto err = x; \ if( err != cudaSuccess ) \ { printf("Error: %s in line %d\n", cudaGetErrorString(err), __LINE__); return err; } \ }; struct GPUTimer { GPUTimer(cudaStream_t stream): stream_(stream) { cudaEventCreate(&start_); cudaEventCreate(&stop_); } ~GPUTimer() { cudaEventDestroy(start_); cudaEventDestroy(stop_); } void start() { cudaEventRecord(start_, stream_); } float seconds() { cudaEventRecord(stop_, stream_); cudaEventSynchronize(stop_); float time; cudaEventElapsedTime(&time, start_, stop_); return time * 1e-3; } private: cudaEvent_t start_, stop_; cudaStream_t stream_; }; int main() { const size_t cuTensornetVersion = cutensornetGetVersion(); printf("cuTensorNet-vers:%ld\n",cuTensornetVersion); cudaDeviceProp prop; int32_t deviceId = -1; HANDLE_CUDA_ERROR( cudaGetDevice(&deviceId) ); HANDLE_CUDA_ERROR( cudaGetDeviceProperties(&prop, deviceId) ); printf("===== device info ======\n"); printf("GPU-name:%s\n", prop.name); printf("GPU-clock:%d\n", prop.clockRate); printf("GPU-memoryClock:%d\n", prop.memoryClockRate); printf("GPU-nSM:%d\n", prop.multiProcessorCount); printf("GPU-major:%d\n", prop.major); printf("GPU-minor:%d\n", prop.minor); printf("========================\n"); typedef float floatType; cudaDataType_t typeData = CUDA_R_32F; cutensornetComputeType_t typeCompute = CUTENSORNET_COMPUTE_32F; printf("Include headers and define data types\n"); // Sphinx: #2 /********************** * Computing: D_{m,x,n,y} = A_{m,h,k,n} B_{u,k,h} C_{x,u,y} **********************/ constexpr int32_t numInputs = 3; // Create vector of modes std::vector<int32_t> modesA{'m','h','k','n'}; std::vector<int32_t> modesB{'u','k','h'}; std::vector<int32_t> modesC{'x','u','y'}; std::vector<int32_t> modesD{'m','x','n','y'}; // Extents std::unordered_map<int32_t, int64_t> extent; extent['m'] = 96; extent['n'] = 96; extent['u'] = 96; extent['h'] = 64; extent['k'] = 64; extent['x'] = 64; extent['y'] = 64; // Create a vector of extents for each tensor std::vector<int64_t> extentA; for (auto mode : modesA) extentA.push_back(extent[mode]); std::vector<int64_t> extentB; for (auto mode : modesB) extentB.push_back(extent[mode]); std::vector<int64_t> extentC; for (auto mode : modesC) extentC.push_back(extent[mode]); std::vector<int64_t> extentD; for (auto mode : modesD) extentD.push_back(extent[mode]); printf("Define network, modes, and extents\n"); // Sphinx: #3 /********************** * Allocating data **********************/ size_t elementsA = 1; for (auto mode : modesA) elementsA *= extent[mode]; size_t elementsB = 1; for (auto mode : modesB) elementsB *= extent[mode]; size_t elementsC = 1; for (auto mode : modesC) elementsC *= extent[mode]; size_t elementsD = 1; for (auto mode : modesD) elementsD *= extent[mode]; size_t sizeA = sizeof(floatType) * elementsA; size_t sizeB = sizeof(floatType) * elementsB; size_t sizeC = sizeof(floatType) * elementsC; size_t sizeD = sizeof(floatType) * elementsD; printf("Total memory: %.2f GiB\n", (sizeA + sizeB + sizeC + sizeD)/1024./1024./1024); void* rawDataIn_d[numInputs]; void* D_d; HANDLE_CUDA_ERROR(cudaMalloc((void**) &rawDataIn_d[0], sizeA)); HANDLE_CUDA_ERROR(cudaMalloc((void**) &rawDataIn_d[1], sizeB)); HANDLE_CUDA_ERROR(cudaMalloc((void**) &rawDataIn_d[2], sizeC)); HANDLE_CUDA_ERROR(cudaMalloc((void**) &D_d, sizeD)); floatType *A = (floatType*) malloc(sizeof(floatType) * elementsA); floatType *B = (floatType*) malloc(sizeof(floatType) * elementsB); floatType *C = (floatType*) malloc(sizeof(floatType) * elementsC); floatType *D = (floatType*) malloc(sizeof(floatType) * elementsD); if (A == NULL || B == NULL || C == NULL || D == NULL) { printf("Error: Host allocation of A or C.\n"); return -1; } /********************** * Allocate workspace **********************/ size_t freeMem, totalMem; HANDLE_CUDA_ERROR( cudaMemGetInfo(&freeMem, &totalMem )); uint64_t worksize = freeMem * 0.9; void *work = nullptr; HANDLE_CUDA_ERROR( cudaMalloc(&work, worksize) ); /******************* * Initialize data *******************/ for (uint64_t i = 0; i < elementsA; i++) A[i] = ((float) rand())/RAND_MAX; for (uint64_t i = 0; i < elementsB; i++) B[i] = ((float) rand())/RAND_MAX; for (uint64_t i = 0; i < elementsC; i++) C[i] = ((float) rand())/RAND_MAX; memset(D, 0, sizeof(floatType) * elementsD); HANDLE_CUDA_ERROR(cudaMemcpy(rawDataIn_d[0], A, sizeA, cudaMemcpyHostToDevice)); HANDLE_CUDA_ERROR(cudaMemcpy(rawDataIn_d[1], B, sizeB, cudaMemcpyHostToDevice)); HANDLE_CUDA_ERROR(cudaMemcpy(rawDataIn_d[2], C, sizeC, cudaMemcpyHostToDevice)); printf("Allocate memory for data and workspace, and initialize data.\n"); // Sphinx: #4 /************************* * cuTensorNet *************************/ cudaStream_t stream; cudaStreamCreate(&stream); cutensornetHandle_t handle; HANDLE_ERROR(cutensornetCreate(&handle)); const int32_t nmodeA = modesA.size(); const int32_t nmodeB = modesB.size(); const int32_t nmodeC = modesC.size(); const int32_t nmodeD = modesD.size(); /******************************* * Create Network Descriptor *******************************/ const int32_t* modesIn[] = {modesA.data(), modesB.data(), modesC.data()}; int32_t const numModesIn[] = {nmodeA, nmodeB, nmodeC}; const int64_t* extentsIn[] = {extentA.data(), extentB.data(), extentC.data()}; const int64_t* stridesIn[] = {NULL, NULL, NULL}; // strides are optional; if no stride is provided, then cuTensorNet assumes a generalized column-major data layout // Notice that pointers are allocated via cudaMalloc are aligned to 256 byte // boundaries by default; however here we're checking the pointer alignment explicitly // to demonstrate how one would check the alginment for arbitrary pointers. auto getMaximalPointerAlignment = [](const void* ptr) { const uint64_t ptrAddr = reinterpret_cast<uint64_t>(ptr); uint32_t alignment = 1; while(ptrAddr % alignment == 0 && alignment < 256) // at the latest we terminate once the alignment reached 256 bytes (we could be going, but any alignment larger or equal to 256 is equally fine) { alignment *= 2; } return alignment; }; const uint32_t alignmentsIn[] = {getMaximalPointerAlignment(rawDataIn_d[0]), getMaximalPointerAlignment(rawDataIn_d[1]), getMaximalPointerAlignment(rawDataIn_d[2])}; const uint32_t alignmentOut = getMaximalPointerAlignment(D_d); // setup tensor network cutensornetNetworkDescriptor_t descNet; HANDLE_ERROR (cutensornetCreateNetworkDescriptor(handle, numInputs, numModesIn, extentsIn, stridesIn, modesIn, alignmentsIn, nmodeD, extentD.data(), /*stridesOut = */NULL, modesD.data(), alignmentOut, typeData, typeCompute, &descNet)); printf("Initialize the cuTensorNet library and create a network descriptor.\n"); // Sphinx: #5 /******************************* * Find "optimal" contraction order and slicing *******************************/ cutensornetContractionOptimizerConfig_t optimizerConfig; HANDLE_ERROR (cutensornetCreateContractionOptimizerConfig(handle, &optimizerConfig)); // Set the value of the partitioner imbalance factor, if desired int imbalance_factor = 30; HANDLE_ERROR(cutensornetContractionOptimizerConfigSetAttribute( handle, optimizerConfig, CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_GRAPH_IMBALANCE_FACTOR, &imbalance_factor, sizeof(imbalance_factor))); cutensornetContractionOptimizerInfo_t optimizerInfo; HANDLE_ERROR (cutensornetCreateContractionOptimizerInfo(handle, descNet, &optimizerInfo)); HANDLE_ERROR (cutensornetContractionOptimize(handle, descNet, optimizerConfig, worksize, optimizerInfo)); int64_t numSlices = 0; HANDLE_ERROR( cutensornetContractionOptimizerInfoGetAttribute( handle, optimizerInfo, CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_NUM_SLICES, &numSlices, sizeof(numSlices))); assert(numSlices > 0); printf("Find an optimized contraction path with cuTensorNet optimizer.\n"); // Sphinx: #6 /******************************* * Initialize all pair-wise contraction plans (for cuTENSOR) *******************************/ cutensornetContractionPlan_t plan; cutensornetWorkspaceDescriptor_t workDesc; HANDLE_ERROR(cutensornetCreateWorkspaceDescriptor(handle, &workDesc)); uint64_t requiredWorkspaceSize = 0; HANDLE_ERROR(cutensornetWorkspaceComputeSizes(handle, descNet, optimizerInfo, workDesc)); HANDLE_ERROR(cutensornetWorkspaceGetSize(handle, workDesc, CUTENSORNET_WORKSIZE_PREF_MIN, CUTENSORNET_MEMSPACE_DEVICE, &requiredWorkspaceSize)); if (worksize < requiredWorkspaceSize) { printf("Not enough workspace memory is available."); } else { HANDLE_ERROR (cutensornetWorkspaceSet(handle, workDesc, CUTENSORNET_MEMSPACE_DEVICE, work, worksize)); HANDLE_ERROR( cutensornetCreateContractionPlan(handle, descNet, optimizerInfo, workDesc, &plan) ); /******************************* * Optional: Auto-tune cuTENSOR's cutensorContractionPlan to pick the fastest kernel *******************************/ cutensornetContractionAutotunePreference_t autotunePref; HANDLE_ERROR(cutensornetCreateContractionAutotunePreference(handle, &autotunePref)); const int numAutotuningIterations = 5; // may be 0 HANDLE_ERROR(cutensornetContractionAutotunePreferenceSetAttribute( handle, autotunePref, CUTENSORNET_CONTRACTION_AUTOTUNE_MAX_ITERATIONS, &numAutotuningIterations, sizeof(numAutotuningIterations))); // modify the plan again to find the best pair-wise contractions HANDLE_ERROR(cutensornetContractionAutotune(handle, plan, rawDataIn_d, D_d, workDesc, autotunePref, stream)); HANDLE_ERROR(cutensornetDestroyContractionAutotunePreference(autotunePref)); printf("Create a contraction plan for cuTENSOR and optionally auto-tune it.\n"); // Sphinx: #7 /********************** * Run **********************/ GPUTimer timer{stream}; double minTimeCUTENSOR = 1e100; const int numRuns = 3; // to get stable perf results for (int i=0; i < numRuns; ++i) { cudaMemcpy(D_d, D, sizeD, cudaMemcpyHostToDevice); // restore output cudaDeviceSynchronize(); /* * Contract over all slices. * * A user may choose to parallelize this loop across multiple devices. * (Note, however, that as of cuTensorNet v1.0.0 the contraction must * start from slice 0, see the cutensornetContraction documentation at * https://docs.nvidia.com/cuda/cuquantum/cutensornet/api/functions.html#cutensornetcontraction ) */ for(int64_t sliceId=0; sliceId < numSlices; ++sliceId) { timer.start(); HANDLE_ERROR(cutensornetContraction(handle, plan, rawDataIn_d, D_d, workDesc, sliceId, stream)); // Synchronize and measure timing auto time = timer.seconds(); minTimeCUTENSOR = (minTimeCUTENSOR < time) ? minTimeCUTENSOR : time; } } printf("Contract the network, each slice uses the same contraction plan.\n"); /*************************/ double flops = -1; HANDLE_ERROR( cutensornetContractionOptimizerInfoGetAttribute( handle, optimizerInfo, CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_FLOP_COUNT, &flops, sizeof(flops))); printf("numSlices: %ld\n", numSlices); printf("%.2f ms / slice\n", minTimeCUTENSOR * 1000.f); printf("%.2f GFLOPS/s\n", flops/1e9/minTimeCUTENSOR ); } HANDLE_ERROR(cutensornetDestroy(handle)); HANDLE_ERROR(cutensornetDestroyNetworkDescriptor(descNet)); HANDLE_ERROR(cutensornetDestroyContractionPlan(plan)); HANDLE_ERROR(cutensornetDestroyContractionOptimizerConfig(optimizerConfig)); HANDLE_ERROR(cutensornetDestroyContractionOptimizerInfo(optimizerInfo)); HANDLE_ERROR(cutensornetDestroyWorkspaceDescriptor(workDesc)); if (A) free(A); if (B) free(B); if (C) free(C); if (D) free(D); if (rawDataIn_d[0]) cudaFree(rawDataIn_d[0]); if (rawDataIn_d[1]) cudaFree(rawDataIn_d[1]); if (rawDataIn_d[2]) cudaFree(rawDataIn_d[2]); if (D_d) cudaFree(D_d); if (work) cudaFree(work); printf("Free resource and exit.\n"); return 0; }
the_stack
#include <cuda_runtime.h> #include <cuComplex.h> #include <complex.h> #include <math.h> #include <stdio.h> #include <sys/time.h> #define SINC_SUB 8192 #define SINC_LEN 8 #define SINC_HALF (SINC_LEN/2) #define SINC_ONE (SINC_LEN+1) #define IDX1D(i,j,w) (((i)*(w))+(j)) #define modulo_f(a,b) fmod(fmod(a,b)+(b),(b)) struct InputData { cuFloatComplex *imgIn; cuFloatComplex *imgOut; float *residAz; float *residRg; double *azOffPoly; double *rgOffPoly; double *dopPoly; double *azCarrierPoly; double *rgCarrierPoly; float *fintp; }; __constant__ double ind[6]; __constant__ int ini[8]; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // GPU Helper Functions // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Data usage: 8 floats/pointers, 2 ints -- 72 bytes/call __device__ double evalPolyAt(double *polyArr, double azi, double rng) { // C-style eval method of Poly2d (adjusted to work with the array-format Poly2d where: // polyArr[0] = azimuthOrder // polyArr[1] = rangeOrder // polyArr[2] = azimuthMean // polyArr[3] = rangeMean // polyArr[4] = azimuthNorm // polyArr[5] = rangeNorm // polyArr[6...] = coeffs (len ([0]+1)*([1]+1)) // Therefore we can guarantee that polyArr has at least 7 elements, and intuitively stores its own length using the orders double val, scalex, scaley, xval, yval; int i, j; val = 0.; scaley = 1.; xval = (rng - polyArr[3]) / polyArr[5]; yval = (azi - polyArr[2]) / polyArr[4]; for (i=0; i<=polyArr[0]; i++,scaley*=yval) { scalex = 1.; for (j=0; j<=polyArr[1]; j++,scalex*=xval) { val += scalex * scaley * polyArr[IDX1D(i,j,int(polyArr[1])+1)+6]; } } return val; } __global__ void removeCarrier(struct InputData inData) { // remove the carriers from input slc // thread id, as the pixel index for the input image int pix = blockDim.x * blockIdx.x + threadIdx.x; // check the thread range // ini[0] - inLength // ini[1] - inWidth if(pix >= ini[0]*ini[1]) return; // get pixel location along azimuth/range int idxi = pix/ini[1]; int idxj = pix%ini[1]; // the poly uses fortran 1-indexing double r_i = idxi +1; double r_j = idxj +1; // get the phase shift due to carriers double ph = evalPolyAt(inData.rgCarrierPoly, r_i, r_j) + evalPolyAt(inData.azCarrierPoly, r_i, r_j); ph = modulo_f(ph, 2.*M_PI); // remove the phase shift from the data cuFloatComplex cval = cuCmulf(inData.imgIn[pix], make_cuFloatComplex(cosf(ph), -sinf(ph))); // assign the new value inData.imgIn[pix] = cval; // all done } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // GPU Main Kernel // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Data Usage: 15 pointers/floats, 5 ints, 1 bool -- 144 bytes/call (assuming 1 bool ==> 1 int) // Add call to sinfc_interp (100 bytes/call) -- 244 bytes/call (for funsies let's assume ~250 bytes/call) // NOTE: We ignore calls to evalPolyAt sinfce they have less // data usage and therefore do not really matter for // max data usage __global__ void GPUResamp(struct InputData inData) { // Main GPU ResampSlc kernel, slightly modified from original algorithm to save significant space int pix = blockDim.x * blockIdx.x + threadIdx.x; // check within outWidth*LINES_PER_TILE if (pix >= (ini[2] * ini[6])) return; // index along row/azimuth int idxi = (pix / ini[2]) + ini[4]; // index along width/range int idxj = (pix % ini[2]); // offset // note that the polys use 1-indexing in Fortran code double ao = evalPolyAt(inData.azOffPoly, idxi+1, idxj+1) + inData.residAz[pix]; double ro = evalPolyAt(inData.rgOffPoly, idxi+1, idxj+1) + inData.residRg[pix]; // azimuth coordinate int ka = floor(idxi + ao); double fraca = idxi + ao - ka; // range coordinate int kr = floor(idxj + ro); double fracr = idxj + ro - kr; // check whether the pixel is out of the interpolation region if ((ka < SINC_HALF) || ( ka >= (ini[0]-SINC_HALF)) || (kr < SINC_HALF) || (kr >= (ini[1]-SINC_HALF))) { // out of range inData.imgOut[pix] = make_cuFloatComplex(0., 0.); return; } // in range, continue // evaluate the doppler phase at the secondary coordinate double dop = evalPolyAt(inData.dopPoly, idxi+1+ao, idxj+1+ro); // phase corrections to be added later double ph = (dop * fraca) + evalPolyAt(inData.rgCarrierPoly, idxi+1+ao, idxj+1+ro) + evalPolyAt(inData.azCarrierPoly, idxi+1+ao, idxj+1+ro); // if flatten if (ini[7] == 1) ph = ph + ((4.*(M_PI/ind[0]))*((ind[2]-ind[3])+(idxj*(ind[4]-ind[5]))+(ro*ind[4]))) +((4.*M_PI*(ind[3]+(idxj*ind[5])))*((1./ind[1])-(1./ind[0]))); ph = modulo_f(ph, 2.*M_PI); // temp variable to keep track of the interpolated value cuFloatComplex cval = make_cuFloatComplex(0.,0.); // get the indices in the sinfc_coef of the fractional parts int ifraca = int(fraca*SINC_SUB); int ifracr = int(fracr*SINC_SUB); // weight for sinfc interp coefficients float weightsum = 0.; // iterate over the interpolation zone, e.g. [-3, 4] x [-3, 4] for SINC_LEN = 8 for (int i=-SINC_HALF+1; i<=SINC_HALF; i++) { cuFloatComplex cdop = make_cuFloatComplex(cosf(i*dop), -sinf(i*dop)); for (int j=-SINC_HALF+1; j<=SINC_HALF; j++) { float weight = inData.fintp[IDX1D(ifraca,SINC_HALF-i,SINC_LEN)] *inData.fintp[IDX1D(ifracr,SINC_HALF-j,SINC_LEN)]; // correct the doppler phase here cuFloatComplex cin = cuCmulf(inData.imgIn[IDX1D(i+ka,j+kr,ini[1])], cdop); cval = cuCaddf(cval, make_cuFloatComplex(cuCrealf(cin)*weight, cuCimagf(cin)*weight)); weightsum += weight; } } // normalize cval = make_cuFloatComplex(cuCrealf(cval)/weightsum, cuCimagf(cval)/weightsum); // phase correction cval = cuCmulf(cval, make_cuFloatComplex(cosf(ph), sinf(ph))); // assign and return inData.imgOut[pix] = cval; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // CPU Helper Functions // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * double cpuSecond() { struct timeval tp; gettimeofday(&tp,NULL); return (double(tp.tv_sec) + double(tp.tv_usec)*1.e-6); } void checkKernelErrors() { cudaError_t errSync = cudaGetLastError(); cudaError_t errAsync = cudaDeviceSynchronize(); if (errSync != cudaSuccess) printf("\nSync kernel error: %s\n", cudaGetErrorString(errSync)); if (errAsync != cudaSuccess) printf("\nAsync kernel error: %s\n", cudaGetErrorString(errAsync)); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Main CPU Function // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * void runGPUResamp(double *h_inpts_dbl, int *h_inpts_int, void *imgIn, void *imgOut, float *residAz, float *residRg, double *azOffPoly, double *rgOffPoly, double *dopPoly, double *azCarrierPoly, double *rgCarrierPoly, float *fintp) { /* * * * * * * * * * * * * * * * * * * * * Input mapping - * * Double 0 - wvl * Double 1 - refwvl * Double 2 - r0 * Double 3 - refr0 * Double 4 - slr * Double 5 - refslr * * Int 0 - inLength * Int 1 - inWidth * Int 2 - outWidth * Int 3 - firstImageRow * Int 4 - firstTileRow * Int 5 - nRowsInBlock * Int 6 - LINES_PER_TILE * Int 7 - flatten * * * * * * * * * * * * * * * * * * * * */ // Casting input/output images to native cuFloatComplex type from complex<float> cuFloatComplex *h_imgIn = (cuFloatComplex *)imgIn; cuFloatComplex *h_imgOut = (cuFloatComplex *)imgOut; // Create handles for device copies of inputs cuFloatComplex *d_imgIn, *d_imgOut; float *d_residAz, *d_residRg; double *d_azOffPoly, *d_rgOffPoly, *d_dopPoly, *d_azCarrierPoly, *d_rgCarrierPoly; float *d_fintp; double startRun, endRun, startKernel, endKernel; struct InputData inData; printf("\n Initializing GPU ResampSlc\n"); cudaSetDevice(0); startRun = cpuSecond(); printf(" Allocating initial memory... "); fflush(stdout); int nInPix = h_inpts_int[5] * h_inpts_int[1]; int nOutPix = h_inpts_int[6] * h_inpts_int[2]; int nResidAzPix = 0; if (residAz != 0) nResidAzPix = h_inpts_int[6] * h_inpts_int[2]; int nResidRgPix = 0; if (residRg != 0) nResidRgPix = h_inpts_int[6] * h_inpts_int[2]; int nAzOffPix = ((azOffPoly[0]+1) * (azOffPoly[1]+1)) + 6; // [0] and [1] of the Poly2d arrays hold the az/rg orders int nRgOffPix = ((rgOffPoly[0]+1) * (rgOffPoly[1]+1)) + 6; int nDopPix = ((dopPoly[0]+1) * (dopPoly[1]+1)) + 6; int nAzCarryPix = ((azCarrierPoly[0]+1) * (azCarrierPoly[1]+1)) + 6; int nRgCarryPix = ((rgCarrierPoly[0]+1) * (rgCarrierPoly[1]+1)) + 6; size_t nb_in = nInPix * sizeof(cuFloatComplex); size_t nb_out = nOutPix * sizeof(cuFloatComplex); size_t nb_rsdAz = nResidAzPix * sizeof(float); size_t nb_rsdRg = nResidRgPix * sizeof(float); size_t nb_azOff = nAzOffPix * sizeof(double); size_t nb_rgOff = nRgOffPix * sizeof(double); size_t nb_dop = nDopPix * sizeof(double); size_t nb_azCarry = nAzCarryPix * sizeof(double); size_t nb_rgCarry = nRgCarryPix * sizeof(double); cudaMalloc((cuFloatComplex**)&d_imgIn, nb_in); cudaMalloc((cuFloatComplex**)&d_imgOut, nb_out); if (residAz != 0) cudaMalloc((float**)&d_residAz, nb_rsdAz); if (residRg != 0) cudaMalloc((float**)&d_residRg, nb_rsdRg); cudaMalloc((double**)&d_azOffPoly, nb_azOff); cudaMalloc((double**)&d_rgOffPoly, nb_rgOff); cudaMalloc((double**)&d_dopPoly, nb_dop); cudaMalloc((double**)&d_azCarrierPoly, nb_azCarry); cudaMalloc((double**)&d_rgCarrierPoly, nb_rgCarry); cudaMalloc((float**)&d_fintp, (SINC_LEN*SINC_SUB*sizeof(float))); printf("Done.\n Copying data to GPU... "); fflush(stdout); startKernel = cpuSecond(); cudaMemcpy(d_imgIn, h_imgIn, nb_in, cudaMemcpyHostToDevice); if (residAz != 0) cudaMemcpy(d_residAz, residAz, nb_rsdAz, cudaMemcpyHostToDevice); if (residRg != 0) cudaMemcpy(d_residRg, residRg, nb_rsdRg, cudaMemcpyHostToDevice); cudaMemcpy(d_azOffPoly, azOffPoly, nb_azOff, cudaMemcpyHostToDevice); cudaMemcpy(d_rgOffPoly, rgOffPoly, nb_rgOff, cudaMemcpyHostToDevice); cudaMemcpy(d_dopPoly, dopPoly, nb_dop, cudaMemcpyHostToDevice); cudaMemcpy(d_azCarrierPoly, azCarrierPoly, nb_azCarry, cudaMemcpyHostToDevice); cudaMemcpy(d_rgCarrierPoly, rgCarrierPoly, nb_rgCarry, cudaMemcpyHostToDevice); cudaMemcpy(d_fintp, fintp, (SINC_LEN*SINC_SUB*sizeof(float)), cudaMemcpyHostToDevice); cudaMemcpyToSymbol(ind, h_inpts_dbl, (6*sizeof(double))); cudaMemcpyToSymbol(ini, h_inpts_int, (8*sizeof(int))); cudaMemset(d_imgOut, 0, nb_out); endKernel = cpuSecond(); printf("Done. (%f s.)\n", (endKernel-startKernel)); printf(" Running GPU ResampSlc... "); fflush(stdout); startKernel = cpuSecond(); inData.imgIn = d_imgIn; inData.imgOut = d_imgOut; inData.residAz = 0; if (residAz != 0) inData.residAz = d_residAz; inData.residRg = 0; if (residRg != 0) inData.residRg = d_residRg; inData.azOffPoly = d_azOffPoly; inData.rgOffPoly = d_rgOffPoly; inData.dopPoly = d_dopPoly; inData.azCarrierPoly = d_azCarrierPoly; inData.rgCarrierPoly = d_rgCarrierPoly; inData.fintp = d_fintp; // remove carriers from the input image int threads = 1024; int blocks = (nInPix + threads-1) / threads; removeCarrier<<<blocks, threads>>>(inData); checkKernelErrors(); // resample blocks = (nOutPix + threads -1) / threads; GPUResamp <<<blocks, threads>>>(inData); checkKernelErrors(); endKernel = cpuSecond(); printf("Done. (%f s.)\n", (endKernel-startKernel)); printf(" Copying memory back to host... "); fflush(stdout); startKernel = cpuSecond(); cudaMemcpy(h_imgOut, d_imgOut, nb_out, cudaMemcpyDeviceToHost); endKernel = cpuSecond(); endRun = cpuSecond(); printf("Done. (%f s.)\n", (endKernel-startKernel)); printf(" Finished GPU ResampSlc in %f s.\n", (endRun-startRun)); printf(" Cleaning device memory and returning to main ResampSlc function...\n"); cudaFree(d_imgIn); cudaFree(d_imgOut); if (residAz != 0) cudaFree(d_residAz); if (residRg != 0) cudaFree(d_residRg); cudaFree(d_azOffPoly); cudaFree(d_rgOffPoly); cudaFree(d_dopPoly); cudaFree(d_azCarrierPoly); cudaFree(d_rgCarrierPoly); cudaFree(d_fintp); cudaDeviceReset(); printf(" Exiting GPU ResampSlc\n\n"); }
the_stack
#if(__CUDACC_VER_MAJOR__<9 || (__CUDACC_VER_MAJOR__==9 && __CUDACC_VER_MINOR__<2)) #if __CUDA_ARCH__>=700 #error CGBN requires CUDA version 9.2 or above on Volta #endif #endif /**************************************************************************************************************** * cgbn_context_t implementation for CUDA ****************************************************************************************************************/ template<uint32_t tpi, class params> __device__ __forceinline__ cgbn_context_t<tpi, params>::cgbn_context_t() : _monitor(cgbn_no_checks), _report(NULL), _instance(0xFFFFFFFF) { } template<uint32_t tpi, class params> __device__ __forceinline__ cgbn_context_t<tpi, params>::cgbn_context_t(cgbn_monitor_t monitor) : _monitor(monitor), _report(NULL), _instance(0xFFFFFFFF) { if(monitor!=cgbn_no_checks) { if(tpi!=32 && tpi!=16 && tpi!=8 && tpi!=4) report_error(cgbn_unsupported_threads_per_instance); if(params::TPB!=0 && params::TPB!=blockDim.x) report_error(cgbn_threads_per_block_mismatch); if(params::CONSTANT_TIME) report_error(cgbn_unsupported_operation); } } template<uint32_t tpi, class params> __device__ __forceinline__ cgbn_context_t<tpi, params>::cgbn_context_t(cgbn_monitor_t monitor, cgbn_error_report_t *report) : _monitor(monitor), _report(report), _instance(0xFFFFFFFF) { if(monitor!=cgbn_no_checks) { if(tpi!=32 && tpi!=16 && tpi!=8 && tpi!=4) report_error(cgbn_unsupported_threads_per_instance); if(params::TPB!=0 && params::TPB!=blockDim.x) report_error(cgbn_threads_per_block_mismatch); if(params::CONSTANT_TIME) report_error(cgbn_unsupported_operation); } } template<uint32_t tpi, class params> __device__ __forceinline__ cgbn_context_t<tpi, params>::cgbn_context_t(cgbn_monitor_t monitor, cgbn_error_report_t *report, uint32_t instance) : _monitor(monitor), _report(report), _instance(instance) { if(monitor!=cgbn_no_checks) { if(tpi!=32 && tpi!=16 && tpi!=8 && tpi!=4) report_error(cgbn_unsupported_threads_per_instance); if(params::TPB!=0 && params::TPB!=blockDim.x) report_error(cgbn_threads_per_block_mismatch); if(params::CONSTANT_TIME) report_error(cgbn_unsupported_operation); } } template<uint32_t tpi, class params> __device__ __forceinline__ bool cgbn_context_t<tpi, params>::check_errors() const { return _monitor!=cgbn_no_checks; } template<uint32_t tpi, class params> __device__ __noinline__ void cgbn_context_t<tpi, params>::report_error(cgbn_error_t error) const { if((threadIdx.x & tpi-1)==0) { if(_report!=NULL) { if(atomicCAS((uint32_t *)&(_report->_error), (uint32_t)cgbn_no_error, (uint32_t)error)==cgbn_no_error) { _report->_instance=_instance; _report->_threadIdx=threadIdx; _report->_blockIdx=blockIdx; } } if(_monitor==cgbn_print_monitor) { switch(_report->_error) { case cgbn_unsupported_threads_per_instance: printf("cgbn error: unsupported threads per instance\n"); break; case cgbn_unsupported_size: printf("cgbn error: unsupported size\n"); break; case cgbn_unsupported_limbs_per_thread: printf("cgbn error: unsupported limbs per thread\n"); break; case cgbn_unsupported_operation: printf("cgbn error: unsupported operation\n"); break; case cgbn_threads_per_block_mismatch: printf("cgbn error: TPB does not match blockDim.x\n"); break; case cgbn_threads_per_instance_mismatch: printf("cgbn errpr: TPI does not match env_t::TPI\n"); break; case cgbn_division_by_zero_error: printf("cgbn error: division by zero on instance\n"); break; case cgbn_division_overflow_error: printf("cgbn error: division overflow on instance\n"); break; case cgbn_invalid_montgomery_modulus_error: printf("cgbn error: division invalid montgomery modulus\n"); break; case cgbn_modulus_not_odd_error: printf("cgbn error: invalid modulus (it must be odd)\n"); break; case cgbn_inverse_does_not_exist_error: printf("cgbn error: inverse does not exist\n"); break; default: printf("cgbn error: unknown error reported by instance\n"); break; } } else if(_monitor==cgbn_halt_monitor) { __trap(); } } } /* template<uint32_t threads_per_instance, uint32_t threads_per_block> template<uint32_t bits> __device__ __forceinline__ cgbn_env_t<cgbn_context_t, bits> cgbn_context_t<threads_per_instance, threads_per_block>::env() { cgbn_env_t<cgbn_context_t, bits> env(this); return env; } template<uint32_t threads_per_instance, uint32_t threads_per_block> template<typename env_t> __device__ __forceinline__ cgbn_env_t<cgbn_context_t, env_t::_bits> cgbn_context_t<threads_per_instance, threads_per_block>::env() { return env<env_t::_bits>(); } */ /**************************************************************************************************************** * cgbn_env_t implementation for CUDA ****************************************************************************************************************/ /* constructor */ template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ cgbn_env_t<context_t, bits, syncable>::cgbn_env_t(const context_t &context) : _context(context) { if(_context.check_errors()) { if(bits==0 || (bits & 0x1F)!=0) _context.report_error(cgbn_unsupported_size); } } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::set(cgbn_t &r, const cgbn_t &a) const { cgbn::core_t<cgbn_env_t>::set(r._limbs, a._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::swap(cgbn_t &r, cgbn_t &a) const { cgbn::core_t<cgbn_env_t>::swap(r._limbs, a._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> template<class source_cgbn_t> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::set(cgbn_t &r, const source_cgbn_t &source) const { uint32_t sync, group_thread=threadIdx.x & TPI-1; uint32_t source_thread=0, source_limb=0, value; // TPI and TPB must match. TPB matches automatically if(_context.check_errors()) { if(TPI!=source_cgbn_t::parent_env_t::TPI) { _context.report_error(cgbn_threads_per_instance_mismatch); return; } } sync=cgbn::core_t<cgbn_env_t>::sync_mask(); cgbn::mpzero<LIMBS>(r._limbs); #pragma nounroll for(int32_t index=0;index<BITS/32;index++) { #pragma unroll for(int32_t limb=0;limb<source_cgbn_t::parent_env_t::LIMBS;limb++) if(limb==source_limb) value=source._limbs[limb]; value=__shfl_sync(sync, value, source_thread, TPI); #pragma unroll for(int32_t limb=0;limb<LIMBS;limb++) if(group_thread*LIMBS+limb==index) r._limbs[limb]=value; source_limb++; if(source_limb==source_cgbn_t::parent_env_t::LIMBS) { source_limb=0; if(++source_thread==TPI) break; } } } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::extract_bits(cgbn_t &r, const cgbn_t &a, const uint32_t start, const uint32_t len) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; uint32_t local_len=len; if(start>=BITS) { cgbn::mpzero<LIMBS>(r._limbs); return; } local_len=cgbn::umin(local_len, BITS-start); core::rotate_right(r._limbs, a._limbs, start); core::bitwise_mask_and(r._limbs, r._limbs, local_len); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::insert_bits(cgbn_t &r, const cgbn_t &a, const uint32_t start, const uint32_t len, const cgbn_t &value) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; uint32_t local_len=len; uint32_t mask[LIMBS], temp[LIMBS]; if(start>=BITS) { cgbn::mpset<LIMBS>(r._limbs, a._limbs); return; } local_len=cgbn::umin(local_len, BITS-start); core::rotate_left(temp, value._limbs, start); core::bitwise_mask_copy(mask, start+local_len); core::bitwise_mask_xor(mask, mask, start); core::bitwise_select(r._limbs, a._limbs, temp, mask); } /* ui32 routines */ template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ uint32_t cgbn_env_t<context_t, bits, syncable>::get_ui32(const cgbn_t &a) const { return cgbn::core_t<cgbn_env_t>::get_ui32(a._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::set_ui32(cgbn_t &r, const uint32_t value) const { cgbn::core_t<cgbn_env_t>::set_ui32(r._limbs, value); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ int32_t cgbn_env_t<context_t, bits, syncable>::add_ui32(cgbn_t &r, const cgbn_t &a, const uint32_t add) const { return cgbn::core_t<cgbn_env_t>::add_ui32(r._limbs, a._limbs, add); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ int32_t cgbn_env_t<context_t, bits, syncable>::sub_ui32(cgbn_t &r, const cgbn_t &a, const uint32_t sub) const { return cgbn::core_t<cgbn_env_t>::sub_ui32(r._limbs, a._limbs, sub); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ uint32_t cgbn_env_t<context_t, bits, syncable>::mul_ui32(cgbn_t &r, const cgbn_t &a, const uint32_t mul) const { return cgbn::core_t<cgbn_env_t>::mul_ui32(r._limbs, a._limbs, mul); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ uint32_t cgbn_env_t<context_t, bits, syncable>::div_ui32(cgbn_t &r, const cgbn_t &a, const uint32_t div) const { if(div==0) { if(_context.check_errors()) _context.report_error(cgbn_division_by_zero_error); return 0; } return cgbn::core_singleton_t<cgbn_env_t, LIMBS>::div_ui32(r._limbs, a._limbs, div); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ uint32_t cgbn_env_t<context_t, bits, syncable>::rem_ui32(const cgbn_t &a, const uint32_t div) const { if(div==0) { if(_context.check_errors()) _context.report_error(cgbn_division_by_zero_error); return 0; } return cgbn::core_singleton_t<cgbn_env_t, LIMBS>::rem_ui32(a._limbs, div); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ bool cgbn_env_t<context_t, bits, syncable>::equals_ui32(const cgbn_t &a, const uint32_t value) const { return cgbn::core_t<cgbn_env_t>::equals_ui32(a._limbs, value); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ int32_t cgbn_env_t<context_t, bits, syncable>::compare_ui32(const cgbn_t &a, const uint32_t value) const { return cgbn::core_t<cgbn_env_t>::compare_ui32(a._limbs, value); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ uint32_t cgbn_env_t<context_t, bits, syncable>::extract_bits_ui32(const cgbn_t &a, const uint32_t start, const uint32_t len) const { return cgbn::core_t<cgbn_env_t>::extract_bits_ui32(a._limbs, start, len); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::insert_bits_ui32(cgbn_t &r, const cgbn_t &a, const uint32_t start, const uint32_t len, const uint32_t value) const { cgbn::core_t<cgbn_env_t>::insert_bits_ui32(r._limbs, a._limbs, start, len, value); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ uint32_t cgbn_env_t<context_t, bits, syncable>::binary_inverse_ui32(const uint32_t x) const { if(_context.check_errors()) { if((x & 0x01)==0) { _context.report_error(cgbn_inverse_does_not_exist_error); return 0; } } return cgbn::ubinary_inverse(x); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ uint32_t cgbn_env_t<context_t, bits, syncable>::gcd_ui32(const cgbn_t &a, const uint32_t value) const { if(value==0) return 0; return cgbn::ugcd(value, rem_ui32(a, value)); } /* bn arithmetic routines */ template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ int32_t cgbn_env_t<context_t, bits, syncable>::add(cgbn_t &r, const cgbn_t &a, const cgbn_t &b) const { return cgbn::core_t<cgbn_env_t>::add(r._limbs, a._limbs, b._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ int32_t cgbn_env_t<context_t, bits, syncable>::sub(cgbn_t &r, const cgbn_t &a, const cgbn_t &b) const { return cgbn::core_t<cgbn_env_t>::sub(r._limbs, a._limbs, b._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ int32_t cgbn_env_t<context_t, bits, syncable>::negate(cgbn_t &r, const cgbn_t &a) const { return cgbn::core_t<cgbn_env_t>::negate(r._limbs, a._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::mul(cgbn_t &r, const cgbn_t &a, const cgbn_t &b) const { uint32_t add[LIMBS]; cgbn::mpzero<LIMBS>(add); cgbn::core_singleton_t<cgbn_env_t, LIMBS>::mul(r._limbs, a._limbs, b._limbs, add); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::mul_high(cgbn_t &r, const cgbn_t &a, const cgbn_t &b) const { uint32_t add[LIMBS]; cgbn::mpzero<LIMBS>(add); cgbn::core_singleton_t<cgbn_env_t, LIMBS>::mul_high(r._limbs, a._limbs, b._limbs, add); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::sqr(cgbn_t &r, const cgbn_t &a) const { uint32_t add[LIMBS]; cgbn::mpzero<LIMBS>(add); cgbn::core_singleton_t<cgbn_env_t, LIMBS>::mul(r._limbs, a._limbs, a._limbs, add); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::sqr_high(cgbn_t &r, const cgbn_t &a) const { uint32_t add[LIMBS]; cgbn::mpzero<LIMBS>(add); cgbn::core_singleton_t<cgbn_env_t, LIMBS>::mul_high(r._limbs, a._limbs, a._limbs, add); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::div(cgbn_t &q, const cgbn_t &num, const cgbn_t &denom) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t num_low[LIMBS], num_high[LIMBS], denom_local[LIMBS]; uint32_t shift, numthreads; if(_context.check_errors()) { if(equals_ui32(denom, 0)) { _context.report_error(cgbn_division_by_zero_error); return; } } // division of padded values is the same as division of unpadded valuess shift=core::clz(denom._limbs); core::rotate_left(denom_local, denom._limbs, shift); core::rotate_left(num_low, num._limbs, shift); core::bitwise_mask_and(num_high, num_low, shift); numthreads=TPI-core::clzt(num_high); singleton::div_wide(q._limbs, num_low, num_high, denom_local, numthreads); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::rem(cgbn_t &r, const cgbn_t &num, const cgbn_t &denom) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t num_low[LIMBS], num_high[LIMBS], denom_local[LIMBS]; uint32_t shift, numthreads; if(_context.check_errors()) { if(equals_ui32(denom, 0)) { _context.report_error(cgbn_division_by_zero_error); return; } } // division of padded values is the same as division of unpadded valuess shift=core::clz(denom._limbs); core::rotate_left(denom_local, denom._limbs, shift); core::rotate_left(num_low, num._limbs, shift); core::bitwise_mask_and(num_high, num_low, shift); core::bitwise_xor(num_low, num_low, num_high); numthreads=TPI-core::clzt(num_high); singleton::rem_wide(r._limbs, num_low, num_high, denom_local, numthreads); core::rotate_right(r._limbs, r._limbs, shift); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::div_rem(cgbn_t &q, cgbn_t &r, const cgbn_t &num, const cgbn_t &denom) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t num_low[LIMBS], num_high[LIMBS], denom_local[LIMBS]; uint32_t shift, numthreads; if(_context.check_errors()) { if(equals_ui32(denom, 0)) { _context.report_error(cgbn_division_by_zero_error); return; } } // division of padded values is the same as division of unpadded valuess shift=core::clz(denom._limbs); core::rotate_left(denom_local, denom._limbs, shift); core::rotate_left(num_low, num._limbs, shift); core::bitwise_mask_and(num_high, num_low, shift); core::bitwise_xor(num_low, num_low, num_high); numthreads=TPI-core::clzt(num_high); singleton::div_rem_wide(q._limbs, r._limbs, num_low, num_high, denom_local, numthreads); core::rotate_right(r._limbs, r._limbs, shift); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::sqrt(cgbn_t &s, const cgbn_t &a) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t shift, numthreads; uint32_t shifted[LIMBS]; shift=core::clz(a._limbs); if(shift==UNPADDED_BITS) { cgbn::mpzero<LIMBS>(s._limbs); return; } numthreads=(UNPADDED_BITS+LIMBS*64-1-shift) / (LIMBS*64); core::rotate_left(shifted, a._limbs, shift & 0xFFFFFFFE); singleton::sqrt(s._limbs, shifted, numthreads); shift=(shift>>1) % (LIMBS*32); core::shift_right(s._limbs, s._limbs, shift); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::sqrt_rem(cgbn_t &s, cgbn_t &r, const cgbn_t &a) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t shift, numthreads; uint32_t remainder[LIMBS], temp[LIMBS]; shift=core::clz(a._limbs); if(shift==UNPADDED_BITS) { cgbn::mpzero<LIMBS>(s._limbs); cgbn::mpzero<LIMBS>(r._limbs); return; } numthreads=(UNPADDED_BITS+LIMBS*64-1-shift) / (LIMBS*64); core::rotate_left(temp, a._limbs, shift & 0xFFFFFFFE); singleton::sqrt_rem(s._limbs, remainder, temp, numthreads); shift=(shift>>1) % (LIMBS*32); singleton::sqrt_resolve_rem(r._limbs, s._limbs, 0, remainder, shift); core::shift_right(s._limbs, s._limbs, shift); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ bool cgbn_env_t<context_t, bits, syncable>::equals(const cgbn_t &a, const cgbn_t &b) const { return cgbn::core_t<cgbn_env_t>::equals(a._limbs, b._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ int32_t cgbn_env_t<context_t, bits, syncable>::compare(const cgbn_t &a, const cgbn_t &b) const { return cgbn::core_t<cgbn_env_t>::compare(a._limbs, b._limbs); } /* wide arithmetic routines */ template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::mul_wide(cgbn_wide_t &r, const cgbn_t &a, const cgbn_t &b) const { uint32_t add[LIMBS]; cgbn::mpzero<LIMBS>(add); cgbn::core_singleton_t<cgbn_env_t, LIMBS>::mul_wide(r._low._limbs, r._high._limbs, a._limbs, b._limbs, add); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::sqr_wide(cgbn_wide_t &r, const cgbn_t &a) const { uint32_t add[LIMBS]; cgbn::mpzero<LIMBS>(add); cgbn::core_singleton_t<cgbn_env_t, LIMBS>::mul_wide(r._low._limbs, r._high._limbs, a._limbs, a._limbs, add); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::div_wide(cgbn_t &q, const cgbn_wide_t &num, const cgbn_t &denom) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t num_low[LIMBS], num_high[LIMBS], denom_local[LIMBS]; uint32_t shift, numthreads; if(_context.check_errors()) { if(core::compare(num._high._limbs, denom._limbs)>=0) { _context.report_error(cgbn_division_overflow_error); return; } } shift=core::clz(denom._limbs); core::rotate_left(denom_local, denom._limbs, shift); core::rotate_left(num_high, num._high._limbs, shift-(UNPADDED_BITS-BITS)); core::rotate_left(num_low, num._low._limbs, shift); core::bitwise_mask_select(num_high, num_high, num_low, shift-(UNPADDED_BITS-BITS)); numthreads=TPI-core::clzt(num_high); singleton::div_wide(q._limbs, num_low, num_high, denom_local, numthreads); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::rem_wide(cgbn_t &r, const cgbn_wide_t &num, const cgbn_t &denom) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t num_low[LIMBS], num_high[LIMBS], denom_local[LIMBS]; uint32_t shift, numthreads; if(_context.check_errors()) { if(core::compare(num._high._limbs, denom._limbs)>=0) { _context.report_error(cgbn_division_overflow_error); return; } } shift=core::clz(denom._limbs); core::rotate_left(denom_local, denom._limbs, shift); core::rotate_left(num_high, num._high._limbs, shift-(UNPADDED_BITS-BITS)); core::rotate_left(num_low, num._low._limbs, shift); core::bitwise_mask_select(num_high, num_high, num_low, shift-(UNPADDED_BITS-BITS)); core::bitwise_mask_and(num_low, num_low, shift-UNPADDED_BITS); numthreads=TPI-core::clzt(num_high); singleton::rem_wide(r._limbs, num_low, num_high, denom_local, numthreads); core::rotate_right(r._limbs, r._limbs, shift); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::div_rem_wide(cgbn_t &q, cgbn_t &r, const cgbn_wide_t &num, const cgbn_t &denom) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t num_low[LIMBS], num_high[LIMBS], denom_local[LIMBS]; uint32_t shift, numthreads; if(_context.check_errors()) { if(core::compare(num._high._limbs, denom._limbs)>=0) { _context.report_error(cgbn_division_overflow_error); return; } } shift=core::clz(denom._limbs); core::rotate_left(denom_local, denom._limbs, shift); core::rotate_left(num_high, num._high._limbs, shift-(UNPADDED_BITS-BITS)); core::rotate_left(num_low, num._low._limbs, shift); core::bitwise_mask_select(num_high, num_high, num_low, shift-(UNPADDED_BITS-BITS)); core::bitwise_mask_and(num_low, num_low, shift-UNPADDED_BITS); numthreads=TPI-core::clzt(num_high); singleton::div_rem_wide(q._limbs, r._limbs, num_low, num_high, denom_local, numthreads); core::rotate_right(r._limbs, r._limbs, shift); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::sqrt_wide(cgbn_t &s, const cgbn_wide_t &a) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t clz_shift, shift, numthreads; uint32_t high_shifted[LIMBS], low_shifted[LIMBS]; clz_shift=core::clz(a._high._limbs); if(clz_shift==UNPADDED_BITS) { clz_shift=core::clz(a._low._limbs); if(clz_shift==UNPADDED_BITS) { cgbn::mpzero<LIMBS>(s._limbs); return; } clz_shift=clz_shift & 0xFFFFFFFE; cgbn::mpset<LIMBS>(high_shifted, a._low._limbs); cgbn::mpzero<LIMBS>(low_shifted); shift=clz_shift + UNPADDED_BITS; } else { clz_shift=clz_shift & 0xFFFFFFFE; cgbn::mpset<LIMBS>(high_shifted, a._high._limbs); core::rotate_left(low_shifted, a._low._limbs, clz_shift+(UNPADDED_BITS-BITS)); shift=clz_shift+UNPADDED_BITS-BITS; } numthreads=(2*UNPADDED_BITS+LIMBS*64-1-shift) / (LIMBS*64); core::rotate_left(high_shifted, high_shifted, clz_shift); if(shift<2*UNPADDED_BITS-BITS) { core::bitwise_mask_select(high_shifted, high_shifted, low_shifted, clz_shift); core::bitwise_mask_and(low_shifted, low_shifted, (int32_t)(shift-UNPADDED_BITS)); } singleton::sqrt_wide(s._limbs, low_shifted, high_shifted, numthreads); shift=(shift>>1) % (LIMBS*32); core::shift_right(s._limbs, s._limbs, shift); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::sqrt_rem_wide(cgbn_t &s, cgbn_wide_t &r, const cgbn_wide_t &a) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core_unpadded; typedef cgbn::core_t<cgbn_env_t> core_padded; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t group_thread=threadIdx.x & TPI-1; uint32_t clz_shift, shift, numthreads, c; uint32_t remainder[LIMBS], high_shifted[LIMBS], low_shifted[LIMBS]; clz_shift=core_unpadded::clz(a._high._limbs); if(clz_shift==UNPADDED_BITS) { clz_shift=core_unpadded::clz(a._low._limbs); if(clz_shift==UNPADDED_BITS) { cgbn::mpzero<LIMBS>(s._limbs); cgbn::mpzero<LIMBS>(r._low._limbs); cgbn::mpzero<LIMBS>(r._high._limbs); return; } clz_shift=clz_shift & 0xFFFFFFFE; cgbn::mpset<LIMBS>(high_shifted, a._low._limbs); cgbn::mpzero<LIMBS>(low_shifted); shift=clz_shift + UNPADDED_BITS; } else { clz_shift=clz_shift & 0xFFFFFFFE; cgbn::mpset<LIMBS>(high_shifted, a._high._limbs); core_unpadded::rotate_left(low_shifted, a._low._limbs, clz_shift+(UNPADDED_BITS-BITS)); shift=clz_shift+UNPADDED_BITS-BITS; } numthreads=(2*UNPADDED_BITS+LIMBS*64-1-shift) / (LIMBS*64); core_unpadded::rotate_left(high_shifted, high_shifted, clz_shift); if(shift<2*UNPADDED_BITS-BITS) { core_unpadded::bitwise_mask_select(high_shifted, high_shifted, low_shifted, clz_shift); core_unpadded::bitwise_mask_and(low_shifted, low_shifted, (int32_t)(shift-UNPADDED_BITS)); } c=singleton::sqrt_rem_wide(s._limbs, remainder, low_shifted, high_shifted, numthreads); shift=(shift>>1) % (LIMBS*32); if(shift==0) { if(UNPADDED_BITS!=BITS) c=core_padded::clear_carry(remainder); cgbn::mpset<LIMBS>(r._low._limbs, remainder); cgbn::mpzero<LIMBS>(r._high._limbs); r._high._limbs[0]=(group_thread==0) ? c : 0; } else { singleton::sqrt_resolve_rem(r._low._limbs, s._limbs, c, remainder, shift); cgbn::mpzero<LIMBS>(r._high._limbs); if(UNPADDED_BITS!=BITS) { c=core_padded::clear_carry(r._low._limbs); r._high._limbs[0]=(group_thread==0) ? c : 0; } core_unpadded::shift_right(s._limbs, s._limbs, shift); } } /* bit counting */ template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ uint32_t cgbn_env_t<context_t, bits, syncable>::pop_count(const cgbn_t &a) const { return cgbn::core_t<cgbn_env_t>::pop_count(a._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ uint32_t cgbn_env_t<context_t, bits, syncable>::clz(const cgbn_t &a) const { return cgbn::core_t<cgbn_env_t>::clz(a._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ uint32_t cgbn_env_t<context_t, bits, syncable>::ctz(const cgbn_t &a) const { return cgbn::core_t<cgbn_env_t>::ctz(a._limbs); } /* logical, shifting, masking */ template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::bitwise_complement(cgbn_t &r, const cgbn_t &a) const { cgbn::core_t<cgbn_env_t>::bitwise_complement(r._limbs, a._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::bitwise_and(cgbn_t &r, const cgbn_t &a, const cgbn_t &b) const { cgbn::core_t<cgbn_env_t>::bitwise_and(r._limbs, a._limbs, b._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::bitwise_ior(cgbn_t &r, const cgbn_t &a, const cgbn_t &b) const { cgbn::core_t<cgbn_env_t>::bitwise_ior(r._limbs, a._limbs, b._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::bitwise_xor(cgbn_t &r, const cgbn_t &a, const cgbn_t &b) const { cgbn::core_t<cgbn_env_t>::bitwise_xor(r._limbs, a._limbs, b._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::bitwise_select(cgbn_t &r, const cgbn_t &clear, const cgbn_t &set, const cgbn_t &select) const { cgbn::core_t<cgbn_env_t>::bitwise_select(r._limbs, clear._limbs, set._limbs, select._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::bitwise_mask_copy(cgbn_t &r, const int32_t numbits) const { cgbn::core_t<cgbn_env_t>::bitwise_mask_copy(r._limbs, numbits); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::bitwise_mask_and(cgbn_t &r, const cgbn_t &a, const int32_t numbits) const { cgbn::core_t<cgbn_env_t>::bitwise_mask_and(r._limbs, a._limbs, numbits); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::bitwise_mask_ior(cgbn_t &r, const cgbn_t &a, const int32_t numbits) const { cgbn::core_t<cgbn_env_t>::bitwise_mask_ior(r._limbs, a._limbs, numbits); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::bitwise_mask_xor(cgbn_t &r, const cgbn_t &a, const int32_t numbits) const { cgbn::core_t<cgbn_env_t>::bitwise_mask_xor(r._limbs, a._limbs, numbits); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::bitwise_mask_select(cgbn_t &r, const cgbn_t &clear, const cgbn_t &set, const int32_t numbits) const { cgbn::core_t<cgbn_env_t>::bitwise_mask_select(r._limbs, clear._limbs, set._limbs, numbits); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::shift_left(cgbn_t &r, const cgbn_t &a, const uint32_t numbits) const { cgbn::core_t<cgbn_env_t>::shift_left(r._limbs, a._limbs, numbits); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::shift_right(cgbn_t &r, const cgbn_t &a, const uint32_t numbits) const { cgbn::core_t<cgbn_env_t>::shift_right(r._limbs, a._limbs, numbits); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::rotate_left(cgbn_t &r, const cgbn_t &a, const uint32_t numbits) const { cgbn::core_t<cgbn_env_t>::rotate_left(r._limbs, a._limbs, numbits); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::rotate_right(cgbn_t &r, const cgbn_t &a, const uint32_t numbits) const { cgbn::core_t<cgbn_env_t>::rotate_right(r._limbs, a._limbs, numbits); } #if 0 template<class context_t, uint32_t bits, cgbn_syncable_t syncable> template<uint32_t numbits> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::shift_left(cgbn_t &r, const cgbn_t &a) const { fwshift_left_constant<LIMBS, numbits>(r._limbs, a._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> template<uint32_t numbits> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::shift_right(cgbn_t &r, const cgbn_t &a) const { fwshift_right_constant<LIMBS, numbits>(r._limbs, a._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> template<uint32_t numbits> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::rotate_left(cgbn_t &r, const cgbn_t &a) const { fwrotate_left_constant<LIMBS, numbits>(r._limbs, a._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> template<uint32_t numbits> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::rotate_right(cgbn_t &r, const cgbn_t &a) const { fwrotate_right_constant<LIMBS, numbits>(r._limbs, a._limbs); } #endif /* accumulator APIs */ template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ cgbn_env_t<context_t, bits, syncable>::cgbn_accumulator_t::cgbn_accumulator_t() { _carry=0; cgbn::mpzero<LIMBS>(_limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ int32_t cgbn_env_t<context_t, bits, syncable>::resolve(cgbn_t &sum, const cgbn_accumulator_t &accumulator) const { typedef cgbn::core_t<cgbn_env_t> core; uint32_t carry=accumulator._carry; int32_t result; cgbn::mpset<LIMBS>(sum._limbs, accumulator._limbs); result=core::resolve_add(carry, sum._limbs); core::clear_padding(sum._limbs); return result; } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::set_ui32(cgbn_accumulator_t &accumulator, const uint32_t value) const { uint32_t group_thread=threadIdx.x & TPI-1; accumulator._carry=0; accumulator._limbs[0]=(group_thread==0) ? value : 0; #pragma unroll for(int32_t index=1;index<LIMBS;index++) accumulator._limbs[index]=0; } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::add_ui32(cgbn_accumulator_t &accumulator, const uint32_t value) const { uint32_t group_thread=threadIdx.x & TPI-1; cgbn::chain_t<> chain; accumulator._limbs[0]=chain.add(accumulator._limbs[0], (group_thread==0) ? value : 0); #pragma unroll for(int32_t index=1;index<LIMBS;index++) accumulator._limbs[index]=chain.add(accumulator._limbs[index], 0); accumulator._carry=chain.add(accumulator._carry, 0); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::sub_ui32(cgbn_accumulator_t &accumulator, const uint32_t value) const { uint32_t group_thread=threadIdx.x & TPI-1; cgbn::chain_t<> chain; chain.sub(0, group_thread); accumulator._limbs[0]=chain.sub(accumulator._limbs[0], (group_thread==0) ? value : 0); #pragma unroll for(int32_t index=1;index<LIMBS;index++) accumulator._limbs[index]=chain.sub(accumulator._limbs[index], 0); if(PADDING==0) accumulator._carry=chain.add(accumulator._carry, (group_thread==TPI-1) ? 0xFFFFFFFF : 0); else accumulator._carry=chain.add(accumulator._carry, 0); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::set(cgbn_accumulator_t &accumulator, const cgbn_t &value) const { accumulator._carry=0; cgbn::mpset<LIMBS>(accumulator._limbs, value._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::add(cgbn_accumulator_t &accumulator, const cgbn_t &value) const { cgbn::chain_t<> chain; #pragma unroll for(int32_t index=0;index<LIMBS;index++) accumulator._limbs[index]=chain.add(accumulator._limbs[index], value._limbs[index]); accumulator._carry=chain.add(accumulator._carry, 0); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::sub(cgbn_accumulator_t &accumulator, const cgbn_t &value) const { uint32_t group_thread=threadIdx.x & TPI-1; cgbn::chain_t<> chain; chain.sub(0, group_thread); #pragma unroll for(int32_t index=0;index<LIMBS;index++) accumulator._limbs[index]=chain.sub(accumulator._limbs[index], value._limbs[index]); if(PADDING==0) accumulator._carry=chain.add(accumulator._carry, (group_thread==TPI-1) ? 0xFFFFFFFF : 0); else accumulator._carry=chain.add(accumulator._carry, 0); } /* math */ template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::binary_inverse(cgbn_t &r, const cgbn_t &x) const { uint32_t low; if(_context.check_errors()) { low=cgbn::core_t<cgbn_env_t>::get_ui32(x._limbs); if((low & 0x01)==0) { _context.report_error(cgbn_inverse_does_not_exist_error); return; } } cgbn::core_t<cgbn_env_t>::binary_inverse(r._limbs, x._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ bool cgbn_env_t<context_t, bits, syncable>::modular_inverse(cgbn_t &r, const cgbn_t &x, const cgbn_t &m) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; return cgbn::core_t<unpadded>::modular_inverse(r._limbs, x._limbs, m._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::modular_power(cgbn_t &r, const cgbn_t &a, const cgbn_t &k, const cgbn_t &m) const { cgbn_wide_t wide; cgbn_t current, square, approx; int32_t bit, m_clz, last; // FIX FIX FIX -- errors get checked again and again if(_context.check_errors()) { if(compare(a, m)>=0) { _context.report_error(cgbn_division_overflow_error); return; } } set_ui32(current, 1); set(square, a); m_clz=barrett_approximation(approx, m); last=bits-1-clz(k); if(last==-1) { set_ui32(r, 1); return; } for(bit=0;bit<last;bit++) { if(extract_bits_ui32(k, bit, 1)==1) { mul_wide(wide, current, square); barrett_rem_wide(current, wide, m, approx, m_clz); } mul_wide(wide, square, square); barrett_rem_wide(square, wide, m, approx, m_clz); } mul_wide(wide, current, square); barrett_rem_wide(r, wide, m, approx, m_clz); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::gcd(cgbn_t &r, const cgbn_t &a, const cgbn_t &b) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; cgbn::core_t<unpadded>::gcd(r._limbs, a._limbs, b._limbs); } /* fast division: common divisor / modulus */ template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ uint32_t cgbn_env_t<context_t, bits, syncable>::bn2mont(cgbn_t &mont, const cgbn_t &bn, const cgbn_t &n) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t num_low[LIMBS], num_high[LIMBS], n_local[LIMBS]; uint32_t shift, low; low=core::get_ui32(n._limbs); if(_context.check_errors()) { if((low & 0x01)==0) { _context.report_error(cgbn_modulus_not_odd_error); return 0; } if(compare(bn, n)>=0) { _context.report_error(cgbn_division_overflow_error); return 0; } } // for padded values, we use a larger R cgbn::mpzero<LIMBS>(num_low); shift=core::clz(n._limbs); core::rotate_left(n_local, n._limbs, shift); core::rotate_left(num_high, bn._limbs, shift); singleton::rem_wide(mont._limbs, num_low, num_high, n_local, TPI); core::shift_right(mont._limbs, mont._limbs, shift); return -cgbn::ubinary_inverse(low); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::mont2bn(cgbn_t &bn, const cgbn_t &mont, const cgbn_t &n, const uint32_t np0) const { uint32_t zeros[LIMBS]; cgbn::mpzero<LIMBS>(zeros); // mont_reduce_wide returns 0<=res<=n cgbn::core_singleton_t<cgbn_env_t, LIMBS>::mont_reduce_wide(bn._limbs, mont._limbs, zeros, n._limbs, np0, true); // handle the case of res==n if(cgbn::core_t<cgbn_env_t>::equals(bn._limbs, n._limbs)) cgbn::mpzero<LIMBS>(bn._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::mont_mul(cgbn_t &r, const cgbn_t &a, const cgbn_t &b, const cgbn_t &n, const uint32_t np0) const { cgbn::core_singleton_t<cgbn_env_t, LIMBS>::mont_mul(r._limbs, a._limbs, b._limbs, n._limbs, np0); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::mont_sqr(cgbn_t &r, const cgbn_t &a, const cgbn_t &n, const uint32_t np0) const { cgbn::core_singleton_t<cgbn_env_t, LIMBS>::mont_mul(r._limbs, a._limbs, a._limbs, n._limbs, np0); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::mont_reduce_wide(cgbn_t &r, const cgbn_wide_t &a, const cgbn_t &n, const uint32_t np0) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t low[LIMBS], high[LIMBS]; cgbn::mpset<LIMBS>(low, a._low._limbs); cgbn::mpset<LIMBS>(high, a._high._limbs); if(PADDING!=0) { core::rotate_right(high, high, UNPADDED_BITS-BITS); core::bitwise_mask_select(low, high, low, BITS); core::bitwise_mask_and(high, high, BITS); } // mont_reduce_wide returns 0<=res<=n singleton::mont_reduce_wide(r._limbs, low, high, n._limbs, np0, false); // handle the case of res==n if(core::equals(r._limbs, n._limbs)) cgbn::mpzero<LIMBS>(r._limbs); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ uint32_t cgbn_env_t<context_t, bits, syncable>::barrett_approximation(cgbn_t &approx, const cgbn_t &denom) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t shift, shifted[LIMBS], low[LIMBS], high[LIMBS]; shift=core::clz(denom._limbs); if(_context.check_errors()) { if(shift==UNPADDED_BITS) { _context.report_error(cgbn_division_by_zero_error); return 0xFFFFFFFF; } } if(shift==UNPADDED_BITS) return 0xFFFFFFFF; core::rotate_left(shifted, denom._limbs, shift); #pragma unroll for(int32_t index=0;index<LIMBS;index++) { low[index]=0xFFFFFFFF; high[index]=~shifted[index]; // high=0xFFFFFFFF - shifted[index] } singleton::div_wide(approx._limbs, low, high, shifted, TPI); return shift; } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::barrett_div(cgbn_t &q, const cgbn_t &num, const cgbn_t &denom, const cgbn_t &approx, const uint32_t denom_clz) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t sync, group_thread=threadIdx.x & TPI-1; uint32_t low[LIMBS], high[LIMBS], quotient[LIMBS], zero[LIMBS]; uint32_t word, c, sub=0; sync=core::sync_mask(); core::shift_right(high, num._limbs, UNPADDED_BITS-denom_clz); cgbn::mpzero<LIMBS>(zero); singleton::mul_high(quotient, high, approx._limbs, zero); c=cgbn::mpadd<LIMBS>(quotient, quotient, high); c+=cgbn::mpadd32<LIMBS>(quotient, quotient, group_thread==0 ? 3 : 0); c=core::resolve_add(c, quotient); if(c!=0) { #pragma unroll for(int32_t index=0;index<LIMBS;index++) quotient[index]=0xFFFFFFFF; } singleton::mul_wide(low, high, denom._limbs, quotient, zero); word=-__shfl_sync(sync, high[0], 0, TPI); c=cgbn::mpsub<LIMBS>(low, num._limbs, low); word-=core::fast_propagate_sub(c, low); while(word!=0) { sub++; c=cgbn::mpadd<LIMBS>(low, low, denom._limbs); word+=core::fast_propagate_add(c, low); } core::sub_ui32(q._limbs, quotient, sub); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::barrett_rem(cgbn_t &r, const cgbn_t &num, const cgbn_t &denom, const cgbn_t &approx, const uint32_t denom_clz) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t sync, group_thread=threadIdx.x & TPI-1; uint32_t low[LIMBS], high[LIMBS], quotient[LIMBS], zero[LIMBS]; uint32_t word, c; sync=core::sync_mask(); core::shift_right(high, num._limbs, UNPADDED_BITS-denom_clz); cgbn::mpzero<LIMBS>(zero); singleton::mul_high(quotient, high, approx._limbs, zero); c=cgbn::mpadd<LIMBS>(quotient, quotient, high); c+=cgbn::mpadd32<LIMBS>(quotient, quotient, group_thread==0 ? 3 : 0); c=core::resolve_add(c, quotient); if(c!=0) { #pragma unroll for(int32_t index=0;index<LIMBS;index++) quotient[index]=0xFFFFFFFF; } singleton::mul_wide(low, high, denom._limbs, quotient, zero); word=-__shfl_sync(sync, high[0], 0, TPI); c=cgbn::mpsub<LIMBS>(low, num._limbs, low); word-=core::fast_propagate_sub(c, low); while(word!=0) { c=cgbn::mpadd<LIMBS>(low, low, denom._limbs); word+=core::fast_propagate_add(c, low); } cgbn::mpset<LIMBS>(r._limbs, low); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::barrett_div_rem(cgbn_t &q, cgbn_t &r, const cgbn_t &num, const cgbn_t &denom, const cgbn_t &approx, const uint32_t denom_clz) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t sync, group_thread=threadIdx.x & TPI-1; uint32_t low[LIMBS], high[LIMBS], quotient[LIMBS], zero[LIMBS]; uint32_t word, c, sub=0; sync=core::sync_mask(); core::shift_right(high, num._limbs, UNPADDED_BITS-denom_clz); cgbn::mpzero<LIMBS>(zero); singleton::mul_high(quotient, high, approx._limbs, zero); c=cgbn::mpadd<LIMBS>(quotient, quotient, high); c+=cgbn::mpadd32<LIMBS>(quotient, quotient, group_thread==0 ? 3 : 0); c=core::resolve_add(c, quotient); if(c!=0) { #pragma unroll for(int32_t index=0;index<LIMBS;index++) quotient[index]=0xFFFFFFFF; } singleton::mul_wide(low, high, denom._limbs, quotient, zero); word=-__shfl_sync(sync, high[0], 0, TPI); c=cgbn::mpsub<LIMBS>(low, num._limbs, low); word-=core::fast_propagate_sub(c, low); while(word!=0) { sub++; c=cgbn::mpadd<LIMBS>(low, low, denom._limbs); word+=core::fast_propagate_add(c, low); } core::sub_ui32(q._limbs, quotient, sub); cgbn::mpset<LIMBS>(r._limbs, low); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::barrett_div_wide(cgbn_t &q, const cgbn_wide_t &num, const cgbn_t &denom, const cgbn_t &approx, const uint32_t denom_clz) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core_unpadded; typedef cgbn::core_t<cgbn_env_t> core_padded; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t sync, group_thread=threadIdx.x & TPI-1, group_base=group_thread*LIMBS; uint32_t low[LIMBS], high[LIMBS], quotient[LIMBS], zero[LIMBS]; uint32_t word, c, sub=0; if(_context.check_errors()) { if(core_unpadded::compare(num._high._limbs, denom._limbs)>=0) { _context.report_error(cgbn_division_overflow_error); return; } } sync=core_unpadded::sync_mask(); word=__shfl_sync(sync, num._high._limbs[0], 0, TPI); core_unpadded::rotate_left(low, num._low._limbs, denom_clz); core_unpadded::rotate_left(high, num._high._limbs, denom_clz-(UNPADDED_BITS-BITS)); core_unpadded::bitwise_mask_select(high, high, low, denom_clz-(UNPADDED_BITS-BITS)); cgbn::mpzero<LIMBS>(zero); singleton::mul_high(quotient, high, approx._limbs, zero); c=cgbn::mpadd<LIMBS>(quotient, quotient, high); c+=cgbn::mpadd32<LIMBS>(quotient, quotient, group_thread==0 ? 3 : 0); c=core_padded::resolve_add(c, quotient); if(c!=0) { #pragma unroll for(int32_t index=0;index<LIMBS;index++) if(PADDING==0) quotient[index]=0xFFFFFFFF; else quotient[index]=(group_base<BITS/32-index) ? 0xFFFFFFFF : 0; } singleton::mul_wide(low, high, denom._limbs, quotient, zero); if(PADDING==0) word=word-__shfl_sync(sync, high[0], 0, TPI); else { word=word-__shfl_sync(sync, low[PAD_LIMB], PAD_THREAD, TPI); core_padded::clear_padding(low); } c=cgbn::mpsub<LIMBS>(low, num._low._limbs, low); word-=core_padded::fast_propagate_sub(c, low); while(word!=0) { sub++; c=cgbn::mpadd<LIMBS>(low, low, denom._limbs); word+=core_padded::fast_propagate_add(c, low); } core_unpadded::sub_ui32(q._limbs, quotient, sub); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::barrett_rem_wide(cgbn_t &r, const cgbn_wide_t &num, const cgbn_t &denom, const cgbn_t &approx, const uint32_t denom_clz) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core_unpadded; typedef cgbn::core_t<cgbn_env_t> core_padded; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t sync, group_thread=threadIdx.x & TPI-1, group_base=group_thread*LIMBS; uint32_t low[LIMBS], high[LIMBS], quotient[LIMBS], zero[LIMBS]; uint32_t word, c; if(_context.check_errors()) { if(core_unpadded::compare(num._high._limbs, denom._limbs)>=0) { _context.report_error(cgbn_division_overflow_error); return; } } sync=core_unpadded::sync_mask(); word=__shfl_sync(sync, num._high._limbs[0], 0, TPI); core_unpadded::rotate_left(low, num._low._limbs, denom_clz); core_unpadded::rotate_left(high, num._high._limbs, denom_clz-(UNPADDED_BITS-BITS)); core_unpadded::bitwise_mask_select(high, high, low, denom_clz-(UNPADDED_BITS-BITS)); cgbn::mpzero<LIMBS>(zero); singleton::mul_high(quotient, high, approx._limbs, zero); c=cgbn::mpadd<LIMBS>(quotient, quotient, high); c+=cgbn::mpadd32<LIMBS>(quotient, quotient, group_thread==0 ? 3 : 0); c=core_padded::resolve_add(c, quotient); if(c!=0) { #pragma unroll for(int32_t index=0;index<LIMBS;index++) if(PADDING==0) quotient[index]=0xFFFFFFFF; else quotient[index]=(group_base<BITS/32-index) ? 0xFFFFFFFF : 0; } singleton::mul_wide(low, high, denom._limbs, quotient, zero); if(PADDING==0) word=word-__shfl_sync(sync, high[0], 0, TPI); else { word=word-__shfl_sync(sync, low[PAD_LIMB], PAD_THREAD, TPI); core_padded::clear_padding(low); } c=cgbn::mpsub<LIMBS>(low, num._low._limbs, low); word-=core_padded::fast_propagate_sub(c, low); while(word!=0) { c=cgbn::mpadd<LIMBS>(low, low, denom._limbs); word+=core_padded::fast_propagate_add(c, low); } cgbn::mpset<LIMBS>(r._limbs, low); } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::barrett_div_rem_wide(cgbn_t &q, cgbn_t &r, const cgbn_wide_t &num, const cgbn_t &denom, const cgbn_t &approx, const uint32_t denom_clz) const { typedef cgbn::unpadded_t<cgbn_env_t> unpadded; typedef cgbn::core_t<unpadded> core_unpadded; typedef cgbn::core_t<cgbn_env_t> core_padded; typedef cgbn::core_singleton_t<unpadded, LIMBS> singleton; uint32_t sync, group_thread=threadIdx.x & TPI-1, group_base=group_thread*LIMBS; uint32_t low[LIMBS], high[LIMBS], quotient[LIMBS], zero[LIMBS]; uint32_t word, c, sub=0; if(_context.check_errors()) { if(core_unpadded::compare(num._high._limbs, denom._limbs)>=0) { _context.report_error(cgbn_division_overflow_error); return; } } sync=core_unpadded::sync_mask(); word=__shfl_sync(sync, num._high._limbs[0], 0, TPI); core_unpadded::rotate_left(low, num._low._limbs, denom_clz); core_unpadded::rotate_left(high, num._high._limbs, denom_clz-(UNPADDED_BITS-BITS)); core_unpadded::bitwise_mask_select(high, high, low, denom_clz-(UNPADDED_BITS-BITS)); cgbn::mpzero<LIMBS>(zero); singleton::mul_high(quotient, high, approx._limbs, zero); c=cgbn::mpadd<LIMBS>(quotient, quotient, high); c+=cgbn::mpadd32<LIMBS>(quotient, quotient, group_thread==0 ? 3 : 0); c=core_padded::resolve_add(c, quotient); if(c!=0) { #pragma unroll for(int32_t index=0;index<LIMBS;index++) if(PADDING==0) quotient[index]=0xFFFFFFFF; else quotient[index]=(group_base<BITS/32-index) ? 0xFFFFFFFF : 0; } singleton::mul_wide(low, high, denom._limbs, quotient, zero); if(PADDING==0) word=word-__shfl_sync(sync, high[0], 0, TPI); else { word=word-__shfl_sync(sync, low[PAD_LIMB], PAD_THREAD, TPI); core_padded::clear_padding(low); } c=cgbn::mpsub<LIMBS>(low, num._low._limbs, low); word-=core_padded::fast_propagate_sub(c, low); while(word!=0) { sub++; c=cgbn::mpadd<LIMBS>(low, low, denom._limbs); word+=core_padded::fast_propagate_add(c, low); } core_unpadded::sub_ui32(q._limbs, quotient, sub); cgbn::mpset<LIMBS>(r._limbs, low); } /* load/store routines */ template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::load(cgbn_t &r, cgbn_mem_t<bits> *const address) const { int32_t group_thread=threadIdx.x & TPI-1; int32_t limb; #pragma unroll for(limb=0;limb<LIMBS;limb++) { if(PADDING!=0) { r._limbs[limb]=0; if(group_thread*LIMBS<BITS/32-limb) r._limbs[limb]=address->_limbs[group_thread*LIMBS + limb]; } else r._limbs[limb]=address->_limbs[group_thread*LIMBS + limb]; } } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::store(cgbn_mem_t<bits> *address, const cgbn_t &a) const { int32_t group_thread=threadIdx.x & TPI-1; int32_t limb; #pragma unroll for(limb=0;limb<LIMBS;limb++) { if(PADDING!=0) { if(group_thread*LIMBS<BITS/32-limb) address->_limbs[group_thread*LIMBS + limb]=a._limbs[limb]; #if 1 else if(a._limbs[limb]!=0) { printf("BAD LIMB: %d %d %d\n", blockIdx.x, threadIdx.x, limb); __trap(); } #endif } else address->_limbs[group_thread*LIMBS + limb]=a._limbs[limb]; } } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::load(cgbn_t &r, cgbn_local_t *const address) const { int32_t limb; #pragma unroll for(limb=0;limb<LIMBS;limb++) r._limbs[limb]=address->_limbs[limb]; } template<class context_t, uint32_t bits, cgbn_syncable_t syncable> __device__ __forceinline__ void cgbn_env_t<context_t, bits, syncable>::store(cgbn_local_t *address, const cgbn_t &a) const { int32_t limb; #pragma unroll for(limb=0;limb<LIMBS;limb++) address->_limbs[limb]=a._limbs[limb]; }
the_stack
#include "cuda/utils.h" #include "cuda/helpers.h" namespace fastertransformer { #define MAX_BLOCKS_PER_BEAM 8 template <typename T> void topK_kernelLauncher(const T* log_probs, int* topk_tmp_id_buf, T* topk_tmp_val_buf, int* topk_id_buf, T* topk_val_buf, const int batch_size, const int beams_per_batch, const int k, const int vocab_size, cudaStream_t stream); } namespace ctranslate2 { namespace ops { template <Device D, typename DataType, typename IndexType> void TopK::compute(const StorageView& x, StorageView& values, StorageView& indices) const { const dim_t depth = x.dim(-1); const dim_t batch_size = x.size() / depth; const dim_t temp_size = batch_size * _k * MAX_BLOCKS_PER_BEAM; auto& allocator = get_allocator<D>(); auto* topk_tmp_id = static_cast<IndexType*>( allocator.allocate(temp_size * sizeof (IndexType))); auto* topk_tmp_val = static_cast<DataType*>( allocator.allocate(temp_size * sizeof (DataType))); fastertransformer::topK_kernelLauncher(cuda::device_cast(x.data<DataType>()), cuda::device_cast(topk_tmp_id), cuda::device_cast(topk_tmp_val), cuda::device_cast(indices.data<IndexType>()), cuda::device_cast(values.data<DataType>()), batch_size, 1, _k, depth, cuda::get_cuda_stream()); allocator.free(topk_tmp_id); allocator.free(topk_tmp_val); } #define DECLARE_IMPL(T) \ template void \ TopK::compute<Device::CUDA, T, int32_t>(const StorageView& x, \ StorageView& values, \ StorageView& indices) const; DECLARE_IMPL(float) DECLARE_IMPL(float16_t) } } // The kernels below were initially developed in FasterTransformer // https://github.com/NVIDIA/DeepLearningExamples/blob/master/FasterTransformer/v3.0/fastertransformer/cuda/topk_kernels.cu // which comes with the following license: /* Copyright (c) 2020, NVIDIA CORPORATION. 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. */ // We use an adaptation of these kernels that was proposed in MarianNMT // https://github.com/rhenry-nv/marian-dev/blob/gpu_optimizations/src/3rd_party/topk.cuh // which comes with the following license: /* MIT License Copyright (c) 2016 Marcin Junczys-Dowmunt, the University of Edinburgh, Adam Mickiewicz University Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cub/cub.cuh> namespace fastertransformer { #define NOT_FOUND -1 template <typename T> __device__ __forceinline__ bool greater(const T& a, const T& b) { return a > b; } #if !CUDA_CAN_USE_HALF template<> __device__ __forceinline__ bool greater(const __half& a, const __half& b) { return float(a) > float(b); } #endif template <typename T> struct TopK { int p = NOT_FOUND; T u = cub::FpLimits<T>::Lowest(); __device__ __forceinline__ void insert(T elem, int elem_id) { if (greater(elem, u)) { u = elem; p = elem_id; } } __device__ __forceinline__ void init() { u = cub::FpLimits<T>::Lowest(); p = NOT_FOUND; } }; template <typename T> __device__ __forceinline__ TopK<T> reduce_topk_op(const TopK<T>& a, const TopK<T>& b) { return greater(a.u, b.u) ? a : b; } template<typename T, int BLOCK_SIZE_, int BLOCKS_PER_BEAM_> __global__ void topk_stage_1(T* log_probs, int* topk_tmp_id_buf, T* topk_tmp_val_buf, const int k, const int vocab_size) { typedef cub::BlockReduce<TopK<T>, BLOCK_SIZE_> BlockReduce; __shared__ typename BlockReduce::TempStorage temp_storage; const int tid = threadIdx.x; const int bid = blockIdx.x; const int row_id = bid / BLOCKS_PER_BEAM_; // row id for log_probs const int block_lane = bid % BLOCKS_PER_BEAM_; // block id for a beam const int tmp_log_buf_index = row_id * vocab_size; const int tmp_topk_buf_index = row_id * BLOCKS_PER_BEAM_ * k + block_lane * k; TopK<T> partial; for (int ite = 0; ite < k; ite++) { partial.init(); #pragma unroll for (int elem_id = tid + block_lane * BLOCK_SIZE_; elem_id < vocab_size; elem_id += BLOCK_SIZE_ * BLOCKS_PER_BEAM_) { int index = elem_id + tmp_log_buf_index; partial.insert(log_probs[index], index); } TopK<T> total = BlockReduce(temp_storage).Reduce(partial, reduce_topk_op<T>); if (tid == 0) { const int index = tmp_topk_buf_index + ite; topk_tmp_id_buf[index] = total.p; topk_tmp_val_buf[index] = total.u; // If we found a max, blank out the value in the log prob array before starting the next iteration if (total.p != NOT_FOUND) log_probs[total.p] = cub::FpLimits<T>::Lowest(); } __syncthreads(); } // Update prob array with original values. for (int beam = tid; beam < k; beam += BLOCK_SIZE_) { const int index = tmp_topk_buf_index + beam; int k_idx = topk_tmp_id_buf[index]; if (k_idx != NOT_FOUND) log_probs[k_idx] = topk_tmp_val_buf[index]; } } template<typename T, int BLOCK_SIZE_, int BLOCKS_PER_BEAM_> __global__ void topk_stage_2(const int* __restrict topk_tmp_id_buf, T* topk_tmp_val_buf, int* topk_id_buf, T* topk_val_buf, const int beams_per_batch, const int vocab_size, const int k) { const int size = beams_per_batch * k * BLOCKS_PER_BEAM_; const int tid = threadIdx.x; const int batch_id = blockIdx.x; typedef cub::BlockReduce<TopK<T>, BLOCK_SIZE_> BlockReduce; __shared__ typename BlockReduce::TempStorage temp_storage; extern __shared__ char array[]; T *s_val = topk_tmp_val_buf + batch_id * size; TopK<T> *topks = (TopK<T>*)(array); TopK<T> partial; for (int ite = 0; ite < k; ite++) { partial.init(); #pragma unroll for (int i = tid; i < size; i+= BLOCK_SIZE_) { partial.insert(s_val[i], i); } TopK<T> total = BlockReduce(temp_storage).Reduce(partial, reduce_topk_op<T>); if (tid == 0) { topks[ite] = total; s_val[total.p] = cub::FpLimits<T>::Lowest(); } __syncthreads(); } for (int beam = tid; beam < k; beam += BLOCK_SIZE_) { int indexInRow = topks[beam].p == NOT_FOUND? 0: topks[beam].p; int id = topk_tmp_id_buf[batch_id * size + indexInRow]; id = id == NOT_FOUND? 0 : id; // If no max found, all values were equal to T::min so just return 0 const int offset = batch_id * k + beam; topk_id_buf[offset] = id % vocab_size; topk_val_buf[offset] = topks[beam].u; } } #define CASE_K(K,BLOCK_SIZE_1_, BLOCK_SIZE_2_, BLOCKS_PER_BEAM_) \ case K: \ topk_stage_1<T, BLOCK_SIZE_1_, BLOCKS_PER_BEAM_> \ <<<batch_size * beams_per_batch * BLOCKS_PER_BEAM_, BLOCK_SIZE_1_, 0, stream>>>( \ const_cast<T*>(log_probs), \ topk_tmp_id_buf, \ topk_tmp_val_buf, \ k, vocab_size); \ topk_stage_2<T, BLOCK_SIZE_2_, BLOCKS_PER_BEAM_> \ <<<batch_size, BLOCK_SIZE_2_, K * sizeof(TopK<T>), stream>>>( \ topk_tmp_id_buf, \ topk_tmp_val_buf, \ topk_id_buf, \ topk_val_buf, \ beams_per_batch, \ vocab_size, \ k); \ break template <typename T> void topK_kernelLauncher(const T* log_probs, int* topk_tmp_id_buf, T* topk_tmp_val_buf, int* topk_id_buf, T* topk_val_buf, const int batch_size, const int beams_per_batch, const int k, const int vocab_size, cudaStream_t stream) { switch (k) { CASE_K(1,128,128,MAX_BLOCKS_PER_BEAM); CASE_K(2,128,128,MAX_BLOCKS_PER_BEAM); CASE_K(4,128,128,MAX_BLOCKS_PER_BEAM); CASE_K(6,128,128,MAX_BLOCKS_PER_BEAM); CASE_K(8,128,128,MAX_BLOCKS_PER_BEAM); CASE_K(10,128,128,MAX_BLOCKS_PER_BEAM); CASE_K(16,128,128,5); CASE_K(32,256,128,1); CASE_K(64,256,256,1); default: topk_stage_1<T, 128, 1> <<<batch_size * beams_per_batch * 1, 128, 0, stream>>>(const_cast<T*>(log_probs), topk_tmp_id_buf, topk_tmp_val_buf, k, vocab_size); topk_stage_2<T, 128, 1> <<<batch_size, 128, k * sizeof(TopK<T>), stream>>>(topk_tmp_id_buf, topk_tmp_val_buf, topk_id_buf, topk_val_buf, beams_per_batch, vocab_size, k); break; } } }
the_stack
#include "HostDevice.hpp" #include <cuda_runtime.h> #include <limits> #include <ostream> namespace std { /** \addtogroup VectorTypeLimits * Provides numeric_limits max, min, lowest for most common CUDA vector types. * In particular, it supports short2, ushort2, short4, ushort4, short2, ushort2, * short4, ushort4, int2, uint2, int4, uint4, longlong2, ulonglong2, float2, * float4, double2 * @{ */ template<> class numeric_limits<char2> { public: static char2 min() noexcept; static char2 max() noexcept; static char2 lowest() noexcept; }; template<> class numeric_limits<uchar2> { public: static uchar2 min() noexcept; static uchar2 max() noexcept; static uchar2 lowest() noexcept; }; template<> class numeric_limits<char4> { public: static char4 min() noexcept; static char4 max() noexcept; static char4 lowest() noexcept; }; template<> class numeric_limits<uchar4> { public: static uchar4 min() noexcept; static uchar4 max() noexcept; static uchar4 lowest() noexcept; }; template<> class numeric_limits<short2> { public: static short2 min() noexcept; static short2 max() noexcept; static short2 lowest() noexcept; }; template<> class numeric_limits<ushort2> { public: static ushort2 min() noexcept; static ushort2 max() noexcept; static ushort2 lowest() noexcept; }; template<> class numeric_limits<short4> { public: static short4 min() noexcept; static short4 max() noexcept; static short4 lowest() noexcept; }; template<> class numeric_limits<ushort4> { public: static ushort4 min() noexcept; static ushort4 max() noexcept; static ushort4 lowest() noexcept; }; template<> class numeric_limits<int2> { public: static int2 min() noexcept; static int2 max() noexcept; static int2 lowest() noexcept; }; template<> class numeric_limits<uint2> { public: static uint2 min() noexcept; static uint2 max() noexcept; static uint2 lowest() noexcept; }; template<> class numeric_limits<int4> { public: static int4 min() noexcept; static int4 max() noexcept; static int4 lowest() noexcept; }; template<> class numeric_limits<uint4> { public: static uint4 min() noexcept; static uint4 max() noexcept; static uint4 lowest() noexcept; }; template<> class numeric_limits<longlong2> { public: static longlong2 min() noexcept; static longlong2 max() noexcept; static longlong2 lowest() noexcept; }; template<> class numeric_limits<ulonglong2> { public: static ulonglong2 min() noexcept; static ulonglong2 max() noexcept; static ulonglong2 lowest() noexcept; }; template<> class numeric_limits<float2> { public: static float2 min() noexcept; static float2 max() noexcept; static float2 lowest() noexcept; }; template<> class numeric_limits<float4> { public: static float4 min() noexcept; static float4 max() noexcept; static float4 lowest() noexcept; }; template<> class numeric_limits<double2> { public: static double2 min() noexcept; static double2 max() noexcept; static double2 lowest() noexcept; }; } // namespace std /** * @} */ //============================================================================== /** \addtogroup VectorTypeOstream * Provides ostream utilities for most common CUDA vector types. * In particular, it provides operator<< for short2, ushort2, short4, ushort4, * short2, ushort2, ushort4, int2, uint2, int4, uint4, long2, ulong2, float2, * float4, double2 * @{ */ inline std::ostream& operator<< (std::ostream& out, const short2& value); inline std::ostream& operator<< (std::ostream& out, const ushort2& value); inline std::ostream& operator<< (std::ostream& out, const short4& value); inline std::ostream& operator<< (std::ostream& out, const ushort4& value); inline std::ostream& operator<< (std::ostream& out, const short2& value); inline std::ostream& operator<< (std::ostream& out, const ushort2& value); inline std::ostream& operator<< (std::ostream& out, const short4& value); inline std::ostream& operator<< (std::ostream& out, const ushort4& value); inline std::ostream& operator<< (std::ostream& out, const int2& value); inline std::ostream& operator<< (std::ostream& out, const uint2& value); inline std::ostream& operator<< (std::ostream& out, const int4& value); inline std::ostream& operator<< (std::ostream& out, const uint4& value); inline std::ostream& operator<< (std::ostream& out, const long2& value); inline std::ostream& operator<< (std::ostream& out, const ulong2& value); inline std::ostream& operator<< (std::ostream& out, const float2& value); inline std::ostream& operator<< (std::ostream& out, const double2& value); /** * @} */ //============================================================================== /** \addtogroup VectorTypeCompare * Provides compare utilities for most common CUDA vector types. * In particular, it provides equal, not equal, less, less equal, greater, * greater equal for short2, ushort2, short4, ushort4, short2, ushort2, short4, * ushort4,int2, uint2, int4, uint4, long2, float2, float4, double2 * @{ */ HOST_DEVICE bool operator== (const char2& A, const char2& B); HOST_DEVICE bool operator!= (const char2& A, const char2& B); HOST_DEVICE bool operator< (const char2& A, const char2& B); HOST_DEVICE bool operator<= (const char2& A, const char2& B); HOST_DEVICE bool operator> (const char2& A, const char2& B); HOST_DEVICE bool operator>= (const char2& A, const char2& B); HOST_DEVICE bool operator== (const uchar2& A, const uchar2& B); HOST_DEVICE bool operator!= (const uchar2& A, const uchar2& B); HOST_DEVICE bool operator< (const uchar2& A, const uchar2& B); HOST_DEVICE bool operator<= (const uchar2& A, const uchar2& B); HOST_DEVICE bool operator> (const uchar2& A, const uchar2& B); HOST_DEVICE bool operator>= (const uchar2& A, const uchar2& B); HOST_DEVICE bool operator== (const char4& A, const char4& B); HOST_DEVICE bool operator!= (const char4& A, const char4& B); HOST_DEVICE bool operator< (const char4& A, const char4& B); HOST_DEVICE bool operator<= (const char4& A, const char4& B); HOST_DEVICE bool operator> (const char4& A, const char4& B); HOST_DEVICE bool operator>= (const char4& A, const char4& B); HOST_DEVICE bool operator== (const uchar4& A, const uchar4& B); HOST_DEVICE bool operator!= (const uchar4& A, const uchar4& B); HOST_DEVICE bool operator< (const uchar4& A, const uchar4& B); HOST_DEVICE bool operator<= (const uchar4& A, const uchar4& B); HOST_DEVICE bool operator> (const uchar4& A, const uchar4& B); HOST_DEVICE bool operator>= (const uchar4& A, const uchar4& B); HOST_DEVICE bool operator== (const short2& A, const short2& B); HOST_DEVICE bool operator!= (const short2& A, const short2& B); HOST_DEVICE bool operator< (const short2& A, const short2& B); HOST_DEVICE bool operator<= (const short2& A, const short2& B); HOST_DEVICE bool operator> (const short2& A, const short2& B); HOST_DEVICE bool operator>= (const short2& A, const short2& B); HOST_DEVICE bool operator== (const ushort2& A, const ushort2& B); HOST_DEVICE bool operator!= (const ushort2& A, const ushort2& B); HOST_DEVICE bool operator< (const ushort2& A, const ushort2& B); HOST_DEVICE bool operator<= (const ushort2& A, const ushort2& B); HOST_DEVICE bool operator> (const ushort2& A, const ushort2& B); HOST_DEVICE bool operator>= (const ushort2& A, const ushort2& B); HOST_DEVICE bool operator== (const short4& A, const short4& B); HOST_DEVICE bool operator!= (const short4& A, const short4& B); HOST_DEVICE bool operator< (const short4& A, const short4& B); HOST_DEVICE bool operator<= (const short4& A, const short4& B); HOST_DEVICE bool operator> (const short4& A, const short4& B); HOST_DEVICE bool operator>= (const short4& A, const short4& B); HOST_DEVICE bool operator== (const ushort4& A, const ushort4& B); HOST_DEVICE bool operator!= (const ushort4& A, const ushort4& B); HOST_DEVICE bool operator< (const ushort4& A, const ushort4& B); HOST_DEVICE bool operator<= (const ushort4& A, const ushort4& B); HOST_DEVICE bool operator> (const ushort4& A, const ushort4& B); HOST_DEVICE bool operator>= (const ushort4& A, const ushort4& B); HOST_DEVICE bool operator== (const int2& A, const int2& B); HOST_DEVICE bool operator!= (const int2& A, const int2& B); HOST_DEVICE bool operator< (const int2& A, const int2& B); HOST_DEVICE bool operator<= (const int2& A, const int2& B); HOST_DEVICE bool operator> (const int2& A, const int2& B); HOST_DEVICE bool operator>= (const int2& A, const int2& B); HOST_DEVICE bool operator== (const uint2& A, const uint2& B); HOST_DEVICE bool operator!= (const uint2& A, const uint2& B); HOST_DEVICE bool operator< (const uint2& A, const uint2& B); HOST_DEVICE bool operator<= (const uint2& A, const uint2& B); HOST_DEVICE bool operator> (const uint2& A, const uint2& B); HOST_DEVICE bool operator>= (const uint2& A, const uint2& B); HOST_DEVICE bool operator== (const int4& A, const int4& B); HOST_DEVICE bool operator!= (const int4& A, const int4& B); HOST_DEVICE bool operator< (const int4& A, const int4& B); HOST_DEVICE bool operator<= (const int4& A, const int4& B); HOST_DEVICE bool operator> (const int4& A, const int4& B); HOST_DEVICE bool operator>= (const int4& A, const int4& B); HOST_DEVICE bool operator== (const uint4& A, const uint4& B); HOST_DEVICE bool operator!= (const uint4& A, const uint4& B); HOST_DEVICE bool operator< (const uint4& A, const uint4& B); HOST_DEVICE bool operator<= (const uint4& A, const uint4& B); HOST_DEVICE bool operator> (const uint4& A, const uint4& B); HOST_DEVICE bool operator>= (const uint4& A, const uint4& B); HOST_DEVICE bool operator== (const longlong2& A, const longlong2& B); HOST_DEVICE bool operator!= (const longlong2& A, const longlong2& B); HOST_DEVICE bool operator< (const longlong2& A, const longlong2& B); HOST_DEVICE bool operator<= (const longlong2& A, const longlong2& B); HOST_DEVICE bool operator> (const longlong2& A, const longlong2& B); HOST_DEVICE bool operator>= (const longlong2& A, const longlong2& B); HOST_DEVICE bool operator== (const ulonglong2& A, const ulonglong2& B); HOST_DEVICE bool operator!= (const ulonglong2& A, const ulonglong2& B); HOST_DEVICE bool operator< (const ulonglong2& A, const ulonglong2& B); HOST_DEVICE bool operator<= (const ulonglong2& A, const ulonglong2& B); HOST_DEVICE bool operator> (const ulonglong2& A, const ulonglong2& B); HOST_DEVICE bool operator>= (const ulonglong2& A, const ulonglong2& B); HOST_DEVICE bool operator== (const float2& A, const float2& B); HOST_DEVICE bool operator!= (const float2& A, const float2& B); HOST_DEVICE bool operator< (const float2& A, const float2& B); HOST_DEVICE bool operator<= (const float2& A, const float2& B); HOST_DEVICE bool operator> (const float2& A, const float2& B); HOST_DEVICE bool operator>= (const float2& A, const float2& B); HOST_DEVICE bool operator== (const float4& A, const float4& B); HOST_DEVICE bool operator!= (const float4& A, const float4& B); HOST_DEVICE bool operator< (const float4& A, const float4& B); HOST_DEVICE bool operator<= (const float4& A, const float4& B); HOST_DEVICE bool operator> (const float4& A, const float4& B); HOST_DEVICE bool operator>= (const float4& A, const float4& B); HOST_DEVICE bool operator== (const double2& A, const double2& B); HOST_DEVICE bool operator!= (const double2& A, const double2& B); HOST_DEVICE bool operator< (const double2& A, const double2& B); HOST_DEVICE bool operator<= (const double2& A, const double2& B); HOST_DEVICE bool operator> (const double2& A, const double2& B); HOST_DEVICE bool operator>= (const double2& A, const double2& B); /** * @} */ //============================================================================== namespace xlib { /** * @brief Provides the Vector Type of dimension 2 of a given type * @details It supports char, unsigned char, short, unsigned short, int, * unsigned, long long, long long unsigned, float, double <br> * e.g. using int2 = typename Make2Str<int>::type. */ template<typename T> struct Make2Str { using type = void; }; /** * @brief Provides the Vector Type of dimension 4 of a given type * @details It supports char, unsigned char, short, unsigned short, int, * unsigned, float * e.g. using int4 = typename Make4Str<int>::type */ template<typename T> struct Make4Str { using type = void; }; /** * @brief Returns vector value of dimension 2 of two given values * @param[in] a first component * @param[in] b second component * @return vector value of dimension 2 <a, b> * @see Make2Str */ template<typename T> __host__ __device__ __forceinline__ typename Make2Str<T>::type make2(T a, T b); /** * @brief Returns vector value of dimension 2 of two given values * @param[in] a first component * @param[in] b second component * @param[in] c third component * @param[in] d fourth component * @return vector value of dimension 4 <a, b, c, d> * @see Make4Str */ template<typename T> __host__ __device__ __forceinline__ typename Make4Str<T>::type make4(T a, T b, T c, T d); } // namespace xlib #include "impl/VectorUtil.i.cuh"
the_stack
#include <simtbx/nanoBragg/nanotypes.h> #include <simtbx/nanoBragg/nanoBraggCUDA.cuh> using simtbx::nanoBragg::shapetype; using simtbx::nanoBragg::hklParams; __global__ void nanoBraggSpotsCUDAKernel(int spixels, int fpixels, int roi_xmin, int roi_xmax, int roi_ymin, int roi_ymax, int oversample, int point_pixel, CUDAREAL pixel_size, CUDAREAL subpixel_size, int steps, CUDAREAL detector_thickstep, int detector_thicksteps, CUDAREAL detector_thick, CUDAREAL detector_mu, const CUDAREAL * __restrict__ sdet_vector, const CUDAREAL * __restrict__ fdet_vector, const CUDAREAL * __restrict__ odet_vector, const CUDAREAL * __restrict__ pix0_vector, int curved_detector, CUDAREAL distance, CUDAREAL close_distance, const CUDAREAL * __restrict__ beam_vector, CUDAREAL Xbeam, CUDAREAL Ybeam, CUDAREAL dmin, CUDAREAL phi0, CUDAREAL phistep, int phisteps, const CUDAREAL * __restrict__ spindle_vector, int sources, const CUDAREAL * __restrict__ source_X, const CUDAREAL * __restrict__ source_Y, const CUDAREAL * __restrict__ source_Z, const CUDAREAL * __restrict__ source_I, const CUDAREAL * __restrict__ source_lambda, const CUDAREAL * __restrict__ a0, const CUDAREAL * __restrict__ b0, const CUDAREAL * __restrict c0, shapetype xtal_shape, CUDAREAL mosaic_spread, int mosaic_domains, const CUDAREAL * __restrict__ mosaic_umats, CUDAREAL Na, CUDAREAL Nb, CUDAREAL Nc, CUDAREAL V_cell, CUDAREAL water_size, CUDAREAL water_F, CUDAREAL water_MW, CUDAREAL r_e_sqr, CUDAREAL fluence, CUDAREAL Avogadro, CUDAREAL spot_scale, int integral_form, CUDAREAL default_F, int interpolate, const CUDAREAL * __restrict__ Fhkl, const hklParams * __restrict__ Fhklparams, int nopolar, const CUDAREAL * __restrict__ polar_vector, CUDAREAL polarization, CUDAREAL fudge, const int unsigned short * __restrict__ maskimage, float * floatimage /*out*/, float * omega_reduction/*out*/, float * max_I_x_reduction/*out*/, float * max_I_y_reduction /*out*/, bool * rangemap); __global__ void debranch_maskall_CUDAKernel(int npanels, int spixels, int fpixels, int total_pixels, int oversample, int point_pixel, CUDAREAL pixel_size, CUDAREAL subpixel_size, int steps, CUDAREAL detector_thickstep, int detector_thicksteps, CUDAREAL detector_thick, CUDAREAL detector_mu, const int vec_len, const CUDAREAL * __restrict__ sdet_vector, const CUDAREAL * __restrict__ fdet_vector, const CUDAREAL * __restrict__ odet_vector, const CUDAREAL * __restrict__ pix0_vector, const CUDAREAL * __restrict__ distance, const CUDAREAL * __restrict__ close_distance, const CUDAREAL * __restrict__ beam_vector, const CUDAREAL * __restrict__ Xbeam, const CUDAREAL * __restrict__ Ybeam, // not even used, after all the work CUDAREAL dmin, CUDAREAL phi0, CUDAREAL phistep, int phisteps, const CUDAREAL * __restrict__ spindle_vector, int sources, const CUDAREAL * __restrict__ source_X, const CUDAREAL * __restrict__ source_Y, const CUDAREAL * __restrict__ source_Z, const CUDAREAL * __restrict__ source_I, const CUDAREAL * __restrict__ source_lambda, const CUDAREAL * __restrict__ a0, const CUDAREAL * __restrict__ b0, const CUDAREAL * __restrict__ c0, shapetype xtal_shape, int mosaic_domains, const CUDAREAL * __restrict__ mosaic_umats, CUDAREAL Na, CUDAREAL Nb, CUDAREAL Nc, CUDAREAL V_cell, CUDAREAL water_size, CUDAREAL water_F, CUDAREAL water_MW, CUDAREAL r_e_sqr, CUDAREAL fluence, CUDAREAL Avogadro, CUDAREAL spot_scale, int integral_form, CUDAREAL default_F, const CUDAREAL * __restrict__ Fhkl, const hklParams * __restrict__ FhklParams, int nopolar, const CUDAREAL * __restrict__ polar_vector, CUDAREAL polarization, CUDAREAL fudge, const int * __restrict__ pixel_lookup, float * floatimage /*out*/, float * omega_reduction/*out*/, float * max_I_x_reduction/*out*/, float * max_I_y_reduction /*out*/, bool * rangemap) { __shared__ int s_vec_len; __shared__ CUDAREAL s_dmin; __shared__ bool s_nopolar; __shared__ int s_phisteps; __shared__ CUDAREAL s_phi0, s_phistep; __shared__ int s_mosaic_domains; __shared__ CUDAREAL s_Na, s_Nb, s_Nc; __shared__ int s_h_min, s_k_min, s_l_min, s_h_range, s_k_range, s_l_range, s_h_max, s_k_max, s_l_max; if (threadIdx.x == 0 && threadIdx.y == 0) { s_vec_len = vec_len; s_dmin = dmin; s_nopolar = nopolar; s_phisteps = phisteps; s_phi0 = phi0; s_phistep = phistep; s_mosaic_domains = mosaic_domains; s_Na = Na; s_Nb = Nb; s_Nc = Nc; s_h_min = FhklParams->h_min; s_k_min = FhklParams->k_min; s_l_min = FhklParams->l_min; s_h_range = FhklParams->h_range; s_k_range = FhklParams->k_range; s_l_range = FhklParams->l_range; s_h_max = s_h_min + s_h_range - 1; s_k_max = s_k_min + s_k_range - 1; s_l_max = s_l_min + s_l_range - 1; } __syncthreads(); /* Implementation notes. This kernel is aggressively debranched, therefore the assumptions are: 1) mosaicity non-zero positive 2) xtal shape is "Gauss" i.e. 3D spheroid. 3) No bounds check for access to the structure factor array. 4) No check for Flatt=0. */ //NKS new design, one-function call covers all panels with mask const int fstride = gridDim.x * blockDim.x; const int sstride = gridDim.y * blockDim.y; const int stride = fstride * sstride; /* add background from something amorphous */ CUDAREAL F_bg = water_F; CUDAREAL I_bg = F_bg * F_bg * r_e_sqr * fluence * water_size * water_size * water_size * 1e6 * Avogadro / water_MW; for (int pixIdx = (blockDim.y * blockIdx.y + threadIdx.y) * fstride + blockDim.x * blockIdx.x + threadIdx.x; pixIdx < total_pixels; pixIdx += stride) { /* position in pixel array */ const int j = pixel_lookup[pixIdx];//pixIdx: index into pixel subset; j: index into the data. const int i_panel = j / (fpixels*spixels); // the panel number const int j_panel = j % (fpixels*spixels); // the pixel number within the panel const int fpixel = j_panel % fpixels; const int spixel = j_panel / fpixels; /* reset photon count for this pixel */ CUDAREAL I = I_bg; CUDAREAL omega_sub_reduction = 0.0; CUDAREAL max_I_x_sub_reduction = 0.0; CUDAREAL max_I_y_sub_reduction = 0.0; CUDAREAL polar = 0.0; if (s_nopolar) { polar = 1.0; } /* add this now to avoid problems with skipping later */ // move this to the bottom to avoid accessing global device memory. floatimage[j] = I_bg; /* loop over sub-pixels */ int subS, subF; for (subS = 0; subS < oversample; ++subS) { // Y voxel for (subF = 0; subF < oversample; ++subF) { // X voxel /* absolute mm position on detector (relative to its origin) */ CUDAREAL Fdet = subpixel_size * (fpixel * oversample + subF) + subpixel_size / 2.0; // X voxel CUDAREAL Sdet = subpixel_size * (spixel * oversample + subS) + subpixel_size / 2.0; // Y voxel // Fdet = pixel_size*fpixel; // Sdet = pixel_size*spixel; max_I_x_sub_reduction = Fdet; max_I_y_sub_reduction = Sdet; int thick_tic; for (thick_tic = 0; thick_tic < detector_thicksteps; ++thick_tic) { /* assume "distance" is to the front of the detector sensor layer */ CUDAREAL Odet = thick_tic * detector_thickstep; // Z Orthagonal voxel. /* construct detector subpixel position in 3D space */ // pixel_X = distance; // pixel_Y = Sdet-Ybeam; // pixel_Z = Fdet-Xbeam; //CUDAREAL * pixel_pos = tmpVector1; CUDAREAL pixel_pos[4]; int iVL = s_vec_len * i_panel; pixel_pos[1] = Fdet * __ldg(&fdet_vector[iVL+1]) + Sdet * __ldg(&sdet_vector[iVL+1]) + Odet * __ldg(&odet_vector[iVL+1]) + __ldg(&pix0_vector[iVL+1]); // X pixel_pos[2] = Fdet * __ldg(&fdet_vector[iVL+2]) + Sdet * __ldg(&sdet_vector[iVL+2]) + Odet * __ldg(&odet_vector[iVL+2]) + __ldg(&pix0_vector[iVL+2]); // X pixel_pos[3] = Fdet * __ldg(&fdet_vector[iVL+3]) + Sdet * __ldg(&sdet_vector[iVL+3]) + Odet * __ldg(&odet_vector[iVL+3]) + __ldg(&pix0_vector[iVL+3]); // X /* construct the diffracted-beam unit vector to this sub-pixel */ //CUDAREAL * diffracted = tmpVector2; CUDAREAL diffracted[4]; CUDAREAL airpath = unitize(pixel_pos, diffracted); /* solid angle subtended by a pixel: (pix/airpath)^2*cos(2theta) */ CUDAREAL omega_pixel = pixel_size * pixel_size / airpath / airpath * close_distance[i_panel] / airpath; /* option to turn off obliquity effect, inverse-square-law only */ if (point_pixel) { omega_pixel = 1.0 / airpath / airpath; } /* now calculate detector thickness effects */ CUDAREAL capture_fraction = 1.0; if (detector_thick > 0.0 && detector_mu> 0.0) { /* inverse of effective thickness increase */ CUDAREAL parallax = dot_product_ldg(&(odet_vector[iVL]), diffracted); capture_fraction = exp(-thick_tic * detector_thickstep / detector_mu / parallax) - exp(-(thick_tic + 1) * detector_thickstep / detector_mu / parallax); } /* loop over sources now */ int source; for (source = 0; source < sources; ++source) { /* retrieve stuff from cache */ CUDAREAL incident[4]; incident[1] = -__ldg(&source_X[source]); incident[2] = -__ldg(&source_Y[source]); incident[3] = -__ldg(&source_Z[source]); CUDAREAL lambda = __ldg(&source_lambda[source]); CUDAREAL source_fraction = __ldg(&source_I[source]); /* construct the incident beam unit vector while recovering source distance */ // TODO[Giles]: Optimization! We can unitize the source vectors before passing them in. unitize(incident, incident); /* construct the scattering vector for this pixel */ CUDAREAL scattering[4]; scattering[1] = (diffracted[1] - incident[1]) / lambda; scattering[2] = (diffracted[2] - incident[2]) / lambda; scattering[3] = (diffracted[3] - incident[3]) / lambda; CUDAREAL stol = 0.5 * norm3d(scattering[1], scattering[2], scattering[3]); /* rough cut to speed things up when we aren't using whole detector */ if (s_dmin > 0.0 && stol > 0.0) { if (s_dmin > 0.5 / stol) { continue; } } /* polarization factor */ if (!s_nopolar) { /* need to compute polarization factor */ polar = polarization_factor(polarization, incident, diffracted, polar_vector); } else { polar = 1.0; } /* sweep over phi angles */ for (int phi_tic = 0; phi_tic < s_phisteps; ++phi_tic) { CUDAREAL phi = s_phistep * phi_tic + s_phi0; CUDAREAL ap[4]; CUDAREAL bp[4]; CUDAREAL cp[4]; /* rotate about spindle if necessary */ rotate_axis_ldg(a0, ap, spindle_vector, phi); rotate_axis_ldg(b0, bp, spindle_vector, phi); rotate_axis_ldg(c0, cp, spindle_vector, phi); /* enumerate mosaic domains */ for (int mos_tic = 0; mos_tic < s_mosaic_domains; ++mos_tic) { /* apply mosaic rotation after phi rotation */ CUDAREAL a[4]; CUDAREAL b[4]; CUDAREAL c[4]; rotate_umat_ldg(ap, a, &mosaic_umats[mos_tic * 9]); rotate_umat_ldg(bp, b, &mosaic_umats[mos_tic * 9]); rotate_umat_ldg(cp, c, &mosaic_umats[mos_tic * 9]); /* construct fractional Miller indicies */ CUDAREAL h = dot_product(a, scattering); CUDAREAL k = dot_product(b, scattering); CUDAREAL l = dot_product(c, scattering); /* round off to nearest whole index */ int h0 = ceil(h - 0.5); int k0 = ceil(k - 0.5); int l0 = ceil(l - 0.5); /* structure factor of the lattice (paralelpiped crystal) F_latt = sin(M_PI*s_Na*h)*sin(M_PI*s_Nb*k)*sin(M_PI*s_Nc*l)/sin(M_PI*h)/sin(M_PI*k)/sin(M_PI*l); */ CUDAREAL F_latt = 1.0; // Shape transform for the crystal. CUDAREAL hrad_sqr = 0.0; /* handy radius in reciprocal space, squared */ hrad_sqr = (h - h0) * (h - h0) * s_Na * s_Na + (k - k0) * (k - k0) * s_Nb * s_Nb + (l - l0) * (l - l0) * s_Nc * s_Nc; /* fudge the radius so that volume and FWHM are similar to square_xtal spots */ double my_arg = hrad_sqr / 0.63 * fudge; F_latt = s_Na * s_Nb * s_Nc * exp(-(my_arg)); /* structure factor of the unit cell */ CUDAREAL F_cell = default_F; //F_cell = quickFcell_ldg(s_hkls, s_h_max, s_h_min, s_k_max, s_k_min, s_l_max, s_l_min, h0, k0, l0, s_h_range, s_k_range, s_l_range, default_F, Fhkl); if ( h0 < s_h_min || k0 < s_k_min || l0 < s_l_min || h0 > s_h_max || k0 > s_k_max || l0 > s_l_max ) F_cell = 0.; else F_cell = __ldg(&Fhkl[(h0-s_h_min)*s_k_range*s_l_range + (k0-s_k_min)*s_l_range + (l0-s_l_min)]); /* now we have the structure factor for this pixel */ /* convert amplitudes into intensity (photons per steradian) */ I += F_cell * F_cell * F_latt * F_latt * source_fraction * capture_fraction * omega_pixel; omega_sub_reduction += omega_pixel; } /* end of mosaic loop */ } /* end of phi loop */ } /* end of source loop */ } /* end of detector thickness loop */ } /* end of sub-pixel y loop */ } /* end of sub-pixel x loop */ const double photons = I_bg + (r_e_sqr * spot_scale * fluence * polar * I) / steps; floatimage[j] = photons; omega_reduction[j] = omega_sub_reduction; // shared contention max_I_x_reduction[j] = max_I_x_sub_reduction; max_I_y_reduction[j] = max_I_y_sub_reduction; rangemap[j] = true; } } __global__ void nanoBraggSpotsInitCUDAKernel(int spixels, int fpixesl, float * floatimage, float * omega_reduction, float * max_I_x_reduction, float * max_I_y_reduction, bool * rangemap); __global__ void add_array_CUDAKernel(double * lhs, float * rhs, int array_size){ const int total_pixels = array_size; const int fstride = gridDim.x * blockDim.x; const int sstride = gridDim.y * blockDim.y; const int stride = fstride * sstride; for (int pixIdx = (blockDim.y * blockIdx.y + threadIdx.y) * fstride + blockDim.x * blockIdx.x + threadIdx.x; pixIdx < total_pixels; pixIdx += stride) { const int j = pixIdx; /* position in pixel array */ lhs[j] = lhs[j] + (double)rhs[j]; // specifically add low precision to high precision array } } __global__ void add_background_CUDAKernel(int sources, int nanoBragg_oversample, CUDAREAL pixel_size, int spixels, int fpixels, int detector_thicksteps, CUDAREAL detector_thickstep, CUDAREAL detector_attnlen, const CUDAREAL * __restrict__ sdet_vector, const CUDAREAL * __restrict__ fdet_vector, const CUDAREAL * __restrict__ odet_vector, const CUDAREAL * __restrict__ pix0_vector, CUDAREAL close_distance, int point_pixel, CUDAREAL detector_thick, const CUDAREAL * __restrict__ source_X, const CUDAREAL * __restrict__ source_Y, const CUDAREAL * __restrict__ source_Z, const CUDAREAL * __restrict__ source_lambda, const CUDAREAL * __restrict__ source_I, int stols, const CUDAREAL * stol_of, const CUDAREAL * Fbg_of, int nopolar, CUDAREAL polarization, const CUDAREAL * __restrict__ polar_vector, CUDAREAL r_e_sqr, CUDAREAL fluence, CUDAREAL amorphous_molecules, float * floatimage); __global__ void add_background_CUDAKernel(int sources, int nanoBragg_oversample, int override_source, CUDAREAL pixel_size, int spixels, int fpixels, int detector_thicksteps, CUDAREAL detector_thickstep, CUDAREAL detector_attnlen, const CUDAREAL * __restrict__ sdet_vector, const CUDAREAL * __restrict__ fdet_vector, const CUDAREAL * __restrict__ odet_vector, const CUDAREAL * __restrict__ pix0_vector, CUDAREAL close_distance, int point_pixel, CUDAREAL detector_thick, const CUDAREAL * __restrict__ source_X, const CUDAREAL * __restrict__ source_Y, const CUDAREAL * __restrict__ source_Z, const CUDAREAL * __restrict__ source_lambda, const CUDAREAL * __restrict__ source_I, int stols, const CUDAREAL * stol_of, const CUDAREAL * Fbg_of, int nopolar, CUDAREAL polarization, const CUDAREAL * __restrict__ polar_vector, CUDAREAL r_e_sqr, CUDAREAL fluence, CUDAREAL amorphous_molecules, float * floatimage) { int oversample=-1; //override features that usually slow things down, //like oversampling pixels & multiple sources int source_start = 0; int orig_sources = sources; int end_sources = sources; /* allow user to override automated oversampling decision at call time with arguments */ if(oversample<=0) oversample = nanoBragg_oversample; if(oversample<=0) oversample = 1; bool have_single_source = false; if(override_source>=0) { /* user-specified source in the argument */ source_start = override_source; end_sources = source_start +1; have_single_source = true; } /* make sure we are normalizing with the right number of sub-steps */ int steps = oversample*oversample; CUDAREAL subpixel_size = pixel_size/oversample; /* sweep over detector */ const int total_pixels = spixels * fpixels; const int fstride = gridDim.x * blockDim.x; const int sstride = gridDim.y * blockDim.y; const int stride = fstride * sstride; for (int pixIdx = (blockDim.y * blockIdx.y + threadIdx.y) * fstride + blockDim.x * blockIdx.x + threadIdx.x; pixIdx < total_pixels; pixIdx += stride) { const int fpixel = pixIdx % fpixels; const int spixel = pixIdx / fpixels; /* position in pixel array */ const int j = pixIdx; /* reset background photon count for this pixel */ CUDAREAL Ibg = 0; int nearest = 0; // sort-stable alogorithm, instead of holding value over from previous pixel /* loop over sub-pixels */ for(int subS=0;subS<oversample;++subS){ for(int subF=0;subF<oversample;++subF){ /* absolute mm position on detector (relative to its origin) */ CUDAREAL Fdet = subpixel_size*(fpixel*oversample + subF ) + subpixel_size/2.0; CUDAREAL Sdet = subpixel_size*(spixel*oversample + subS ) + subpixel_size/2.0; for(int thick_tic=0;thick_tic<detector_thicksteps;++thick_tic){ /* assume "distance" is to the front of the detector sensor layer */ CUDAREAL Odet = thick_tic*detector_thickstep; CUDAREAL pixel_pos[4]; pixel_pos[1] = Fdet * __ldg(&fdet_vector[1]) + Sdet * __ldg(&sdet_vector[1]) + Odet * __ldg(&odet_vector[1]) + __ldg(&pix0_vector[1]); // X pixel_pos[2] = Fdet * __ldg(&fdet_vector[2]) + Sdet * __ldg(&sdet_vector[2]) + Odet * __ldg(&odet_vector[2]) + __ldg(&pix0_vector[2]); // X pixel_pos[3] = Fdet * __ldg(&fdet_vector[3]) + Sdet * __ldg(&sdet_vector[3]) + Odet * __ldg(&odet_vector[3]) + __ldg(&pix0_vector[3]); // X pixel_pos[0] = 0.0; /* no curved detector option (future implementation) */ /* construct the diffracted-beam unit vector to this pixel */ CUDAREAL diffracted[4]; CUDAREAL airpath = unitize(pixel_pos,diffracted); /* solid angle subtended by a pixel: (pix/airpath)^2*cos(2theta) */ CUDAREAL omega_pixel = pixel_size*pixel_size/airpath/airpath*close_distance/airpath; /* option to turn off obliquity effect, inverse-square-law only */ if(point_pixel) omega_pixel = 1.0/airpath/airpath; /* now calculate detector thickness effects */ CUDAREAL capture_fraction = 1.0; if(detector_thick > 0.0){ /* inverse of effective thickness increase */ CUDAREAL parallax = dot_product(diffracted,odet_vector); capture_fraction = exp(-thick_tic*detector_thickstep/detector_attnlen/parallax) -exp(-(thick_tic+1)*detector_thickstep/detector_attnlen/parallax); } /* loop over sources now */ for(int source=source_start; source < end_sources; ++source){ CUDAREAL n_source_scale = (have_single_source) ? orig_sources : __ldg(&source_I[source]); /* retrieve stuff from cache */ CUDAREAL incident[4]; incident[1] = -__ldg(&source_X[source]); incident[2] = -__ldg(&source_Y[source]); incident[3] = -__ldg(&source_Z[source]); CUDAREAL lambda = __ldg(&source_lambda[source]); /* construct the incident beam unit vector while recovering source distance */ unitize(incident,incident); /* construct the scattering vector for this pixel */ CUDAREAL scattering[4]; scattering[1] = (diffracted[1]-incident[1])/lambda; scattering[2] = (diffracted[2]-incident[2])/lambda; scattering[3] = (diffracted[3]-incident[3])/lambda; magnitude(scattering); /* sin(theta)/lambda is half the scattering vector length */ CUDAREAL stol = 0.5*scattering[0]; /* now we need to find the nearest four "stol file" points */ while(stol > stol_of[nearest] && nearest <= stols){++nearest; }; while(stol < stol_of[nearest] && nearest >= 2){--nearest; }; /* cubic spline interpolation */ CUDAREAL Fbg; polint(stol_of+nearest-1, Fbg_of+nearest-1, stol, &Fbg); /* allow negative F values to yield negative intensities */ CUDAREAL sign=1.0; if(Fbg<0.0) sign=-1.0; /* now we have the structure factor for this pixel */ /* polarization factor */ CUDAREAL polar = 1.0; if(! nopolar){ /* need to compute polarization factor */ polar = polarization_factor(polarization,incident,diffracted,polar_vector); } /* accumulate unscaled pixel intensity from this */ Ibg += sign*Fbg*Fbg*polar*omega_pixel*capture_fraction*n_source_scale; } /* end of source loop */ } /* end of detector thickness loop */ } /* end of sub-pixel y loop */ } /* end of sub-pixel x loop */ /* save photons/pixel (if fluence specified), or F^2/omega if no fluence given */ floatimage[j] += Ibg*r_e_sqr*fluence*amorphous_molecules/steps; } // end of pixIdx loop } #endif // SIMTBX_GPU_SIMULATION_CUH
the_stack
namespace poisson { //------------------------------------------------------------------------ #define globalThreadIdx (threadIdx.x + blockDim.x * (threadIdx.y + blockDim.y * (blockIdx.x + gridDim.x * blockIdx.y))) #if __CUDA_ARCH__ < 350 template <class T> __device__ __forceinline__ T __ldg (const T* in) { return *in; } #endif template <class T> __device__ __forceinline__ T ld4 (const T& in) { T out; for (int ofs = 0; ofs < sizeof(T); ofs += 4) *(float*)((char*)&out + ofs) = __ldg((float*)((char*)&in + ofs)); return out; } template <class T> __device__ __forceinline__ T ld8 (const T& in) { T out; for (int ofs = 0; ofs < sizeof(T); ofs += 8) *(float2*)((char*)&out + ofs) = __ldg((float2*)((char*)&in + ofs)); return out; } template <class T> __device__ __forceinline__ T ld16 (const T& in) { T out; for (int ofs = 0; ofs < sizeof(T); ofs += 16) *(float4*)((char*)&out + ofs) = __ldg((float4*)((char*)&in + ofs)); return out; } //------------------------------------------------------------------------ BackendCUDA::BackendCUDA(int device) { assert(device >= -1); // No device specified => choose one. if (device == -1) { device = chooseDevice(); if (device == -1) fail("No suitable CUDA device found!"); } // Initialize. cudaDeviceProp prop; cudaGetDeviceProperties(&prop, device); cudaSetDevice(device); checkError(); printf("Using CUDA device %d: %s\n", device, prop.name); if (prop.major < 3) fail("Compute capability 3.0 or higher is required!"); m_maxGridWidth = prop.maxGridSize[0]; m_blockDim = (prop.major >= 5) ? dim3(32, 2, 1) : dim3(32, 4, 1); } //------------------------------------------------------------------------ BackendCUDA::~BackendCUDA(void) { } //------------------------------------------------------------------------ int BackendCUDA::chooseDevice(void) { int numDevices = 0; cudaGetDeviceCount(&numDevices); int bestDevice = -1; cudaDeviceProp bestProp; memset(&bestProp, 0, sizeof(bestProp)); for (int d = 0; d < numDevices; d++) { cudaDeviceProp p; cudaGetDeviceProperties(&p, d); if (p.major < 3) // need at least sm_30 continue; if (bestDevice == -1 || (p.major != bestProp.major) ? (p.major > bestProp.major) : (p.minor != bestProp.minor) ? (p.minor > bestProp.minor) : (p.multiProcessorCount > bestProp.multiProcessorCount)) { bestDevice = d; bestProp = p; } } checkError(); return bestDevice; } //------------------------------------------------------------------------ void BackendCUDA::checkError(void) { cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) fail("CUDA runtime error: %s!", cudaGetErrorString(error)); } //------------------------------------------------------------------------ BackendCUDA::Vector* BackendCUDA::allocVector(int numElems, size_t bytesPerElem) { assert(numElems >= 0); assert(bytesPerElem > 0); Vector* x = new Vector; x->numElems = numElems; x->bytesPerElem = bytesPerElem; x->bytesTotal = numElems * bytesPerElem; x->ptr = NULL; cudaMalloc(&x->ptr, x->bytesTotal); checkError(); return x; } //------------------------------------------------------------------------ void BackendCUDA::freeVector(Vector* x) { if (x && x->ptr) { cudaFree(x->ptr); checkError(); } delete x; } //------------------------------------------------------------------------ void* BackendCUDA::map(Vector* x) { assert(x); void* ptr = NULL; cudaMallocHost(&ptr, x->bytesTotal); cudaMemcpy(ptr, x->ptr, x->bytesTotal, cudaMemcpyDeviceToHost); checkError(); return ptr; } //------------------------------------------------------------------------ void BackendCUDA::unmap(Vector* x, void* ptr, bool modified) { if (ptr) { if (modified && x) cudaMemcpy(x->ptr, ptr, x->bytesTotal, cudaMemcpyHostToDevice); cudaFreeHost(ptr); checkError(); } } //------------------------------------------------------------------------ __global__ void kernel_set(float* x, float y, int numElems) { int i = globalThreadIdx; if (i >= numElems) return; x[i] = y; } //------------------------------------------------------------------------ void BackendCUDA::set(Vector* x, float y) { assert(x && x->bytesPerElem % sizeof(float) == 0); int numElems = (int)(x->bytesTotal / sizeof(float)); cudaFuncSetCacheConfig(&kernel_set, cudaFuncCachePreferL1); kernel_set<<<gridDim(numElems), m_blockDim>>> ((float*)x->ptr, y, numElems); checkError(); } //------------------------------------------------------------------------ void BackendCUDA::copy(Vector* x, Vector* y) { assert(x && y && x->bytesTotal == y->bytesTotal); cudaMemcpy(x->ptr, y->ptr, x->bytesTotal, cudaMemcpyDeviceToDevice); checkError(); } //------------------------------------------------------------------------ void BackendCUDA::read(void* ptr, Vector* x) { assert(ptr && x); cudaMemcpy(ptr, x->ptr, x->bytesTotal, cudaMemcpyDeviceToHost); checkError(); } //------------------------------------------------------------------------ void BackendCUDA::write(Vector* x, const void* ptr) { assert(x && ptr); cudaMemcpy(x->ptr, ptr, x->bytesTotal, cudaMemcpyHostToDevice); checkError(); } //------------------------------------------------------------------------ __global__ void kernel_Px(Vec3f* Px, const Vec3f* x, Vec2i size, float alpha) { int xx = threadIdx.x + blockIdx.x * blockDim.x; int yy = threadIdx.y + blockIdx.y * blockDim.y; if (xx >= size.x || yy >= size.y) return; int i = xx + yy * size.x; int n = size.x * size.y; Vec3f xi = ld4(x[i]); Px[n * 0 + i] = xi * alpha; Px[n * 1 + i] = (xx != size.x - 1) ? ld4(x[i + 1]) - xi : 0.0f; Px[n * 2 + i] = (yy != size.y - 1) ? ld4(x[i + size.x]) - xi : 0.0f; } //------------------------------------------------------------------------ void BackendCUDA::calc_Px(Vector* Px, PoissonMatrix P, Vector* x) { assert(Px && Px->numElems == P.size.x * P.size.y * 3 && Px->bytesPerElem == sizeof(Vec3f)); assert(P.size.x >= 0 && P.size.y >= 0); assert(x && x->numElems == P.size.x * P.size.y && x->bytesPerElem == sizeof(Vec3f)); cudaFuncSetCacheConfig(&kernel_Px, cudaFuncCachePreferL1); kernel_Px<<<gridDim(P.size.x, P.size.y), m_blockDim>>> ((Vec3f*)Px->ptr, (const Vec3f*)x->ptr, P.size, P.alpha); checkError(); } //------------------------------------------------------------------------ __global__ void kernel_PTW2x(Vec3f* PTW2x, const float* w2, const Vec3f* x, Vec2i size, float alpha) { int xx = threadIdx.x + blockIdx.x * blockDim.x; int yy = threadIdx.y + blockIdx.y * blockDim.y; if (xx >= size.x || yy >= size.y) return; int i = xx + yy * size.x; int n = size.x * size.y; Vec3f PTW2xi = ld4(w2[n * 0 + i]) * ld4(x[n * 0 + i]) * alpha; if (xx != 0) PTW2xi += ld4(w2[n * 1 + i - 1]) * ld4(x[n * 1 + i - 1]); if (xx != size.x - 1) PTW2xi -= ld4(w2[n * 1 + i]) * ld4(x[n * 1 + i]); if (yy != 0) PTW2xi += ld4(w2[n * 2 + i - size.x]) * ld4(x[n * 2 + i - size.x]); if (yy != size.y - 1) PTW2xi -= ld4(w2[n * 2 + i]) * ld4(x[n * 2 + i]); PTW2x[i] = PTW2xi; } //------------------------------------------------------------------------ void BackendCUDA::calc_PTW2x(Vector* PTW2x, PoissonMatrix P, Vector* w2, Vector* x) { assert(PTW2x && PTW2x->numElems == P.size.x * P.size.y && PTW2x->bytesPerElem == sizeof(Vec3f)); assert(P.size.x >= 0 && P.size.y >= 0); assert(w2 && w2->numElems == P.size.x * P.size.y * 3 && w2->bytesPerElem == sizeof(float)); assert(x && x->numElems == P.size.x * P.size.y * 3 && x->bytesPerElem == sizeof(Vec3f)); cudaFuncSetCacheConfig(&kernel_PTW2x, cudaFuncCachePreferL1); kernel_PTW2x<<<gridDim(P.size.x, P.size.y), m_blockDim>>> ((Vec3f*)PTW2x->ptr, (const float*)w2->ptr, (const Vec3f*)x->ptr, P.size, P.alpha); checkError(); } //------------------------------------------------------------------------ __global__ void kernel_Ax_xAx(Vec3f* Ax, Vec3f* xAx, const float* w2, const Vec3f* x, Vec2i size, int elemsPerThread, float alphaSqr) { int xxbegin = threadIdx.x + blockIdx.x * (elemsPerThread * 32); int xxend = ::min(xxbegin + elemsPerThread * 32, size.x); int yy = threadIdx.y + blockIdx.y * blockDim.y; if (yy >= size.y || xxbegin >= xxend) return; Vec3f sum = 0.0f; int n = size.x * size.y; for (int xx = xxbegin; xx < xxend; xx += 32) { int i = xx + yy * size.x; Vec3f xi = ld4(x[i]); Vec3f Axi = ld4(w2[n * 0 + i]) * xi * alphaSqr; if (xx != 0) Axi += ld4(w2[n * 1 + i - 1]) * (xi - ld4(x[i - 1])); if (xx != size.x - 1) Axi += ld4(w2[n * 1 + i]) * (xi - ld4(x[i + 1])); if (yy != 0) Axi += ld4(w2[n * 2 + i - size.x]) * (xi - ld4(x[i - size.x])); if (yy != size.y - 1) Axi += ld4(w2[n * 2 + i]) * (xi - ld4(x[i + size.x])); Ax[i] = Axi; sum += xi * Axi; } for (int c = 0; c < 3; c++) { float t = sum[c]; for (int i = 1; i < 32; i *= 2) t += __shfl_xor(t, i); if (threadIdx.x == 0) atomicAdd(&xAx->x + c, t); } } //------------------------------------------------------------------------ void BackendCUDA::calc_Ax_xAx(Vector* Ax, Vector* xAx, PoissonMatrix P, Vector* w2, Vector* x) { assert(Ax && Ax->numElems == P.size.x * P.size.y && Ax->bytesPerElem == sizeof(Vec3f)); assert(xAx && xAx->numElems == 1 && xAx->bytesPerElem == sizeof(Vec3f)); assert(P.size.x >= 0 && P.size.y >= 0); assert(w2 && w2->numElems == P.size.x * P.size.y * 3 && w2->bytesPerElem == sizeof(float)); assert(x && x->numElems == P.size.x * P.size.y && x->bytesPerElem == sizeof(Vec3f)); int elemsPerThread = 2; int totalThreadsX = (P.size.x - 1) / elemsPerThread + 1; set(xAx, 0.0f); cudaFuncSetCacheConfig(&kernel_Ax_xAx, cudaFuncCachePreferL1); kernel_Ax_xAx<<<gridDim(totalThreadsX, P.size.y), m_blockDim>>> ((Vec3f*)Ax->ptr, (Vec3f*)xAx->ptr, (const float*)w2->ptr, (const Vec3f*)x->ptr, P.size, elemsPerThread, P.alpha * P.alpha); checkError(); } //------------------------------------------------------------------------ __global__ void kernel_axpy(Vec3f* axpy, Vec3f a, const Vec3f* x, const Vec3f* y, int numElems) { int i = globalThreadIdx; if (i >= numElems) return; axpy[i] = a * ld4(x[i]) + ld4(y[i]); } //------------------------------------------------------------------------ void BackendCUDA::calc_axpy(Vector* axpy, Vec3f a, Vector* x, Vector* y) { assert(axpy && axpy->numElems == x->numElems && axpy->bytesPerElem == sizeof(Vec3f)); assert(x && x->bytesPerElem == sizeof(Vec3f)); assert(y && y->numElems == x->numElems && y->bytesPerElem == sizeof(Vec3f)); cudaFuncSetCacheConfig(&kernel_axpy, cudaFuncCachePreferL1); kernel_axpy<<<gridDim(x->numElems), m_blockDim>>> ((Vec3f*)axpy->ptr, a, (const Vec3f*)x->ptr, (const Vec3f*)y->ptr, x->numElems); checkError(); } //------------------------------------------------------------------------ __global__ void kernel_xdoty(Vec3f* xdoty, const Vec3f* x, const Vec3f* y, int numElems, int elemsPerThread) { int begin = globalThreadIdx; begin = (begin & 31) + (begin & ~31) * elemsPerThread; int end = ::min(begin + elemsPerThread * 32, numElems); if (begin >= end) return; Vec3f sum = 0.0f; for (int i = begin; i < end; i += 32) sum += ld4(x[i]) * ld4(y[i]); for (int c = 0; c < 3; c++) { float t = sum[c]; for (int i = 1; i < 32; i *= 2) t += __shfl_xor(t, i); if (threadIdx.x == 0) atomicAdd(&xdoty->x + c, t); } } //------------------------------------------------------------------------ void BackendCUDA::calc_xdoty(Vector* xdoty, Vector* x, Vector* y) { assert(xdoty && xdoty->numElems == 1 && xdoty->bytesPerElem == sizeof(Vec3f)); assert(x && x->bytesPerElem == sizeof(Vec3f)); assert(y && y->numElems == x->numElems && y->bytesPerElem == sizeof(Vec3f)); int elemsPerThread = 2; int totalThreads = (x->numElems - 1) / elemsPerThread + 1; set(xdoty, 0.0f); cudaFuncSetCacheConfig(&kernel_xdoty, cudaFuncCachePreferL1); kernel_xdoty<<<gridDim(totalThreads), m_blockDim>>> ((Vec3f*)xdoty->ptr, (const Vec3f*)x->ptr, (const Vec3f*)y->ptr, x->numElems, elemsPerThread); checkError(); } //------------------------------------------------------------------------ __global__ void kernel_r_rz(Vec3f* r, Vec3f* rz, const Vec3f* Ap, const Vec3f* rz2, const Vec3f* pAp, int numPixels, int elemsPerThread) { int begin = globalThreadIdx; begin = (begin & 31) + (begin & ~31) * elemsPerThread; int end = ::min(begin + elemsPerThread * 32, numPixels); if (begin >= end) return; Vec3f a = ld4(*rz2) / max(ld4(*pAp), FLT_MIN); Vec3f sum = 0.0f; for (int i = begin; i < end; i += 32) { Vec3f ri = ld4(r[i]) - ld4(Ap[i]) * a; r[i] = ri; sum += ri * ri; } for (int c = 0; c < 3; c++) { float t = sum[c]; for (int i = 1; i < 32; i *= 2) t += __shfl_xor(t, i); if (threadIdx.x == 0) atomicAdd(&rz->x + c, t); } } //------------------------------------------------------------------------ void BackendCUDA::calc_r_rz(Vector* r, Vector* rz, Vector* Ap, Vector* rz2, Vector* pAp) { assert(r && r->bytesPerElem == sizeof(Vec3f)); assert(rz && rz->numElems == 1 && rz->bytesPerElem == sizeof(Vec3f)); assert(Ap && Ap->numElems == r->numElems && Ap->bytesPerElem == sizeof(Vec3f)); assert(rz2 && rz2->numElems == 1 && rz2->bytesPerElem == sizeof(Vec3f)); assert(pAp && pAp->numElems == 1 && pAp->bytesPerElem == sizeof(Vec3f)); int elemsPerThread = 2; int totalThreads = (r->numElems - 1) / elemsPerThread + 1; set(rz, 0.0f); cudaFuncSetCacheConfig(&kernel_r_rz, cudaFuncCachePreferL1); kernel_r_rz<<<gridDim(totalThreads), m_blockDim>>> ((Vec3f*)r->ptr, (Vec3f*)rz->ptr, (const Vec3f*)Ap->ptr, (const Vec3f*)rz2->ptr, (const Vec3f*)pAp->ptr, r->numElems, elemsPerThread); checkError(); } //------------------------------------------------------------------------ __global__ void kernel_x_p(Vec3f* x, Vec3f* p, const Vec3f* r, const Vec3f* rz, const Vec3f* rz2, const Vec3f* pAp, int numElems) { int i = globalThreadIdx; if (i >= numElems) return; Vec3f rzv = ld4(*rz); Vec3f rz2v = ld4(*rz2); Vec3f pApv = ld4(*pAp); Vec3f a = rz2v / max(pApv, FLT_MIN); Vec3f b = rzv / max(rz2v, FLT_MIN); Vec3f pi = ld4(p[i]); x[i] += pi * a; p[i] = ld4(r[i]) + pi * b; } //------------------------------------------------------------------------ void BackendCUDA::calc_x_p(Vector* x, Vector* p, Vector* r, Vector* rz, Vector* rz2, Vector* pAp) { assert(x && x->bytesPerElem == sizeof(Vec3f)); assert(p && p->numElems == x->numElems && p->bytesPerElem == sizeof(Vec3f)); assert(r && r->numElems == x->numElems && r->bytesPerElem == sizeof(Vec3f)); assert(rz && rz->numElems == 1 && rz->bytesPerElem == sizeof(Vec3f)); assert(rz2 && rz2->numElems == 1 && rz2->bytesPerElem == sizeof(Vec3f)); assert(pAp && pAp->numElems == 1 && pAp->bytesPerElem == sizeof(Vec3f)); cudaFuncSetCacheConfig(&kernel_x_p, cudaFuncCachePreferL1); kernel_x_p<<<gridDim(x->numElems), m_blockDim>>> ((Vec3f*)x->ptr, (Vec3f*)p->ptr, (const Vec3f*)r->ptr, (const Vec3f*)rz->ptr, (const Vec3f*)rz2->ptr, (const Vec3f*)pAp->ptr, x->numElems); checkError(); } //------------------------------------------------------------------------ __global__ void kernel_w2sum(float* w2sum, const Vec3f* e, float reg, int numElems, int elemsPerThread) { int begin = globalThreadIdx; begin = (begin & 31) + (begin & ~31) * elemsPerThread; int end = ::min(begin + elemsPerThread * 32, numElems); if (begin >= end) return; float sum = 0.0f; for (int i = begin; i < end; i += 32) sum += 1.0f / (length(ld4(e[i])) + reg); for (int i = 1; i < 32; i *= 2) sum += __shfl_xor(sum, i); if (threadIdx.x == 0) atomicAdd(w2sum, sum); } //------------------------------------------------------------------------ __global__ void kernel_w2(float* w2, const Vec3f* e, float reg, int numElems, float coef) { int i = globalThreadIdx; if (i >= numElems) return; w2[i] = coef / (length(ld4(e[i])) + reg); } //------------------------------------------------------------------------ void BackendCUDA::calc_w2(Vector* w2, Vector* e, float reg) { assert(w2 && w2->bytesPerElem == sizeof(float)); assert(e && e->numElems == w2->numElems && e->bytesPerElem == sizeof(Vec3f)); int elemsPerThread = 2; int totalThreads = (w2->numElems - 1) / elemsPerThread + 1; cudaMemset(w2->ptr, 0, sizeof(float)); cudaFuncSetCacheConfig(&kernel_w2sum, cudaFuncCachePreferL1); kernel_w2sum<<<gridDim(totalThreads), m_blockDim>>> ((float*)w2->ptr, (const Vec3f*)e->ptr, reg, w2->numElems, elemsPerThread); float w2sum = 0.0f; cudaMemcpy(&w2sum, w2->ptr, sizeof(float), cudaMemcpyDeviceToHost); float coef = (float)w2->numElems / w2sum; // normalize so that average(w2) = 1 cudaFuncSetCacheConfig(&kernel_w2, cudaFuncCachePreferL1); kernel_w2<<<gridDim(w2->numElems), m_blockDim>>> ((float*)w2->ptr, (const Vec3f*)e->ptr, reg, w2->numElems, coef); checkError(); } //------------------------------------------------------------------------ __global__ void kernel_tonemapSRGB(unsigned int* out, const Vec3f* in, int numPixels, float scale, float bias) { int i = globalThreadIdx; if (i >= numPixels) return; Vec3f color = ld4(in[i]); for (int c = 0; c < 3; c++) { float& t = color[c]; t = t * scale + bias; t = (t <= 0.0031308f) ? 12.92f * t : 1.055f * powf(t, 1.0f / 2.4f) - 0.055f; // linear to sRGB } out[i] = 0xFF000000 | ((int)min(max(color.x * 255.0f + 0.5f, 0.0f), 255.0f) << 0) | ((int)min(max(color.y * 255.0f + 0.5f, 0.0f), 255.0f) << 8) | ((int)min(max(color.z * 255.0f + 0.5f, 0.0f), 255.0f) << 16); } //------------------------------------------------------------------------ void BackendCUDA::tonemapSRGB(Vector* out, Vector* in, int idx, float scale, float bias) { assert(out && out->bytesPerElem == sizeof(unsigned int)); assert(in && in->numElems % out->numElems == 0 && in->bytesPerElem == sizeof(Vec3f)); cudaFuncSetCacheConfig(&kernel_tonemapSRGB, cudaFuncCachePreferL1); kernel_tonemapSRGB<<<gridDim(out->numElems), m_blockDim>>> ((unsigned int*)out->ptr, (const Vec3f*)in->ptr + idx * out->bytesTotal, out->numElems, scale, bias); checkError(); } //------------------------------------------------------------------------ __global__ void kernel_tonemapLinearA(unsigned int* minmaxU32, const float* in, int numPixels, int numComponents) { int i = globalThreadIdx; if (i >= numPixels) return; float inMin = +FLT_MAX; float inMax = -FLT_MAX; for (int c = 0; c < numComponents; c++) { float t = ld4(in[i * numComponents + c]); inMin = fminf(inMin, t); inMax = fmaxf(inMax, t); } unsigned int minU32 = __float_as_int(inMin); unsigned int maxU32 = __float_as_int(inMax); atomicMin(&minmaxU32[0], minU32 ^ (((int)minU32 >> 31) | 0x80000000u)); atomicMax(&minmaxU32[1], maxU32 ^ (((int)maxU32 >> 31) | 0x80000000u)); } //------------------------------------------------------------------------ __global__ void kernel_tonemapLinearB(unsigned int* out, const float* in, int numPixels, int numComponents, float scale, float bias) { int i = globalThreadIdx; if (i >= numPixels) return; Vec3f color; for (int c = 0; c < 3; c++) color[c] = (c < numComponents) ? fabsf(ld4(in[i * numComponents + c]) * scale + bias) : color[c - 1]; out[i] = 0xFF000000 | ((int)min(max(color.x * 255.0f + 0.5f, 0.0f), 255.0f) << 0) | ((int)min(max(color.y * 255.0f + 0.5f, 0.0f), 255.0f) << 8) | ((int)min(max(color.z * 255.0f + 0.5f, 0.0f), 255.0f) << 16); } //------------------------------------------------------------------------ void BackendCUDA::tonemapLinear(Vector* out, Vector* in, int idx, float scaleMin, float scaleMax, bool hasNegative) { assert(out && out->numElems >= 2 && out->bytesPerElem == sizeof(unsigned int)); assert(in && in->numElems % out->numElems == 0 && in->bytesPerElem % sizeof(float) == 0); int numComponents = (int)(in->bytesPerElem / sizeof(float)); Vec2i minmaxU32(~0u, 0u); cudaMemcpy(out->ptr, &minmaxU32, sizeof(Vec2i), cudaMemcpyHostToDevice); cudaFuncSetCacheConfig(&kernel_tonemapLinearA, cudaFuncCachePreferL1); kernel_tonemapLinearA<<<gridDim(out->numElems), m_blockDim>>> ((unsigned int*)out->ptr, (const float*)in->ptr + idx * out->bytesTotal, out->numElems, numComponents); cudaMemcpy(&minmaxU32, out->ptr, sizeof(Vec2i), cudaMemcpyDeviceToHost); minmaxU32.x ^= ~((int)minmaxU32.x >> 31) | 0x80000000u; minmaxU32.y ^= ~((int)minmaxU32.y >> 31) | 0x80000000u; float inMin = *(float*)&minmaxU32.x; float inMax = *(float*)&minmaxU32.y; float scale = min(max((hasNegative) ? 0.5f / max(max(-inMin, inMax), FLT_MIN) : 1.0f / max(inMax, FLT_MIN), scaleMin), scaleMax); float bias = (hasNegative) ? 0.5f : 0.0f; cudaFuncSetCacheConfig(&kernel_tonemapLinearB, cudaFuncCachePreferL1); kernel_tonemapLinearB<<<gridDim(out->numElems), m_blockDim>>> ((unsigned int*)out->ptr, (const float*)in->ptr + idx * out->bytesTotal, out->numElems, numComponents, scale, bias); checkError(); } //------------------------------------------------------------------------ Backend::Timer* BackendCUDA::allocTimer(void) { TimerCUDA* timerCUDA = new TimerCUDA; timerCUDA->beginTicks = 0; timerCUDA->beginEvent = NULL; timerCUDA->endEvent = NULL; cudaEventCreate(&timerCUDA->beginEvent); cudaEventCreate(&timerCUDA->endEvent); checkError(); return timerCUDA; } //------------------------------------------------------------------------ void BackendCUDA::freeTimer(Timer* timer) { TimerCUDA* timerCUDA = (TimerCUDA*)timer; if (timerCUDA) { cudaEventDestroy(timerCUDA->beginEvent); cudaEventDestroy(timerCUDA->endEvent); checkError(); delete timerCUDA; } } //------------------------------------------------------------------------ void BackendCUDA::beginTimer(Timer* timer) { assert(timer); TimerCUDA* timerCUDA = (TimerCUDA*)timer; cudaDeviceSynchronize(); cudaEventRecord(timerCUDA->beginEvent); checkError(); } //------------------------------------------------------------------------ float BackendCUDA::endTimer(Timer* timer) { assert(timer); TimerCUDA* timerCUDA = (TimerCUDA*)timer; cudaEventRecord(timerCUDA->endEvent); cudaDeviceSynchronize(); float millis = 0.0f; cudaEventElapsedTime(&millis, timerCUDA->beginEvent, timerCUDA->endEvent); checkError(); return millis * 1.0e-3f; } //------------------------------------------------------------------------ dim3 BackendCUDA::gridDim(int totalThreadsX, int totalThreadsY) { dim3 gd; gd.x = (totalThreadsX - 1) / m_blockDim.x + 1; gd.y = (totalThreadsY - 1) / m_blockDim.y + 1; gd.z = 1; while ((int)gd.x > m_maxGridWidth) { gd.x /= 2; gd.y *= 2; } return gd; } //------------------------------------------------------------------------ } // namespace poisson
the_stack
#include "filterinterpolation_cuda_kernel.cuh" #include <ATen/ATen.h> #include <ATen/NativeFunctions.h> #include <ATen/Dispatch.h> #include <ATen/cuda/CUDAApplyUtils.cuh> #define min(a,b) ((a<b)?(a):(b)) #define max(a,b) ((a>b)?(a):(b)) #define DEBUG (0) #ifndef BLOCKDIMX #define BLOCKDIMX (32) #endif #ifndef BLOCKDIMY #define BLOCKDIMY (16) #endif using at::Half; //forward path of our layer template <typename scalar_t> __global__ void FilterInterpolationLayer_gpu_forward_kernelfunc( const int nElement, const int w, const int h, const int channel, const int filter_size, const int input1_b_stride, const int input1_c_stride, const int input1_h_stride, const int input1_w_stride, const int input2_b_stride, const int input2_c_stride, const int input2_h_stride, const int input2_w_stride, const int input3_b_stride, const int input3_c_stride, const int input3_h_stride, const int input3_w_stride, const scalar_t* __restrict__ input1, const scalar_t* __restrict__ input2, const scalar_t* __restrict__ input3, scalar_t* output ) { //blockIdx.z : batch index from 0~B-1 //blockIdx.y : height patch index from ceil(h/16) //blockIdx.x : width patch index from ceil(w/32) //threadidx.x: width index 0~31 //threadIdx.y: height index 0~15 //threadIdx.z: Not used //only use one dimensioon of the grid and block const int w_i = blockIdx.x * blockDim.x + threadIdx.x; const int h_i = blockIdx.y * blockDim.y + threadIdx.y; const bool withinXbounds = w_i < w; const bool withinYbounds = h_i < h; const int batch_i = blockIdx.z; const int off = batch_i * input1_b_stride; // __syncthreads(); // const float fillvalue =0.0f; if( withinXbounds && withinYbounds) { float fx = input2[batch_i * input2_b_stride + 0 * input2_c_stride + h_i * input2_h_stride + w_i ]; float fy = input2[batch_i * input2_b_stride + 1 * input2_c_stride + h_i * input2_h_stride + w_i ]; float x2 = (float)(w_i) + fx; float y2 = (float)(h_i) + fy; if(x2 >= 0.0f && y2 >=0.0f && x2 <= (float)(w -1) && y2 <= (float)(h-1) && fabs(fx) < (float)(w)/2.0f && fabs(fy) < (float)(h)/2.0f){ int ix2_L = int(x2) + 1 - (int)(filter_size / 2); int iy2_T = int(y2) + 1 - (int)(filter_size / 2); int ix2_R = ix2_L + filter_size; int iy2_B = iy2_T + filter_size; float alpha = x2 - (int)(x2); float beta = y2 - (int)(y2); //TODO: here is a bug that if the iy2_B or ix2_R gets out of the border, than there is no enough pixels to warp the target one. for (int c_i = 0 ; c_i < channel ; c_i++){ float TL = 0.0f; for(int filter_j = iy2_T; filter_j <= (int)(y2); filter_j ++){ int _filter_j = min(max(0, filter_j), h - 1); for( int filter_i = ix2_L; filter_i <= (int) ( x2) ; filter_i ++ ){ int _filter_i = min(max(0, filter_i ), w - 1); TL += input1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i ] * input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i] ; } } float TR = 0.0f; for (int filter_j = iy2_T; filter_j <= (int) (y2); filter_j ++ ){ int _filter_j = min(max(0, filter_j),h - 1); // only used for input1 for (int filter_i = (int) (x2) + 1 ; filter_i < ix2_R; filter_i ++ ){ int _filter_i = min(max(0, filter_i),w - 1);// only used for input1 TR += input1 [off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i] * input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]; } } float BL = 0.0f; for (int filter_j = (int) (y2) + 1; filter_j < iy2_B; filter_j ++ ){ int _filter_j = min(max(0, filter_j),h - 1); // only used for input1 for (int filter_i = ix2_L; filter_i <= (int) (x2); filter_i ++ ){ int _filter_i = min(max(0, filter_i),w - 1);// only used for input1 BL += input1 [off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i] * input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]; } } float BR = 0.0f; for (int filter_j = (int) (y2) + 1; filter_j < iy2_B; filter_j ++ ){ int _filter_j = min(max(0, filter_j),h - 1); // only used for input1 for (int filter_i = (int) (x2) + 1; filter_i < ix2_R; filter_i ++ ){ int _filter_i = min(max(0, filter_i),w - 1);// only used for input1 BR += input1 [off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i] * input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]; } } output[off + c_i * input1_c_stride + h_i * input1_h_stride + w_i ] = (1-alpha)*(1-beta)*TL + alpha*(1-beta)*TR + (1-alpha)*beta*BL + alpha*beta*BR; // for( int filter_i = ix2_L; filter_i < ix2_R ; filter_i ++ ){ // int _filter_i = min(max(0, filter_i),w - 1); // output[off + c_i * input1_c_stride + h_i * input1_h_stride + w_i ] += // input1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i ] * // input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i] * //// exp( -(fabs((float) filter_j - y2) + fabs((float) filter_i - x2)) / (float)(filter_size)); // the distance weight // exp( -(fabs((float) filter_j - y2) + fabs((float) filter_i - x2)) ); // the distance weight // //// if(w_i == 141 && h_i == 316 && c_i == 0 ){ ////printf("gpu: %f, %f,%f,%f\n",input1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i ] , ////input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i], ////exp( -(fabs((float) filter_j - y2) + fabs((float) filter_i - x2)) / (float)(filter_size)), ////output[off + c_i * input1_c_stride + h_i * input1_h_stride + w_i ] //// ); ////} // // } // } } } else{ //the warping data is out of range, we fill it with zeros for(int c_i = 0 ; c_i < channel; c_i ++){ output[off + c_i * input1_c_stride + h_i * input1_h_stride + w_i] = input1[off + c_i* input1_c_stride+ h_i * input1_h_stride + w_i]; } } } return ; } template <typename scalar_t> __global__ void FilterInterpolationLayer_gpu_backward_kernelfunc( const int nElement, const int w, const int h, const int channel, const int filter_size, const int input1_b_stride, const int input1_c_stride, const int input1_h_stride, const int input1_w_stride, const int input2_b_stride, const int input2_c_stride, const int input2_h_stride, const int input2_w_stride, const int input3_b_stride, const int input3_c_stride, const int input3_h_stride, const int input3_w_stride, const scalar_t* __restrict__ input1, const scalar_t* __restrict__ input2, const scalar_t* __restrict__ input3, scalar_t* gradoutput, scalar_t* gradinput1, scalar_t* gradinput2, scalar_t* gradinput3 ) { //blockIdx.z : batch index from 0~B-1 //blockIdx.y : height patch index from ceil(h/16) //blockIdx.x : width patch index from ceil(w/32) //threadidx.x: width index 0~31 //threadIdx.y: height index 0~15 //threadIdx.z: Not used const int w_i = blockIdx.x * blockDim.x + threadIdx.x; const int h_i = blockIdx.y * blockDim.y + threadIdx.y; const bool withinXbounds = w_i < w; const bool withinYbounds = h_i < h; const int batch_i = blockIdx.z; const int off = batch_i * input1_b_stride; // __syncthreads(); if(withinXbounds && withinYbounds){ float fx = input2[batch_i * input2_b_stride + 0 * input2_c_stride + h_i * input2_h_stride + w_i]; float fy = input2[batch_i * input2_b_stride + 1 * input2_c_stride + h_i * input2_h_stride + w_i]; float x2 = float(w_i) + fx; float y2 = float(h_i) + fy; if(x2 >= 0.0f && y2 >= 0.0f && x2 <= (float)(w - 1) && y2 <= (float)(h -1) && fabs(fx) < (float)(w)/2.0f && fabs(fy) < (float)(h)/2.0f){ int ix2_L = int(x2) + 1 - (int) (filter_size/2); int iy2_T = int(y2) + 1 - (int) (filter_size/2); int ix2_R = ix2_L + filter_size; int iy2_B = iy2_T + filter_size; float alpha = x2 - (int)(x2); float beta = y2 - (int)(y2); /*** Step 1: calculate the gradients for input1, i.e. the input image; ***/ /*** STEP 3: calculate the gradients for input3, i.e. the filter ***/ /*** Step 1 and Step 3 are simultaneously computed ***/ for (int c_i = 0 ; c_i < channel; c_i++){ float gradoutput_value = gradoutput[off + c_i * input1_c_stride + h_i * input1_h_stride + w_i]; float TL_grad = gradoutput_value * (1-alpha ) * (1-beta); for(int filter_j = iy2_T; filter_j <= (int) (y2) ; filter_j ++ ){ int _filter_j = min(max(0, filter_j), h - 1); for (int filter_i = ix2_L ; filter_i <= (int)(x2) ; filter_i ++){ int _filter_i = min(max(0, filter_i), w - 1); atomicAdd( &gradinput1[off +c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i ], TL_grad * input3[batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]); atomicAdd( & gradinput3[batch_i * input3_b_stride + ((filter_j - iy2_T ) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i], TL_grad * input1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i]); } } float TR_grad= gradoutput_value * alpha * ( 1- beta); for (int filter_j = iy2_T; filter_j <= (int) (y2); filter_j ++ ){ int _filter_j = min(max(0, filter_j),h - 1); // only used for input1 for (int filter_i = (int) (x2) + 1 ; filter_i < ix2_R; filter_i ++ ){ int _filter_i = min(max(0, filter_i),w - 1);// only used for input1 atomicAdd( &gradinput1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i ], TR_grad * input3[batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]); atomicAdd( & gradinput3[batch_i * input3_b_stride + ((filter_j - iy2_T ) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i], TR_grad * input1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i]); } } float BL_grad = gradoutput_value * ( 1 - alpha ) * beta; for (int filter_j = (int) (y2) + 1; filter_j < iy2_B; filter_j ++ ){ int _filter_j = min(max(0, filter_j),h - 1); // only used for input1 for (int filter_i = ix2_L; filter_i <= (int) (x2); filter_i ++ ){ int _filter_i = min(max(0, filter_i),w - 1);// only used for input1 atomicAdd( &gradinput1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i ], BL_grad * input3[batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]); atomicAdd( & gradinput3[batch_i * input3_b_stride + ((filter_j - iy2_T ) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i], BL_grad * input1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i]); } } float BR_grad = gradoutput_value * alpha * beta; for (int filter_j = (int) (y2) + 1; filter_j < iy2_B; filter_j ++ ){ int _filter_j = min(max(0, filter_j),h - 1); // only used for input1 for (int filter_i = (int) (x2) + 1; filter_i < ix2_R; filter_i ++ ){ int _filter_i = min(max(0, filter_i),w - 1);// only used for input1 atomicAdd( &gradinput1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i ], BR_grad * input3[batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]); atomicAdd( & gradinput3[batch_i * input3_b_stride + ((filter_j - iy2_T ) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i], BR_grad * input1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i]); } } // for ( int filter_j = iy2_T; filter_j < iy2_B ; filter_j ++ ){ // int _filter_j = min(max(0, filter_j), h - 1); // for( int filter_i = ix2_L; filter_i< ix2_R ; filter_i++){ // int _filter_i = min(max(0,filter_i), w - 1); // atomicAdd( & gradinput1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i], // gradoutput_value * // input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L))* input3_c_stride + h_i * input3_h_stride + w_i] * //// exp( -(fabs((float)filter_j - y2) + fabs((float)filter_i - x2))/(float)filter_size) // exp( -(fabs((float)filter_j - y2) + fabs((float)filter_i - x2))) // // ); // } // } } /*** Step 2: calculate the gradients for input2, i.e., the optical flow, STEP 2.1: for the x/horizonotal direction. ***/ float gamma = 1.0f - beta; //iy2_B - y2; float bot_diff = 0.0f; for(int c_i =0 ; c_i< channel; c_i ++ ){ float gradoutput_value = gradoutput[off + c_i * input1_c_stride + h_i * input1_h_stride + w_i]; float TL = 0.0f; for(int filter_j = iy2_T; filter_j <= (int)(y2); filter_j ++){ int _filter_j = min(max(0, filter_j), h - 1); for( int filter_i = ix2_L; filter_i <= (int) ( x2) ; filter_i ++ ){ int _filter_i = min(max(0, filter_i ), w - 1); TL += input1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i ] * input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i] ; } } float TR = 0.0f; for (int filter_j = iy2_T; filter_j <= (int) (y2); filter_j ++ ){ int _filter_j = min(max(0, filter_j),h - 1); // only used for input1 for (int filter_i = (int) (x2) + 1 ; filter_i < ix2_R; filter_i ++ ){ int _filter_i = min(max(0, filter_i),w - 1);// only used for input1 TR += input1 [off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i] * input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]; } } float BL = 0.0f; for (int filter_j = (int) (y2) + 1; filter_j < iy2_B; filter_j ++ ){ int _filter_j = min(max(0, filter_j),h - 1); // only used for input1 for (int filter_i = ix2_L; filter_i <= (int) (x2); filter_i ++ ){ int _filter_i = min(max(0, filter_i),w - 1);// only used for input1 BL += input1 [off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i] * input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]; } } float BR = 0.0f; for (int filter_j = (int) (y2) + 1; filter_j < iy2_B; filter_j ++ ){ int _filter_j = min(max(0, filter_j),h - 1); // only used for input1 for (int filter_i = (int) (x2) + 1; filter_i < ix2_R; filter_i ++ ){ int _filter_i = min(max(0, filter_i),w - 1);// only used for input1 BR += input1 [off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i] * input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]; } } float temp = 0.0f; temp += gamma * (TR - TL); temp += (1-gamma) * (BR - BL); bot_diff += gradoutput_value * temp; // for( int filter_j = iy2_T; filter_j< iy2_B; filter_j++){ // int _filter_j = min(max(0, filter_j) , h - 1); // for( int filter_i = ix2_L; filter_i< ix2_R; filter_i ++){ // int _filter_i = min(max(0,filter_i), w-1); // // bot_diff += // gradoutput_value * // input1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i] * // input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L))* input3_c_stride + h_i * input3_h_stride + w_i ] * //// exp( - ( fabs((float) filter_j - y2 ) + fabs((float) filter_i - x2))/ (float)filter_size) * //// ((float) filter_i > x2 ? 1.0f : -1.0f) / (float)filter_size; // exp( - ( fabs((float) filter_j - y2 ) + fabs((float) filter_i - x2))) * // ((float) filter_i > x2 ? 1.0f : -1.0f); // } // } } //the gradients of the x direction/ horizontal direction gradinput2[batch_i * input2_b_stride + 0 * input2_c_stride + h_i * input2_h_stride + w_i] = bot_diff; /*** STEP 2.2: for the x/horizonotal direction. ***/ gamma = 1.0f - alpha; //ix2_R -x2; bot_diff = 0.0f; for(int c_i = 0 ; c_i < channel; c_i ++ ){ float gradoutput_value = gradoutput [ off + c_i * input1_c_stride + h_i * input1_h_stride +w_i]; float TL = 0.0f; for(int filter_j = iy2_T; filter_j <= (int)(y2); filter_j ++){ int _filter_j = min(max(0, filter_j), h - 1); for( int filter_i = ix2_L; filter_i <= (int) ( x2) ; filter_i ++ ){ int _filter_i = min(max(0, filter_i ), w - 1); TL += input1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i ] * input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i] ; } } float TR = 0.0f; for (int filter_j = iy2_T; filter_j <= (int) (y2); filter_j ++ ){ int _filter_j = min(max(0, filter_j),h - 1); // only used for input1 for (int filter_i = (int) (x2) + 1 ; filter_i < ix2_R; filter_i ++ ){ int _filter_i = min(max(0, filter_i),w - 1);// only used for input1 TR += input1 [off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i] * input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]; } } float BL = 0.0f; for (int filter_j = (int) (y2) + 1; filter_j < iy2_B; filter_j ++ ){ int _filter_j = min(max(0, filter_j),h - 1); // only used for input1 for (int filter_i = ix2_L; filter_i <= (int) (x2); filter_i ++ ){ int _filter_i = min(max(0, filter_i),w - 1);// only used for input1 BL += input1 [off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i] * input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]; } } float BR = 0.0f; for (int filter_j = (int) (y2) + 1; filter_j < iy2_B; filter_j ++ ){ int _filter_j = min(max(0, filter_j),h - 1); // only used for input1 for (int filter_i = (int) (x2) + 1; filter_i < ix2_R; filter_i ++ ){ int _filter_i = min(max(0, filter_i),w - 1);// only used for input1 BR += input1 [off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i] * input3 [batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i]; } } float temp = 0.0f; temp += gamma * (BL - TL); temp += (1.0f - gamma) * ( BR - TR); bot_diff += gradoutput_value * temp; // for( int filter_j = iy2_T; filter_j < iy2_B; filter_j ++ ){ // int _filter_j = min(max(0, filter_j), h - 1); // for( int filter_i = ix2_L; filter_i < ix2_R; filter_i ++){ // int _filter_i = min(max(0, filter_i), w - 1); // // bot_diff += // gradoutput_value * // input1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i] * // input3 [batch_i * input3_b_stride +((filter_j - iy2_T) * filter_size + ( filter_i - ix2_L)) * input3_c_stride + h_i * input3_h_stride + w_i ] * //// exp( - (fabs((float) filter_j - y2) + fabs((float) filter_i - x2))/ (float)filter_size ) * //// ((float) filter_j > y2 ? 1.0f : - 1.0f ) / (float)filter_size; // exp( - (fabs((float) filter_j - y2) + fabs((float) filter_i - x2)) ) * // ((float) filter_j > y2 ? 1.0f : - 1.0f ); // } // } } gradinput2[batch_i * input2_b_stride + 1 * input2_c_stride + h_i * input2_h_stride + w_i]= bot_diff; /*** STEP 3: calculate the gradients for input3, i.e. the filter ***/ // for(int c_i = 0 ; c_i <channel ; c_i ++ ){ // float gradoutput_value = gradoutput[ off + c_i * input1_c_stride + h_i * input1_h_stride + w_i ]; // for( int filter_j= iy2_T ; filter_j < iy2_B; filter_j ++ ){ // int _filter_j = min(max(0, filter_j), h -1 ); // for ( int filter_i = ix2_L; filter_i < ix2_R; filter_i ++ ){ // int _filter_i = min(max(0, filter_i ), w - 1); // // gradinput3 [ batch_i * input3_b_stride + ((filter_j - iy2_T) * filter_size + (filter_i - ix2_L ) ) * input3_c_stride + h_i * input3_h_stride + w_i] += // gradoutput_value * // input1[off + c_i * input1_c_stride + _filter_j * input1_h_stride + _filter_i] * //// exp( -(fabs((float) filter_j - y2 ) + fabs((float) filter_i - x2))/ (float)filter_size); // exp( -(fabs((float) filter_j - y2 ) + fabs((float) filter_i - x2))); // } // } // } } } return ; } int FilterInterpolationLayer_gpu_forward_kernel( cudaStream_t stream, const int nElement, const int w, const int h, const int channel, const int batch, const int filter_size, const int input1_b_stride, const int input1_c_stride, const int input1_h_stride, const int input1_w_stride, const int input2_b_stride, const int input2_c_stride, const int input2_h_stride, const int input2_w_stride, const int input3_b_stride, const int input3_c_stride, const int input3_h_stride, const int input3_w_stride, at::Tensor& input1, at::Tensor& input2, at::Tensor& input3, at::Tensor& output ) { int error = 1 ; dim3 grid; dim3 block; // blockthread = 128; //the threadIdx.x is sheduled first, then threadIdx.y, threadIdx.z //the three channels are processsed in one kernel block = dim3(BLOCKDIMX,BLOCKDIMY,1); grid = dim3( (w + BLOCKDIMX - 1)/ BLOCKDIMX, (h + BLOCKDIMY - 1) / BLOCKDIMY, batch); if(BLOCKDIMX != 32 || BLOCKDIMY != 16||DEBUG) printf("BLOCKDIMX revised to %d, BLOCKDIMY revised to %d \n", BLOCKDIMX,BLOCKDIMY); //extract the data of CudaTensor and use kernel to calculate. AT_DISPATCH_FLOATING_TYPES(input1.type(), "DepthFlowProjection_gpu_backward", ([&] { FilterInterpolationLayer_gpu_forward_kernelfunc<<<grid,block,0, stream >>>( nElement, //to let the nummous w,h,channel,filter_size, input1_b_stride,input1_c_stride,input1_h_stride,input1_w_stride, input2_b_stride,input2_c_stride,input2_h_stride,input2_w_stride, input3_b_stride,input3_c_stride,input3_h_stride,input3_w_stride, input1.data<scalar_t>(),input2.data<scalar_t>(),input3.data<scalar_t>(), output.data<scalar_t>() ); })); // THCudaCheck(cudaGetLastError()); cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) { printf("gpuerror in BilinearSampler.updateOutput: %s\n", cudaGetErrorString(err)); //THError("aborting"); return error; } error = 0; return error; } int FilterInterpolationLayer_gpu_backward_kernel( cudaStream_t stream, const int nElement, const int w, const int h, const int channel, const int batch, const int filter_size, const int input1_b_stride, const int input1_c_stride, const int input1_h_stride, const int input1_w_stride, const int input2_b_stride, const int input2_c_stride, const int input2_h_stride, const int input2_w_stride, const int input3_b_stride, const int input3_c_stride, const int input3_h_stride, const int input3_w_stride, at::Tensor& input1, at::Tensor& input2, at::Tensor& input3, at::Tensor& gradoutput, at::Tensor& gradinput1, at::Tensor& gradinput2, at::Tensor& gradinput3 ) { int error = 1 ; dim3 grid; dim3 block; //blockthread = 128; //the threadIdx.x is sheduled first, then threadIdx.y, threadIdx.z //the three channels are processsed in one kernel block = dim3(BLOCKDIMX,BLOCKDIMY,1); grid = dim3( (w + BLOCKDIMX - 1)/ BLOCKDIMX, (h + BLOCKDIMY - 1) / BLOCKDIMY, batch); if(BLOCKDIMX != 32 || BLOCKDIMY != 16||DEBUG) printf("BLOCKDIMX revised to %d, BLOCKDIMY revised to %d \n", BLOCKDIMX,BLOCKDIMY); // cudaMemset((void*)gradinput1, 0, input1_b_stride * batch * sizeof(float)); // cudaMemset((void*)gradinput2, 0, input2_b_stride * batch * sizeof(float)); // cudaMemset((void*)gradinput3, 0, input3_b_stride * batch * sizeof(float)); AT_DISPATCH_FLOATING_TYPES(input1.type(), "DepthFlowProjection_gpu_backward", ([&] { FilterInterpolationLayer_gpu_backward_kernelfunc <<<grid,block,0, stream>>>( nElement, //to let the nummous w,h,channel,filter_size, input1_b_stride,input1_c_stride,input1_h_stride,input1_w_stride, input2_b_stride,input2_c_stride,input2_h_stride,input2_w_stride, input3_b_stride,input3_c_stride,input3_h_stride,input3_w_stride, input1.data<scalar_t>(), input2.data<scalar_t>(), input3.data<scalar_t>(), gradoutput.data<scalar_t>(), gradinput1.data<scalar_t>(), gradinput2.data<scalar_t>(), gradinput3.data<scalar_t>() ); })); cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) { printf("gpuerror in BilinearSampler.updateGradInput %s\n", cudaGetErrorString(err)); //THError("aborting"); return error; } error = 0; return error; }
the_stack
using namespace std; typedef uint8_t uint8; typedef unsigned int uint32; typedef unsigned long long int uint64; #define STREAM_BLOCK 16 #define BLOCK_SIZE 32 #define BLOCK_D_SIZE 64 #define INTEGRAL_BLOCK_SIZE 8 #define XDIM_MAX_THREADS 1024 #define XDIM_H_THREADS 512 #define XDIM_Q_THREADS 256 #define SHARED_MEMORY 49152 #define INIT_BLOCK 8 __global__ void SADKernel(const float* left, const float* right, float* integral_vol, const int rows, const int cols, const int integrrows , const int integrcols , const int ndisp ){ extern __shared__ float row_slice[]; int Col = threadIdx.x; int uCol = XDIM_MAX_THREADS+threadIdx.x; int Row = blockIdx.x; if(Col <cols && Row<rows ){ row_slice[Col] = left[Row*cols+Col]; row_slice[cols+Col] = right[Row*cols+Col]; } if(uCol<cols && Row<rows){ row_slice[uCol] = left[Row*cols+uCol]; row_slice[cols+uCol] = right[Row*cols+uCol]; } __syncthreads(); for(int d=0; d<ndisp; d++){ if(Row < rows && Col < cols && Col-d >=0 ){ integral_vol[d*integrrows*integrcols+Row*integrcols + Col] = abs(row_slice[Col] - row_slice[cols+Col-d] ); } if(Row<rows && uCol<cols){ integral_vol[d*integrrows*integrcols+Row*integrcols + uCol] = abs(row_slice[uCol] - row_slice[cols+uCol-d] ); } } } __global__ void SAD(const float* integral_vol, float* slice, const int integrrows , const int integrcols , const int rows , const int cols, const int wsize, const int wc){ int Row = blockIdx.y * BLOCK_SIZE + threadIdx.y; int Col = blockIdx.x * BLOCK_SIZE + threadIdx.x; const int d = blockIdx.z; float cost = 6375; if(Row < rows-wsize && Col < cols-wsize && Col >=d){ cost = integral_vol[d*integrrows*integrcols+(Row+wsize)*integrcols + (Col+wsize)] - integral_vol[d*integrrows*integrcols+(Row)*integrcols + (Col+wsize)] - integral_vol[d*integrrows*integrcols+(Row+wsize)*integrcols + Col] + integral_vol[d*integrrows*integrcols+(Row)*integrcols + Col]; } if(Row < rows && Col<cols) slice[d*rows*cols+(Row+wc)*cols+(Col+wc)] = cost; } void usage(void){ std::cout << "SAD genmeric CUDA implementation" << std::endl; std::cout << "Arguments" << std::endl; std::cout << "-l:\t\t Left image | File containing names of the left images" << std::endl; std::cout << "-r:\t\t Right image | File containing the names of the right images" << std::endl; std::cout << "-ndisp:\t\t Number of Disparities" << std::endl; std::cout << "-wsize:\t\t Window size" << std::endl; std::cout << "-dopost:\t Default false. If set, activates sgm cost optimization" << std::endl; std::cout << "-list:\t\t Default is single file. If set, left and right files should be lists of images." << std::endl; std::cout << "-out:\t\t Output directory for disparity images." << std::endl; std::cout << "-out_type:\t Output image type. Supports pgm|pfm|png|disp(uint16 png format)." << std::endl; std::cout << "-postconf:\t Optional configuration file for post-processing." << std::endl; std::cout << "-h:\t\t Prints this help" << std::endl; } int main(int argc, char* argv[]){ string leftfile; string rightfile; string out=string("."); string out_t=string("disp"); int wsize=9; int ndisp=256; bool post=false; bool single=true; int argsassigned = 0; int required=0; postparams params; //sgm params params.pi1=750; params.pi2=6000; params.tau_so=1; params.alpha1=2; params.sgm_q1=3; params.sgm_q2=2; params.alpha2=6; params.sigma = 5.99; params.kernel_size=5; int direction =-1; for(int i=0; i<argc; i++){ if( !strcmp(argv[i], "-l") ){ leftfile = string(argv[++i]); argsassigned++; required++; }else if( !strcmp(argv[i],"-r") ){ rightfile = string(argv[++i]); argsassigned++; required++; }else if( !strcmp(argv[i],"-ndisp") ){ ndisp= atoi(argv[++i]); argsassigned++; required++; }else if( !strcmp(argv[i],"-wsize") ){ wsize= atoi(argv[++i]); argsassigned++; required++; }else if( !strcmp(argv[i], "-dopost") ){ post= true; argsassigned++; }else if(!strcmp(argv[i],"-list")){ single=false; argsassigned++; }else if(!strcmp(argv[i],"-out")){ out=string(argv[++i]); argsassigned++; }else if(!strcmp(argv[i],"-out_type")){ out_t=string(argv[++i]); argsassigned++; }else if(!strcmp(argv[i],"-postconf")){ parseConf(params ,string(argv[++i])); argsassigned++; }else if(!strcmp(argv[i],"-h")){ usage(); return 0; } } if(argsassigned == 0){ usage(); return 0; } if(argsassigned ==1){ leftfile = string("../../leftimg.txt"); rightfile = string("../../rightimg.txt"); } else if( required < 4 ){ usage(); return 0; } std::vector<string> limg; std::vector<string> rimg; if (single){ limg.push_back(leftfile); rimg.push_back(rightfile); }else{ limg = getImages(leftfile); rimg = getImages(rightfile); } imgio* imgutil = new imgio(); imgutil->read_image_meta(limg[0].c_str()); //######################### Allocate memory on the device ###########################################// float* imgl; size_t ibytes = imgutil->getWidth()*imgutil->getHeight()*sizeof(float); cudaMallocHost( (void**) &imgl, ibytes ); float* imgr; cudaMallocHost( (void**) &imgr, ibytes ); int width = imgutil->getWidth(); int height = imgutil->getHeight(); int wdiv = ceil((float)width/32); cudaStream_t stream1; cudaStream_t stream2; cudaStreamCreate(&stream1); cudaStreamCreate(&stream2); const int wc = wsize/2; float* cost_d; size_t bytes = height*width*ndisp*sizeof(float); cudaMalloc( (void**) &cost_d, bytes ); float* post_cost_d; cudaMalloc( (void**) &post_cost_d, bytes ); float* disp_h; size_t dbytes = imgutil->getWidth()*imgutil->getHeight()*sizeof(float); cudaMallocHost( (void**) &disp_h, dbytes ); float * disp_d; cudaMalloc(&disp_d, dbytes); float * disp_tmp; cudaMalloc(&disp_tmp, dbytes); float* imgl_d; cudaMalloc(&imgl_d, imgutil->getWidth()*imgutil->getHeight()*sizeof(float)); float* imgr_d; cudaMalloc(&imgr_d, imgutil->getWidth()*imgutil->getHeight()*sizeof(float)); int size1 = height*ndisp; int size2 = width*ndisp; dim3 argGridSGM1((size1 - 1) / ndisp + 1,width); dim3 argGridSGM2((size2 - 1) / ndisp + 1,height); float * tmp_d; cudaMalloc(&tmp_d, width*ndisp*sizeof(float)); cudaMemsetAsync(tmp_d,0 , width*ndisp*sizeof(float),0); int kr = ceil(params.sigma*3); int ks = kr*2+1; float * kernel = (float*)calloc(ks*ks,sizeof(float)); for (int i=0; i<ks; i++){ for(int j=0; j<ks; j++){ int y= (i-1)-kr; int x= (j-1)-kr; kernel[i*ks+j] = exp( -(x*x+y*y)/(2*params.sigma*params.sigma) ); } } float *kernel_d; cudaMalloc(&kernel_d, ks*ks*sizeof(float)); cudaMemcpy( kernel_d, kernel, ks*ks*sizeof(float), cudaMemcpyHostToDevice); int vthreads = XDIM_MAX_THREADS; if(height < XDIM_Q_THREADS) vthreads=XDIM_Q_THREADS; else if(height < XDIM_Q_THREADS) vthreads=XDIM_H_THREADS; dim3 vintegralBlock(vthreads); dim3 integralBlock(XDIM_MAX_THREADS); dim3 integraldim1Griddisp(1,height,ndisp ); dim3 vintegralGriddisp(1,width,ndisp ); dim3 dimBlock(BLOCK_SIZE,BLOCK_SIZE); dim3 dimCostSlice( ceil((float) width/ BLOCK_SIZE),ceil( (float)height/ BLOCK_SIZE),ndisp ); dim3 swapBlock(BLOCK_D_SIZE,16,1); dim3 swapGrid(ceil((float)imgutil->getWidth()*imgutil->getHeight()/BLOCK_D_SIZE),ceil((float) ndisp/BLOCK_D_SIZE )); dim3 argBlock(BLOCK_SIZE, BLOCK_SIZE); dim3 argGrid(ceil((float) imgutil->getWidth() / BLOCK_SIZE),ceil( (float)imgutil->getHeight()/ BLOCK_SIZE)); dim3 SADBlock(XDIM_MAX_THREADS); dim3 SADGrid(imgutil->getHeight()); int hreps = ceil((float) width/XDIM_MAX_THREADS ); int vreps = ceil((float) height/vthreads ); //###########################################################################################################################################// for(size_t i=0; i<limg.size(); i++){ imgutil->read_image(limg[i],imgl); imgutil->read_image(rimg[i],imgr); cudaMemcpyAsync( imgl_d, imgl, width*height*sizeof(float), cudaMemcpyHostToDevice,stream1); cudaMemcpyAsync( imgr_d, imgr, width*height*sizeof(float), cudaMemcpyHostToDevice,stream2); cudaMemsetAsync(cost_d,0 , height*width*ndisp*sizeof(float),stream1); cudaMemsetAsync(post_cost_d,0 , width*height*ndisp*sizeof(float),stream2); SADKernel<<<SADGrid, SADBlock,2*width*sizeof(float)>>>(imgl_d,imgr_d,post_cost_d,height , width,height , width,ndisp); for(int r=0; r<hreps; r++){ IntegralKernel<<<integraldim1Griddisp, integralBlock, 32*sizeof(float) >>>(post_cost_d, height, width,ndisp,r*(XDIM_MAX_THREADS-1) ); } for(int r=0; r<vreps; r++){ VerticalIntegralKernel<<<vintegralGriddisp, vintegralBlock,32*sizeof(float) >>>(post_cost_d,height,width,1,r*(vthreads-1)); } SAD<<<dimCostSlice, dimBlock,0>>>(post_cost_d,cost_d,height,width,height,width ,wsize,wc); if(post){ swap_axis<<< swapGrid, swapBlock >>>( cost_d, post_cost_d,height,width,ndisp ); cudaMemset(cost_d,0 , height*width*ndisp*sizeof(float)); for (int step = 0; step < width; step++) { sgm_loop<0><<<(size1 - 1) / ndisp + 1, ndisp,2*ndisp*sizeof(float)>>>( imgl_d, imgr_d, post_cost_d, cost_d, tmp_d, params.pi1, params.pi2, params.tau_so, params.alpha1, params.sgm_q1, params.sgm_q2, direction, height, width, ndisp, step); } for (int step = 0; step < width; step++) { sgm_loop<1><<<(size1 - 1) / ndisp + 1, ndisp,2*ndisp*sizeof(float)>>>( imgl_d, imgr_d, post_cost_d, cost_d, tmp_d, params.pi1, params.pi2, params.tau_so, params.alpha1, params.sgm_q1, params.sgm_q2, direction, height, width, ndisp, step); } for (int step = 0; step < height; step++) { sgm_loop<2><<<(size2 - 1) / ndisp + 1, ndisp,2*ndisp*sizeof(float)>>>( imgl_d, imgr_d, post_cost_d, cost_d, tmp_d, params.pi1, params.pi2, params.tau_so, params.alpha1, params.sgm_q1, params.sgm_q2, direction, height, width, ndisp, step); } for (int step = 0; step < height; step++) { sgm_loop<3><<<(size2 - 1) / ndisp + 1, ndisp,2*ndisp*sizeof(float)>>>( imgl_d, imgr_d, post_cost_d, cost_d, tmp_d, params.pi1, params.pi2, params.tau_so, params.alpha1, params.sgm_q1, params.sgm_q2, direction, height, width, ndisp, step); } argmin<<<argGrid, argBlock>>>( disp_d, cost_d, height, width,ndisp ); subpixel_enchancement<<<(height*width - 1) / TB + 1, TB>>>( disp_d, cost_d, disp_tmp, height*width, height*width, ndisp); median2d<<<(height*width - 1) / TB + 1, TB>>>( disp_tmp, disp_d, height*width, height, width, params.kernel_size / 2); mean2d<<<(height*width - 1) / TB + 1, TB>>>( disp_d, kernel_d, disp_tmp, height*width, ks / 2, height, width, params.alpha2); }else{ argmin_d<<<argGrid, argBlock>>>( disp_tmp, cost_d, height, width,ndisp ); } cudaMemcpy( disp_h, disp_tmp, height*width*sizeof(float), cudaMemcpyDeviceToHost ); cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) printf("Error: %s\n", cudaGetErrorString(err)); imgutil->write_image(out + string("/") +limg[i].substr(limg[i].find_last_of("/")+1) ,disp_h,out_t); } cudaFreeHost(imgl); cudaFreeHost(imgr); cudaStreamDestroy(stream1); cudaStreamDestroy(stream2); cudaFree(tmp_d); cudaFreeHost(imgl); cudaFreeHost(imgr); cudaFreeHost(disp_h); cudaFree(disp_d); cudaFree(disp_tmp); cudaFree(imgl_d); cudaFree(imgr_d); cudaFree(cost_d); cudaFree(post_cost_d); delete imgutil; }
the_stack
// The dimensions of the thread block #define BLOCKDIM_X 16 #define BLOCKDIM_Y 16 #define ABS(n) ((n) < 0 ? -(n) : (n)) // Double single functions based on DSFUN90 package: // http://crd.lbl.gov/~dhbailey/mpdist/index.html // This function sets the DS number A equal to the double precision floating // point number B. inline void dsdeq(float &a0, float &a1, double b) { a0 = (float)b; a1 = (float)(b - a0); } // dsdcp // This function sets the DS number A equal to the single precision floating // point number B. __device__ inline void dsfeq(float &a0, float &a1, float b) { a0 = b; a1 = 0.0f; } // dsfeq // This function computes c = a + b. __device__ inline void dsadd(float &c0, float &c1, const float a0, const float a1, const float b0, const float b1) { // Compute dsa + dsb using Knuth's trick. float t1 = a0 + b0; float e = t1 - a0; float t2 = ((b0 - e) + (a0 - (t1 - e))) + a1 + b1; // The result is t1 + t2, after normalization. c0 = e = t1 + t2; c1 = t2 - (e - t1); } // dsadd // This function computes c = a - b. __device__ inline void dssub(float &c0, float &c1, const float a0, const float a1, const float b0, const float b1) { // Compute dsa - dsb using Knuth's trick. float t1 = a0 - b0; float e = t1 - a0; float t2 = ((-b0 - e) + (a0 - (t1 - e))) + a1 - b1; // The result is t1 + t2, after normalization. c0 = e = t1 + t2; c1 = t2 - (e - t1); } // dssub #if 1 // This function multiplies DS numbers A and B to yield the DS product C. __device__ inline void dsmul(float &c0, float &c1, const float a0, const float a1, const float b0, const float b1) { // This splits dsa(1) and dsb(1) into high-order and low-order words. float cona = a0 * 8193.0f; float conb = b0 * 8193.0f; float sa1 = cona - (cona - a0); float sb1 = conb - (conb - b0); float sa2 = a0 - sa1; float sb2 = b0 - sb1; // Multilply a0 * b0 using Dekker's method. float c11 = a0 * b0; float c21 = (((sa1 * sb1 - c11) + sa1 * sb2) + sa2 * sb1) + sa2 * sb2; // Compute a0 * b1 + a1 * b0 (only high-order word is needed). float c2 = a0 * b1 + a1 * b0; // Compute (c11, c21) + c2 using Knuth's trick, also adding low-order product. float t1 = c11 + c2; float e = t1 - c11; float t2 = ((c2 - e) + (c11 - (t1 - e))) + c21 + a1 * b1; // The result is t1 + t2, after normalization. c0 = e = t1 + t2; c1 = t2 - (e - t1); } // dsmul #else // Modified double-single mul function by Norbert Juffa, NVIDIA // uses __fmul_rn() and __fadd_rn() intrinsics which prevent FMAD merging /* Based on: Guillaume Da Gra�a, David Defour. Implementation of Float-Float * Operators on Graphics Hardware. RNC'7 pp. 23-32, 2006. */ // This function multiplies DS numbers A and B to yield the DS product C. __device__ inline void dsmul(float &c0, float &c1, const float a0, const float a1, const float b0, const float b1) { // This splits dsa(1) and dsb(1) into high-order and low-order words. float cona = a0 * 8193.0f; float conb = b0 * 8193.0f; float sa1 = cona - (cona - a0); float sb1 = conb - (conb - b0); float sa2 = a0 - sa1; float sb2 = b0 - sb1; // Multilply a0 * b0 using Dekker's method. float c11 = __fmul_rn(a0, b0); float c21 = (((sa1 * sb1 - c11) + sa1 * sb2) + sa2 * sb1) + sa2 * sb2; // Compute a0 * b1 + a1 * b0 (only high-order word is needed). float c2 = __fmul_rn(a0, b1) + __fmul_rn(a1, b0); // Compute (c11, c21) + c2 using Knuth's trick, also adding low-order product. float t1 = c11 + c2; float e = t1 - c11; float t2 = ((c2 - e) + (c11 - (t1 - e))) + c21 + __fmul_rn(a1, b1); // The result is t1 + t2, after normalization. c0 = e = t1 + t2; c1 = t2 - (e - t1); } // dsmul #endif // The core Mandelbrot CUDA GPU calculation function #if 1 // Unrolled version template <class T> __device__ inline int CalcMandelbrot(const T xPos, const T yPos, const T xJParam, const T yJParam, const int crunch, const bool isJulia) { T x, y, xx, yy; int i = crunch; T xC, yC; if (isJulia) { xC = xJParam; yC = yJParam; y = yPos; x = xPos; yy = y * y; xx = x * x; } else { xC = xPos; yC = yPos; y = 0; x = 0; yy = 0; xx = 0; } do { // Iteration 1 if (xx + yy > T(4.0)) return i - 1; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 2 if (xx + yy > T(4.0)) return i - 2; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 3 if (xx + yy > T(4.0)) return i - 3; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 4 if (xx + yy > T(4.0)) return i - 4; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 5 if (xx + yy > T(4.0)) return i - 5; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 6 if (xx + yy > T(4.0)) return i - 6; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 7 if (xx + yy > T(4.0)) return i - 7; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 8 if (xx + yy > T(4.0)) return i - 8; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 9 if (xx + yy > T(4.0)) return i - 9; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 10 if (xx + yy > T(4.0)) return i - 10; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 11 if (xx + yy > T(4.0)) return i - 11; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 12 if (xx + yy > T(4.0)) return i - 12; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 13 if (xx + yy > T(4.0)) return i - 13; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 14 if (xx + yy > T(4.0)) return i - 14; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 15 if (xx + yy > T(4.0)) return i - 15; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 16 if (xx + yy > T(4.0)) return i - 16; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 17 if (xx + yy > T(4.0)) return i - 17; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 18 if (xx + yy > T(4.0)) return i - 18; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 19 if (xx + yy > T(4.0)) return i - 19; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; // Iteration 20 i -= 20; if ((i <= 0) || (xx + yy > T(4.0))) return i; y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; } while (1); } // CalcMandelbrot #else template <class T> __device__ inline int CalcMandelbrot(const T xPos, const T yPos, const T xJParam, const T yJParam, const int crunch, const isJulia) { T x, y, xx, yy, xC, yC; if (isJulia) { xC = xJParam; yC = yJParam; y = yPos; x = xPos; yy = y * y; xx = x * x; } else { xC = xPos; yC = yPos; y = 0; x = 0; yy = 0; xx = 0; } int i = crunch; while (--i && (xx + yy < T(4.0))) { y = x * y * T(2.0) + yC; x = xx - yy + xC; yy = y * y; xx = x * x; } return i; // i > 0 ? crunch - i : 0; } // CalcMandelbrot #endif // The core Mandelbrot calculation function in double-single precision __device__ inline int CalcMandelbrotDS(const float xPos0, const float xPos1, const float yPos0, const float yPos1, const float xJParam, const float yJParam, const int crunch, const bool isJulia) { float xx0, xx1; float yy0, yy1; float sum0, sum1; int i = crunch; float x0, x1, y0, y1; float xC0, xC1, yC0, yC1; if (isJulia) { xC0 = xJParam; xC1 = 0; yC0 = yJParam; yC1 = 0; y0 = yPos0; // y = yPos; y1 = yPos1; x0 = xPos0; // x = xPos; x1 = xPos1; dsmul(yy0, yy1, y0, y1, y0, y1); // yy = y * y; dsmul(xx0, xx1, x0, x1, x0, x1); // xx = x * x; } else { xC0 = xPos0; xC1 = xPos1; yC0 = yPos0; yC1 = yPos1; y0 = 0; // y = 0 ; y1 = 0; x0 = 0; // x = 0 ; x1 = 0; yy0 = 0; // yy = 0 ; yy1 = 0; xx0 = 0; // xx = 0 ; xx1 = 0; } dsadd(sum0, sum1, xx0, xx1, yy0, yy1); // sum = xx + yy; while (--i && (sum0 + sum1 < 4.0f)) { dsmul(y0, y1, x0, x1, y0, y1); // y = x * y * 2.0f + yC; // yC is yPos for // Mandelbrot and it is yJParam for Julia dsadd(y0, y1, y0, y1, y0, y1); dsadd(y0, y1, y0, y1, yC0, yC1); dssub(x0, x1, xx0, xx1, yy0, yy1); // x = xx - yy + xC; // xC is xPos for // Mandelbrot and it is xJParam for // Julia dsadd(x0, x1, x0, x1, xC0, xC1); dsmul(yy0, yy1, y0, y1, y0, y1); // yy = y * y; dsmul(xx0, xx1, x0, x1, x0, x1); // xx = x * x; dsadd(sum0, sum1, xx0, xx1, yy0, yy1); // sum = xx + yy; } return i; } // CalcMandelbrotDS // Determine if two pixel colors are within tolerance __device__ inline int CheckColors(const uchar4 &color0, const uchar4 &color1) { int x = color1.x - color0.x; int y = color1.y - color0.y; int z = color1.z - color0.z; return (ABS(x) > 10) || (ABS(y) > 10) || (ABS(z) > 10); } // CheckColors // Increase the grid size by 1 if the image width or height does not divide // evenly // by the thread block dimensions inline int iDivUp(int a, int b) { return ((a % b) != 0) ? (a / b + 1) : (a / b); } // iDivUp
the_stack
#include <array/NDArrayFactory.h> #include <array/ResultSet.h> #include <exceptions/cuda_exception.h> #include <helpers/ConstantTadHelper.h> #include <helpers/PointersManager.h> #include <helpers/ShapeUtils.h> #include <helpers/TAD.h> #include <ops/declarable/helpers/transforms.h> #include <numeric> namespace sd { namespace ops { namespace helpers { /////////////////////////////////////////////////////////////////// // x - input, y - paddings, z - output template <typename X, typename Y> SD_KERNEL static void padCuda(const int mode, const void* vx, const sd::LongType* xShapeInfo, const void* vy, const sd::LongType* yShapeInfo, void* vz, const sd::LongType* zShapeInfo, const void* vPadVal) { const X padVal = *reinterpret_cast<const X*>(vPadVal); const auto x = reinterpret_cast<const X*>(vx); const auto y = reinterpret_cast<const Y*>(vy); auto z = reinterpret_cast<X*>(vz); __shared__ int rank, rankMinusOne; __shared__ sd::LongType zLen, totalThreads, *coords, *xShape, *zShape, shift1, shift2, yStride0; if (threadIdx.x == 0) { extern __shared__ unsigned char shmem[]; coords = reinterpret_cast<sd::LongType*>(shmem); zLen = shape::length(zShapeInfo); xShape = shape::shapeOf(const_cast<sd::LongType*>(xShapeInfo)); zShape = shape::shapeOf(const_cast<sd::LongType*>(zShapeInfo)); yStride0 = shape::stride(const_cast<sd::LongType*>(yShapeInfo))[0]; rank = shape::rank(xShapeInfo); zLen = shape::length(zShapeInfo); rankMinusOne = rank - 1; totalThreads = gridDim.x * blockDim.x; shift1 = mode == 1 ? 0 : 1; // REFLECT : SYMMETRIC shift2 = mode == 1 ? 2 : 1; // REFLECT : SYMMETRIC } __syncthreads(); auto xzCoord = coords + threadIdx.x * rank; // we use xzCoord storage both for x and z arrays const auto tid = blockIdx.x * blockDim.x + threadIdx.x; if (mode == 0) { // CONSTANT case for (sd::LongType i = tid; i < zLen; i += totalThreads) { shape::index2coords(i, zShapeInfo, xzCoord); const auto zOffset = shape::getOffset(zShapeInfo, xzCoord); bool within = true; for (int j = rankMinusOne; j >= 0; --j) { if (xShape[j] == zShape[j]) continue; const auto left = y[shape::getIndexOffset(yStride0 * j, yShapeInfo)]; if (xzCoord[j] < left || xzCoord[j] >= left + xShape[j]) { within = false; break; } else { xzCoord[j] = xzCoord[j] - left; } } if (within) z[zOffset] = x[shape::getOffset(xShapeInfo, xzCoord)]; else z[zOffset] = padVal; } } else { // REFLECT and SYMMETRIC cases for (sd::LongType i = tid; i < zLen; i += totalThreads) { shape::index2coords(i, zShapeInfo, xzCoord); const auto zOffset = shape::getOffset(zShapeInfo, xzCoord); for (int j = rankMinusOne; j >= 0; --j) { if (xShape[j] == zShape[j]) continue; xzCoord[j] = xzCoord[j] - y[shape::getIndexOffset( yStride0 * j, yShapeInfo)]; // are ready to fill middle (within input dimension range) if (xzCoord[j] < 0) xzCoord[j] = -xzCoord[j] - shift1; // means fill from left else if (xzCoord[j] >= xShape[j]) xzCoord[j] = 2 * xShape[j] - xzCoord[j] - shift2; // means fill from right } const auto xOffset = shape::getOffset(xShapeInfo, xzCoord); z[zOffset] = x[xOffset]; } } } /////////////////////////////////////////////////////////////////// template <typename X, typename Y> static void padCudaLauncher(const int blocksPerGrid, const int threadsPerBlock, const int sharedMem, const cudaStream_t* stream, const int mode, const void* vx, const sd::LongType* xShapeInfo, const void* vy, const sd::LongType* yShapeInfo, void* vz, const sd::LongType* zShapeInfo, const void* padVal) { padCuda<X, Y><<<blocksPerGrid, threadsPerBlock, sharedMem, *stream>>>(mode, vx, xShapeInfo, vy, yShapeInfo, vz, zShapeInfo, padVal); } /////////////////////////////////////////////////////////////////// void pad(sd::LaunchContext* context, const int mode, const NDArray& input, const NDArray& paddings, NDArray& output, const NDArray& padValue) { PointersManager manager(context, "pad"); NDArray::prepareSpecialUse({&output}, {&input, &paddings, &padValue}); const int threadsPerBlock = SD_MAX_NUM_THREADS / 4; const int blocksPerGrid = (output.lengthOf() + threadsPerBlock - 1) / threadsPerBlock; const int sharedMem = 8 * threadsPerBlock * output.rankOf() + 128; const auto xType = input.dataType(); const auto yType = paddings.dataType(); BUILD_DOUBLE_SELECTOR( xType, yType, padCudaLauncher, (blocksPerGrid, threadsPerBlock, sharedMem, context->getCudaStream(), mode, input.specialBuffer(), input.specialShapeInfo(), paddings.specialBuffer(), paddings.specialShapeInfo(), output.specialBuffer(), output.specialShapeInfo(), padValue.specialBuffer()), SD_COMMON_TYPES, SD_INDEXING_TYPES); NDArray::registerSpecialUse({&output}, {&input, &paddings, &padValue}); manager.synchronize(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename T> static SD_KERNEL void mirrorPadLinearKernel(void const* vx, const sd::LongType* xShape, void* vz, const sd::LongType* zShape, sd::LongType leftSide, sd::LongType leftSideCorrected, sd::LongType xLen, sd::LongType len, sd::LongType zLen) { __shared__ T const* x; __shared__ T* z; if (threadIdx.x == 0) { x = reinterpret_cast<T const*>(vx); z = reinterpret_cast<T*>(vz); } __syncthreads(); auto start = blockIdx.x * blockDim.x + threadIdx.x; auto step = blockDim.x * gridDim.x; for (int i = start; i < zLen; i += step) { auto zIndex = shape::getIndexOffset(i, zShape); auto xIndex = shape::getIndexOffset(len - i, xShape); if (i < leftSide) // left side xIndex = shape::getIndexOffset(leftSideCorrected - i, xShape); else if (i >= leftSide && i < leftSide + xLen) // middle xIndex = shape::getIndexOffset(i - leftSide, xShape); // else // right side // z[i] = x[len - i]; z[zIndex] = x[xIndex]; } } template <typename F, typename I> static SD_KERNEL void mirrorPadKernel(void const* vx, const sd::LongType* xShape, void* vz, const sd::LongType* zShape, sd::LongType outLen, void const* paddings, const sd::LongType* paddingShape, int reflBorder) { __shared__ F const* x; __shared__ I const* pads; __shared__ F* z; __shared__ sd::LongType zRank, rank; __shared__ sd::LongType* xIdx; if (threadIdx.x == 0) { extern __shared__ unsigned char shmem[]; xIdx = reinterpret_cast<sd::LongType*>(shmem); rank = shape::rank(xShape); x = reinterpret_cast<F const*>(vx); // pads = reinterpret_cast<I const*>(paddings); z = reinterpret_cast<F*>(vz); } __syncthreads(); auto start = threadIdx.x + blockIdx.x * blockDim.x; auto step = blockDim.x * gridDim.x; for (sd::LongType i = start; i < outLen; i += step) { auto xzCoord = xIdx + threadIdx.x * rank; // auto zxCoord = xIdx + (threadIdx.x + threadIdx.x % 2 + 1) * rank; shape::index2coords(i, zShape, xzCoord); auto outOffset = shape::getOffset(zShape, xzCoord); // auto intStep = blockDim.y * gridDim.y; for (int j = 0; j < rank; j++) { const sd::LongType inLen = shape::sizeAt(xShape, j); sd::LongType coords[2] = {j, 0}; auto padOffset = shape::getOffset(paddingShape, coords); // padding already has rank 2 const auto leftSide = pads[padOffset]; const auto leftSideCorrected = leftSide - reflBorder; const sd::LongType len = 2 * (inLen - 1) + leftSide + reflBorder; if (xzCoord[j] < leftSide) // left side xzCoord[j] = leftSideCorrected - xzCoord[j]; else if (xzCoord[j] >= leftSide && xzCoord[j] < leftSide + inLen) // middle xzCoord[j] = xzCoord[j] - leftSide; else if (len > xzCoord[j]) // right side xzCoord[j] = len - xzCoord[j]; else xzCoord[j] = xzCoord[j] - len; } auto inOffset = shape::getOffset(xShape, xzCoord); z[outOffset] = x[inOffset]; } } template <typename F, typename I> static void mirrorPad_(sd::LaunchContext* context, const NDArray& input, const NDArray& paddings, NDArray& output, const int mode) { // mode: 0 - REFLECT, else - SYMMETRIC const int reflBorder = (bool)mode ? 1 : 0; const int rank = input.rankOf(); const sd::LongType outLen = output.lengthOf(); auto stream = context->getCudaStream(); NDArray::prepareSpecialUse({&output}, {&input, &paddings}); if (rank <= 1) { const sd::LongType inLen = input.lengthOf(); const auto leftSide = paddings.e<sd::LongType>(0); const auto leftSideCorrected = leftSide - reflBorder; const sd::LongType len = 2 * (inLen - 1) + leftSide + reflBorder; mirrorPadLinearKernel<F><<<256, 512, 256, *stream>>>(input.specialBuffer(), input.specialShapeInfo(), output.specialBuffer(), output.specialShapeInfo(), leftSide, leftSideCorrected, inLen, len, outLen); sd::DebugHelper::checkErrorCode(stream, "helpers::mirrorPadLinearKernel(...) failed"); } else { const int threadsPerBlock = SD_MAX_NUM_THREADS / 2; const int blocksPerGrid = (outLen + threadsPerBlock - 1) / threadsPerBlock; const int sharedMem = threadsPerBlock * sizeof(sd::LongType) * input.rankOf() + 256; mirrorPadKernel<F, I><<<blocksPerGrid, threadsPerBlock, sharedMem, *stream>>>( input.specialBuffer(), input.specialShapeInfo(), output.specialBuffer(), output.specialShapeInfo(), outLen, paddings.specialBuffer(), paddings.specialShapeInfo(), reflBorder); sd::DebugHelper::checkErrorCode(stream, "helpers::mirrorPadKernel(...) failed"); } NDArray::registerSpecialUse({&output}, {&input, &paddings}); } void mirrorPad(sd::LaunchContext* context, const NDArray& input, const NDArray& paddings, NDArray& output, const int mode) { BUILD_DOUBLE_SELECTOR(input.dataType(), paddings.dataType(), mirrorPad_, (context, input, paddings, output, mode), SD_COMMON_TYPES, SD_INDEXING_TYPES); } } // namespace helpers } // namespace ops } // namespace sd
the_stack
#include "correlation_cuda_kernel.h" #define real float #define CUDA_NUM_THREADS 1024 #define THREADS_PER_BLOCK 32 __global__ void channels_first(float* input, float* rinput, int channels, int height, int width, int pad_size) { // n (batch size), c (num of channels), y (height), x (width) int n = blockIdx.x; int y = blockIdx.y; int x = blockIdx.z; int ch_off = threadIdx.x; float value; int dimcyx = channels * height * width; int dimyx = height * width; int p_dimx = (width + 2 * pad_size); int p_dimy = (height + 2 * pad_size); int p_dimyxc = channels * p_dimy * p_dimx; int p_dimxc = p_dimx * channels; for (int c = ch_off; c < channels; c += THREADS_PER_BLOCK) { value = input[n * dimcyx + c * dimyx + y * width + x]; rinput[n * p_dimyxc + (y + pad_size) * p_dimxc + (x + pad_size) * channels + c] = value; } } __global__ void Correlation_forward( float *output, int nOutputChannels, int outputHeight, int outputWidth, float *rInput1, int nInputChannels, int inputHeight, int inputWidth, float *rInput2, int pad_size, int kernel_size, int max_displacement, int stride1, int stride2) { // n (batch size), c (num of channels), y (height), x (width) int pInputWidth = inputWidth + 2 * pad_size; int pInputHeight = inputHeight + 2 * pad_size; int kernel_rad = (kernel_size - 1) / 2; int displacement_rad = max_displacement / stride2; int displacement_size = 2 * displacement_rad + 1; int n = blockIdx.x; int y1 = blockIdx.y * stride1 + max_displacement + kernel_rad; int x1 = blockIdx.z * stride1 + max_displacement + kernel_rad; int c = threadIdx.x; int pdimyxc = pInputHeight * pInputWidth * nInputChannels; int pdimxc = pInputWidth * nInputChannels; int pdimc = nInputChannels; int tdimcyx = nOutputChannels * outputHeight * outputWidth; int tdimyx = outputHeight * outputWidth; int tdimx = outputWidth; float nelems = kernel_size * kernel_size * pdimc; __shared__ float prod_sum[THREADS_PER_BLOCK]; // no significant speed-up in using chip memory for input1 sub-data, // not enough chip memory size to accomodate memory per block for input2 sub-data // instead i've used device memory for both // element-wise product along channel axis for (int tj = -displacement_rad; tj <= displacement_rad; ++tj ) { for (int ti = -displacement_rad; ti <= displacement_rad; ++ti ) { prod_sum[c] = 0; int x2 = x1 + ti*stride2; int y2 = y1 + tj*stride2; for (int j = -kernel_rad; j <= kernel_rad; ++j) { for (int i = -kernel_rad; i <= kernel_rad; ++i) { for (int ch = c; ch < pdimc; ch += THREADS_PER_BLOCK) { int indx1 = n * pdimyxc + (y1+j) * pdimxc + (x1 + i) * pdimc + ch; int indx2 = n * pdimyxc + (y2+j) * pdimxc + (x2 + i) * pdimc + ch; prod_sum[c] += rInput1[indx1] * rInput2[indx2]; } } } // accumulate __syncthreads(); if (c == 0) { float reduce_sum = 0; for (int index = 0; index < THREADS_PER_BLOCK; ++index) { reduce_sum += prod_sum[index]; } int tc = (tj + displacement_rad) * displacement_size + (ti + displacement_rad); const int tindx = n * tdimcyx + tc * tdimyx + blockIdx.y * tdimx + blockIdx.z; output[tindx] = reduce_sum / nelems; } } } } __global__ void Correlation_backward_input1(int item, float *gradInput1, int nInputChannels, int inputHeight, int inputWidth, float *gradOutput, int nOutputChannels, int outputHeight, int outputWidth, float *rInput2, int pad_size, int kernel_size, int max_displacement, int stride1, int stride2) { // n (batch size), c (num of channels), y (height), x (width) int n = item; int y = blockIdx.x * stride1 + pad_size; int x = blockIdx.y * stride1 + pad_size; int c = blockIdx.z; int tch_off = threadIdx.x; int kernel_rad = (kernel_size - 1) / 2; int displacement_rad = max_displacement / stride2; int displacement_size = 2 * displacement_rad + 1; int xmin = (x - kernel_rad - max_displacement) / stride1; int ymin = (y - kernel_rad - max_displacement) / stride1; int xmax = (x + kernel_rad - max_displacement) / stride1; int ymax = (y + kernel_rad - max_displacement) / stride1; if (xmax < 0 || ymax < 0 || xmin >= outputWidth || ymin >= outputHeight) { // assumes gradInput1 is pre-allocated and zero filled return; } if (xmin > xmax || ymin > ymax) { // assumes gradInput1 is pre-allocated and zero filled return; } xmin = max(0,xmin); xmax = min(outputWidth-1,xmax); ymin = max(0,ymin); ymax = min(outputHeight-1,ymax); int pInputWidth = inputWidth + 2 * pad_size; int pInputHeight = inputHeight + 2 * pad_size; int pdimyxc = pInputHeight * pInputWidth * nInputChannels; int pdimxc = pInputWidth * nInputChannels; int pdimc = nInputChannels; int tdimcyx = nOutputChannels * outputHeight * outputWidth; int tdimyx = outputHeight * outputWidth; int tdimx = outputWidth; int odimcyx = nInputChannels * inputHeight* inputWidth; int odimyx = inputHeight * inputWidth; int odimx = inputWidth; float nelems = kernel_size * kernel_size * nInputChannels; __shared__ float prod_sum[THREADS_PER_BLOCK]; prod_sum[tch_off] = 0; for (int tc = tch_off; tc < nOutputChannels; tc += THREADS_PER_BLOCK) { int i2 = (tc % displacement_size - displacement_rad) * stride2; int j2 = (tc / displacement_size - displacement_rad) * stride2; int indx2 = n * pdimyxc + (y + j2)* pdimxc + (x + i2) * pdimc + c; float val2 = rInput2[indx2]; for (int j = ymin; j <= ymax; ++j) { for (int i = xmin; i <= xmax; ++i) { int tindx = n * tdimcyx + tc * tdimyx + j * tdimx + i; prod_sum[tch_off] += gradOutput[tindx] * val2; } } } __syncthreads(); if(tch_off == 0) { float reduce_sum = 0; for(int idx = 0; idx < THREADS_PER_BLOCK; idx++) { reduce_sum += prod_sum[idx]; } const int indx1 = n * odimcyx + c * odimyx + (y - pad_size) * odimx + (x - pad_size); gradInput1[indx1] = reduce_sum / nelems; } } __global__ void Correlation_backward_input2(int item, float *gradInput2, int nInputChannels, int inputHeight, int inputWidth, float *gradOutput, int nOutputChannels, int outputHeight, int outputWidth, float *rInput1, int pad_size, int kernel_size, int max_displacement, int stride1, int stride2) { // n (batch size), c (num of channels), y (height), x (width) int n = item; int y = blockIdx.x * stride1 + pad_size; int x = blockIdx.y * stride1 + pad_size; int c = blockIdx.z; int tch_off = threadIdx.x; int kernel_rad = (kernel_size - 1) / 2; int displacement_rad = max_displacement / stride2; int displacement_size = 2 * displacement_rad + 1; int pInputWidth = inputWidth + 2 * pad_size; int pInputHeight = inputHeight + 2 * pad_size; int pdimyxc = pInputHeight * pInputWidth * nInputChannels; int pdimxc = pInputWidth * nInputChannels; int pdimc = nInputChannels; int tdimcyx = nOutputChannels * outputHeight * outputWidth; int tdimyx = outputHeight * outputWidth; int tdimx = outputWidth; int odimcyx = nInputChannels * inputHeight* inputWidth; int odimyx = inputHeight * inputWidth; int odimx = inputWidth; float nelems = kernel_size * kernel_size * nInputChannels; __shared__ float prod_sum[THREADS_PER_BLOCK]; prod_sum[tch_off] = 0; for (int tc = tch_off; tc < nOutputChannels; tc += THREADS_PER_BLOCK) { int i2 = (tc % displacement_size - displacement_rad) * stride2; int j2 = (tc / displacement_size - displacement_rad) * stride2; int xmin = (x - kernel_rad - max_displacement - i2) / stride1; int ymin = (y - kernel_rad - max_displacement - j2) / stride1; int xmax = (x + kernel_rad - max_displacement - i2) / stride1; int ymax = (y + kernel_rad - max_displacement - j2) / stride1; if (xmax < 0 || ymax < 0 || xmin >= outputWidth || ymin >= outputHeight) { // assumes gradInput2 is pre-allocated and zero filled continue; } if (xmin > xmax || ymin > ymax) { // assumes gradInput2 is pre-allocated and zero filled continue; } xmin = max(0,xmin); xmax = min(outputWidth-1,xmax); ymin = max(0,ymin); ymax = min(outputHeight-1,ymax); int indx1 = n * pdimyxc + (y - j2)* pdimxc + (x - i2) * pdimc + c; float val1 = rInput1[indx1]; for (int j = ymin; j <= ymax; ++j) { for (int i = xmin; i <= xmax; ++i) { int tindx = n * tdimcyx + tc * tdimyx + j * tdimx + i; prod_sum[tch_off] += gradOutput[tindx] * val1; } } } __syncthreads(); if(tch_off == 0) { float reduce_sum = 0; for(int idx = 0; idx < THREADS_PER_BLOCK; idx++) { reduce_sum += prod_sum[idx]; } const int indx2 = n * odimcyx + c * odimyx + (y - pad_size) * odimx + (x - pad_size); gradInput2[indx2] = reduce_sum / nelems; } } #ifdef __cplusplus extern "C" { #endif int Correlation_forward_cuda_kernel(/*THCudaTensor_data(state, output)*/ float *output, /*THCudaTensor_size(state, output, 0)*/ int ob, /*THCudaTensor_size(state, output, 1)*/ int oc, /*THCudaTensor_size(state, output, 2)*/ int oh, /*THCudaTensor_size(state, output, 3)*/ int ow, /*THCudaTensor_stride(state, output, 0)*/ int osb, /*THCudaTensor_stride(state, output, 1)*/ int osc, /*THCudaTensor_stride(state, output, 2)*/ int osh, /*THCudaTensor_stride(state, output, 3)*/ int osw, /*THCudaTensor_data(state, input1)*/ float *input1, /*THCudaTensor_size(state, input1, 1)*/ int ic, /*THCudaTensor_size(state, input1, 2)*/ int ih, /*THCudaTensor_size(state, input1, 3)*/ int iw, /*THCudaTensor_stride(state, input1, 0)*/ int isb, /*THCudaTensor_stride(state, input1, 1)*/ int isc, /*THCudaTensor_stride(state, input1, 2)*/ int ish, /*THCudaTensor_stride(state, input1, 3)*/ int isw, /*THCudaTensor_data(state, input2)*/ float *input2, /*THCudaTensor_size(state, input2, 1)*/ int gc, /*THCudaTensor_stride(state, input2, 0)*/ int gsb, /*THCudaTensor_stride(state, input2, 1)*/ int gsc, /*THCudaTensor_stride(state, input2, 2)*/ int gsh, /*THCudaTensor_stride(state, input2, 3)*/ int gsw, /*THCudaTensor_data(state, rInput1)*/ float *rInput1, /*THCudaTensor_data(state, rInput2)*/ float *rInput2, int pad_size, int kernel_size, int max_displacement, int stride1, int stride2, int corr_type_multiply, /*THCState_getCurrentStream(state)*/ cudaStream_t stream) { int batchSize = ob; int nInputChannels = ic; int inputWidth = iw; int inputHeight = ih; int nOutputChannels = oc; int outputWidth = ow; int outputHeight = oh; dim3 blocks_grid(batchSize, inputHeight, inputWidth); dim3 threads_block(THREADS_PER_BLOCK); channels_first<<<blocks_grid,threads_block, 0, stream>>> (input1,rInput1, nInputChannels, inputHeight, inputWidth,pad_size); channels_first<<<blocks_grid,threads_block, 0, stream>>> (input2,rInput2, nInputChannels, inputHeight, inputWidth, pad_size); dim3 threadsPerBlock(THREADS_PER_BLOCK); dim3 totalBlocksCorr(batchSize, outputHeight, outputWidth); Correlation_forward <<< totalBlocksCorr, threadsPerBlock, 0, stream >>> (output, nOutputChannels, outputHeight, outputWidth, rInput1, nInputChannels, inputHeight, inputWidth, rInput2, pad_size, kernel_size, max_displacement, stride1, stride2); // check for errors cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) { printf("error in Correlation_forward_cuda_kernel: %s\n", cudaGetErrorString(err)); return 0; } return 1; } int Correlation_backward_cuda_kernel( /*THCudaTensor_data(state, gradOutput)*/ float *gradOutput, /*THCudaTensor_size(state, gradOutput, 0)*/ int gob, /*THCudaTensor_size(state, gradOutput, 1)*/ int goc, /*THCudaTensor_size(state, gradOutput, 2)*/ int goh, /*THCudaTensor_size(state, gradOutput, 3)*/ int gow, /*THCudaTensor_stride(state, gradOutput, 0)*/ int gosb, /*THCudaTensor_stride(state, gradOutput, 1)*/ int gosc, /*THCudaTensor_stride(state, gradOutput, 2)*/ int gosh, /*THCudaTensor_stride(state, gradOutput, 3)*/ int gosw, /*THCudaTensor_data(state, input1)*/ float* input1, /*THCudaTensor_size(state, input1, 1)*/ int ic, /*THCudaTensor_size(state, input1, 2)*/ int ih, /*THCudaTensor_size(state, input1, 3)*/ int iw, /*THCudaTensor_stride(state, input1, 0)*/ int isb, /*THCudaTensor_stride(state, input1, 1)*/ int isc, /*THCudaTensor_stride(state, input1, 2)*/ int ish, /*THCudaTensor_stride(state, input1, 3)*/ int isw, /*THCudaTensor_data(state, input2)*/ float *input2, /*THCudaTensor_stride(state, input2, 0)*/ int gsb, /*THCudaTensor_stride(state, input2, 1)*/ int gsc, /*THCudaTensor_stride(state, input2, 2)*/ int gsh, /*THCudaTensor_stride(state, input2, 3)*/ int gsw, /*THCudaTensor_data(state, gradInput1)*/ float *gradInput1, /*THCudaTensor_stride(state, gradInput1, 0)*/ int gisb, /*THCudaTensor_stride(state, gradInput1, 1)*/ int gisc, /*THCudaTensor_stride(state, gradInput1, 2)*/ int gish, /*THCudaTensor_stride(state, gradInput1, 3)*/ int gisw, /*THCudaTensor_data(state, gradInput2)*/ float *gradInput2, /*THCudaTensor_size(state, gradInput2, 1)*/ int ggc, /*THCudaTensor_stride(state, gradInput2, 0)*/ int ggsb, /*THCudaTensor_stride(state, gradInput2, 1)*/ int ggsc, /*THCudaTensor_stride(state, gradInput2, 2)*/ int ggsh, /*THCudaTensor_stride(state, gradInput2, 3)*/ int ggsw, /*THCudaTensor_data(state, rInput1)*/ float *rInput1, /*THCudaTensor_data(state, rInput2)*/ float *rInput2, int pad_size, int kernel_size, int max_displacement, int stride1, int stride2, int corr_type_multiply, /*THCState_getCurrentStream(state)*/cudaStream_t stream) { int batchSize = gob; int num = batchSize; int nInputChannels = ic; int inputWidth = iw; int inputHeight = ih; int nOutputChannels = goc; int outputWidth = gow; int outputHeight = goh; dim3 blocks_grid(batchSize, inputHeight, inputWidth); dim3 threads_block(THREADS_PER_BLOCK); channels_first<<<blocks_grid,threads_block, 0, stream>>> (input1, rInput1, nInputChannels,inputHeight, inputWidth, pad_size); channels_first<<<blocks_grid,threads_block, 0, stream>>> (input2, rInput2, nInputChannels, inputHeight, inputWidth, pad_size); dim3 threadsPerBlock(THREADS_PER_BLOCK); dim3 totalBlocksCorr(inputHeight, inputWidth, nInputChannels); for (int n = 0; n < num; ++n) { Correlation_backward_input1 << <totalBlocksCorr, threadsPerBlock, 0, stream >> > ( n, gradInput1, nInputChannels, inputHeight, inputWidth, gradOutput, nOutputChannels, outputHeight, outputWidth, rInput2, pad_size, kernel_size, max_displacement, stride1, stride2); } for(int n = 0; n < batchSize; n++) { Correlation_backward_input2<<<totalBlocksCorr, threadsPerBlock, 0, stream>>>( n, gradInput2, nInputChannels, inputHeight, inputWidth, gradOutput, nOutputChannels, outputHeight, outputWidth, rInput1, pad_size, kernel_size, max_displacement, stride1, stride2); } // check for errors cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) { printf("error in Correlation_backward_cuda_kernel: %s\n", cudaGetErrorString(err)); return 0; } return 1; } #ifdef __cplusplus } #endif
the_stack
#include <nbla/array.hpp> #include <nbla/cuda/common.hpp> #include <nbla/cuda/function/random_erase.hpp> #include <nbla/cuda/utils/nd_index.cuh> #include <nbla/cuda/utils/random.cuh> #include <nbla/variable.hpp> #include <curand_kernel.h> namespace nbla { namespace random_erase { template <typename T, bool accum = true> __global__ void kernel_copy(const int size, T *gx, const T *gy) { NBLA_CUDA_KERNEL_LOOP(idx, size) { gx[idx] = accum ? gx[idx] + gy[idx] : gy[idx]; } } __global__ void kernel_create_random_coordinates(const int size, float *random_coords, const int H, const int W, const float2 area_ratios, const float2 aspect_ratios) { auto S = H * W; NBLA_CUDA_KERNEL_LOOP(idx, size) { auto elm0 = random_coords[idx]; auto elm1 = random_coords[idx + size * 1]; auto elm2 = random_coords[idx + size * 2]; auto elm3 = random_coords[idx + size * 3]; auto elm4 = random_coords[idx + size * 4]; auto eprob = elm0; auto Se = ((area_ratios.y - area_ratios.x) * elm1 + area_ratios.x) * S; auto re = (aspect_ratios.y - aspect_ratios.x) * elm2 + aspect_ratios.x; auto He = sqrt(Se * re); auto We = sqrt(Se / re); He = min(He, (float)H); We = min(We, (float)W); int ye_start = (H - He) * elm3; int xe_start = (W - We) * elm4; random_coords[idx] = eprob; random_coords[idx + size * 1] = ye_start; random_coords[idx + size * 2] = xe_start; random_coords[idx + size * 3] = ye_start + He; random_coords[idx + size * 4] = xe_start + We; } } template <typename T, bool channel_last = false, bool share = true, bool accum = false> __global__ void kernel_random_erase_backward(const int size, T *gx, const T *gy, int3 dstride, int N, const float *random_coords, int3 estride, float prob, float2 replacements) { // size: B x C x H x W // y, x: (B, C, H, W) or (B, H, W, C) // random_coords: (5, N, B) or (5, N, B, C) NBLA_CUDA_KERNEL_LOOP(idx, size) { auto nd_index = device_flat_to_4d(idx, dstride); auto b = nd_index.x; auto c = channel_last ? nd_index.w : nd_index.y; auto h = channel_last ? nd_index.y : nd_index.z; auto w = channel_last ? nd_index.z : nd_index.w; auto fall = false; for (int n = 0; n < N; n++) { auto offset = share ? (n * estride.y + b) : (n * estride.y + b * estride.z + c); float eprob = random_coords[0 * estride.x + offset]; int ye_start = random_coords[1 * estride.x + offset]; int xe_start = random_coords[2 * estride.x + offset]; int ye_end = random_coords[3 * estride.x + offset]; int xe_end = random_coords[4 * estride.x + offset]; if ((eprob <= prob) && (ye_start <= h && h <= ye_end) && (xe_start <= w && w <= xe_end)) { fall = true; break; } } if (fall) { gx[idx] = accum ? (gx[idx] + T(0)) : T(0); } else { gx[idx] = accum ? (gx[idx] + gy[idx]) : gy[idx]; } } } template <typename T, bool channel_last = false, bool share = true> __global__ void kernel_random_erase(const int size, T *y, const T *x, int3 dstride, int N, int4 shape, const float *random_coords, int3 estride, float prob, curandState *func_state, float2 replacements) { // size: H x W // y, x: (B, C, H, W) or (B, H, W, C) // random_coords: (5, N, B) or (5, N, B, C) // Minimize size of func_states since it cannot be reused over layers NBLA_CUDA_KERNEL_LOOP(idx, size) { auto B = shape.x; auto C = channel_last ? shape.w : shape.y; auto W = channel_last ? shape.z : shape.w; auto h = idx / W; auto w = idx - h * W; curandState local_state = func_state[idx]; for (int n = 0; n < N; n++) { for (int b = 0; b < B; b++) { for (int c = 0; c < C; c++) { auto offset = share ? (n * estride.y + b) : (n * estride.y + b * estride.z + c); float eprob = random_coords[0 * estride.x + offset]; int ye_start = random_coords[1 * estride.x + offset]; int xe_start = random_coords[2 * estride.x + offset]; int ye_end = random_coords[3 * estride.x + offset]; int xe_end = random_coords[4 * estride.x + offset]; auto nd_index = channel_last ? make_int4(b, h, w, c) : make_int4(b, c, h, w); auto idx_data = device_4d_to_flat(nd_index, dstride); if ((eprob <= prob) && (ye_start <= h && h <= ye_end) && (xe_start <= w && w <= xe_end)) { y[idx_data] = curand_uniform(&local_state, replacements.x, replacements.y); } } } } func_state[idx] = local_state; } } } template <typename T> void RandomEraseCuda<T>::setup_impl(const Variables &inputs, const Variables &outputs) { RandomErase<T>::setup_impl(inputs, outputs); cuda_set_device(this->device_); auto shape = inputs[0]->shape(); auto H = this->channel_last_ ? shape[this->base_axis_] : shape[this->base_axis_ + 1]; auto W = this->channel_last_ ? shape[this->base_axis_ + 1] : shape[this->base_axis_ + 2]; this->state_ = std::make_shared<NdArray>( Shape_t{static_cast<long>(H * W * sizeof(curandState))}); curandState *func_state = this->state_->cast(get_dtype<char>(), this->ctx_) ->template pointer<curandState>(); curand_initialize(H * W, this->seed_, 0, func_state); output_data_for_recomp_.reshape(outputs[0]->shape(), true); } template <typename T> void RandomEraseCuda<T>::setup_recompute_impl(const Variables &inputs, const Variables &outputs) { save_output_data_ = true; } template <typename T> void RandomEraseCuda<T>::forward_impl(const Variables &inputs, const Variables &outputs) { cuda_set_device(this->device_); // Settings auto shape = inputs[0]->shape(); auto N = this->n_; auto B = std::accumulate(shape.begin(), std::next(shape.begin(), this->base_axis_), 1, std::multiplies<size_t>()); auto C = this->channel_last_ ? shape[this->base_axis_ + 2] : shape[this->base_axis_]; auto H = this->channel_last_ ? shape[this->base_axis_] : shape[this->base_axis_ + 1]; auto W = this->channel_last_ ? shape[this->base_axis_ + 1] : shape[this->base_axis_ + 2]; // Generate 5 x N x B (x C), 5 is {prob, Se, re, xe, ye} this->random_coordinates_ = this->share_ ? std::make_shared<NdArray>(Shape_t{5, N, B}) : std::make_shared<NdArray>(Shape_t{5, N, B, C}); float *random_coords = this->random_coordinates_->cast(get_dtype<float>(), this->ctx_) ->template pointer<float>(); curandGenerator_t &gen = this->seed_ == -1 ? SingletonManager::get<Cuda>()->curand_generator() : curand_generator_; curand_generate_rand<float>(gen, 0.0f, 1.0f, random_coords, this->random_coordinates_->size()); // Create 5 x N x B (x C), 5 is {prob, ye_start, xe_start, ye_end, xe_end} // inplace auto area_ratios = make_float2(this->area_ratios_[0], this->area_ratios_[1]); auto aspect_ratios = make_float2(this->aspect_ratios_[0], this->aspect_ratios_[1]); NBLA_CUDA_LAUNCH_KERNEL_SIMPLE( (random_erase::kernel_create_random_coordinates), this->random_coordinates_->size() / 5, random_coords, H, W, area_ratios, aspect_ratios); // Copy once auto size = inputs[0]->size(); Tcu *y = outputs[0]->cast_data_and_get_pointer<Tcu>(this->ctx_, true); const Tcu *x = inputs[0]->get_data_pointer<Tcu>(this->ctx_); NBLA_CUDA_LAUNCH_KERNEL_SIMPLE((random_erase::kernel_copy<Tcu, false>), size, y, x); // Replace auto dstride = this->channel_last_ ? make_int3(H * W * C, W * C, C) : make_int3(C * H * W, H * W, W); auto dshape = this->channel_last_ ? make_int4(B, H, W, C) : make_int4(B, C, H, W); auto estride = this->share_ ? make_int3(N * B, B, 1) : make_int3(N * B * C, B * C, C); curandState *func_state = this->state_->cast(get_dtype<char>(), this->ctx_) ->template pointer<curandState>(); auto replacements = make_float2(this->replacements_[0], this->replacements_[1]); using random_erase::kernel_random_erase; auto kernel = this->channel_last_ ? (this->share_ ? kernel_random_erase<Tcu, true, true> : kernel_random_erase<Tcu, true, false>) : (this->share_ ? kernel_random_erase<Tcu, false, true> : kernel_random_erase<Tcu, false, false>); NBLA_CUDA_LAUNCH_KERNEL_SIMPLE(kernel, H * W, y, x, dstride, N, dshape, random_coords, estride, this->prob_, func_state, replacements); // Release memory if (!this->ste_fine_grained_) { this->random_coordinates_ = nullptr; } // Save output data for recomputation. if (save_output_data_) { save_output_data<Tcu>(this->ctx_, outputs[0], output_data_for_recomp_); } } template <typename T> void RandomEraseCuda<T>::recompute_impl(const Variables &inputs, const Variables &outputs) { // Restore output data of previous forward execution. restore_output_data<Tcu>(this->ctx_, output_data_for_recomp_, outputs[0]); save_output_data_ = false; } template <typename T> void RandomEraseCuda<T>::backward_impl(const Variables &inputs, const Variables &outputs, const vector<bool> &propagate_down, const vector<bool> &accum) { if (!(propagate_down[0])) { return; } cuda_set_device(this->device_); auto size = inputs[0]->size(); const Tcu *gy = outputs[0]->get_grad_pointer<Tcu>(this->ctx_); Tcu *gx = inputs[0]->cast_grad_and_get_pointer<Tcu>(this->ctx_, !accum[0]); // STE if (!this->ste_fine_grained_) { if (accum[0]) { NBLA_CUDA_LAUNCH_KERNEL_SIMPLE((random_erase::kernel_copy<Tcu, true>), size, gx, gy); } else { NBLA_CUDA_LAUNCH_KERNEL_SIMPLE((random_erase::kernel_copy<Tcu, false>), size, gx, gy); } return; } // Correct backward auto shape = inputs[0]->shape(); auto N = this->n_; auto B = std::accumulate(shape.begin(), std::next(shape.begin(), this->base_axis_), 1, std::multiplies<size_t>()); auto C = this->channel_last_ ? shape[this->base_axis_ + 2] : shape[this->base_axis_]; auto H = this->channel_last_ ? shape[this->base_axis_] : shape[this->base_axis_ + 1]; auto W = this->channel_last_ ? shape[this->base_axis_ + 1] : shape[this->base_axis_ + 2]; auto dstride = this->channel_last_ ? make_int3(H * W * C, W * C, C) : make_int3(C * H * W, H * W, W); auto estride = this->share_ ? make_int3(N * B, B, 1) : make_int3(N * B * C, B * C, C); float *random_coords = this->random_coordinates_->cast(get_dtype<float>(), this->ctx_) ->template pointer<float>(); auto replacements = make_float2(this->replacements_[0], this->replacements_[1]); using random_erase::kernel_random_erase_backward; if (accum[0]) { auto kernel = this->channel_last_ ? (this->share_ ? kernel_random_erase_backward<Tcu, true, true, true> : kernel_random_erase_backward<Tcu, true, false, true>) : (this->share_ ? kernel_random_erase_backward<Tcu, false, true, true> : kernel_random_erase_backward<Tcu, false, false, true>); NBLA_CUDA_LAUNCH_KERNEL_SIMPLE(kernel, size, gx, gy, dstride, N, random_coords, estride, this->prob_, replacements); } else { auto kernel = this->channel_last_ ? (this->share_ ? kernel_random_erase_backward<Tcu, true, true, false> : kernel_random_erase_backward<Tcu, true, false, false>) : (this->share_ ? kernel_random_erase_backward<Tcu, false, true, false> : kernel_random_erase_backward<Tcu, false, false, false>); NBLA_CUDA_LAUNCH_KERNEL_SIMPLE(kernel, size, gx, gy, dstride, N, random_coords, estride, this->prob_, replacements); } // Release memory this->random_coordinates_ = nullptr; } }
the_stack
#include <nvbench/benchmark_base.cuh> #include <nvbench/device_info.cuh> #include <nvbench/printer_base.cuh> #include <nvbench/state.cuh> #include <nvbench/summary.cuh> #include <nvbench/detail/ring_buffer.cuh> #include <nvbench/detail/throw.cuh> #include <fmt/format.h> #include <algorithm> #include <cstdio> #include <stdexcept> #include <variant> namespace nvbench::detail { measure_cold_base::measure_cold_base(state &exec_state) : m_state{exec_state} , m_run_once{exec_state.get_run_once()} , m_min_samples{exec_state.get_min_samples()} , m_max_noise{exec_state.get_max_noise()} , m_min_time{exec_state.get_min_time()} , m_skip_time{exec_state.get_skip_time()} , m_timeout{exec_state.get_timeout()} {} void measure_cold_base::check() { const auto device = m_state.get_device(); if (!device) { NVBENCH_THROW(std::runtime_error, "{}", "Device required for `cold` measurement."); } if (!device->is_active()) { // This means something went wrong higher up. Throw an error. NVBENCH_THROW(std::runtime_error, "{}", "Internal error: Current device is not active."); } } void measure_cold_base::initialize() { m_total_cuda_time = 0.; m_total_cpu_time = 0.; m_cpu_noise = 0.; m_total_samples = 0; m_noise_tracker.clear(); m_cuda_times.clear(); m_cpu_times.clear(); m_max_time_exceeded = false; } void measure_cold_base::run_trials_prologue() { m_walltime_timer.start(); } void measure_cold_base::record_measurements() { // Update and record timers and counters: const auto cur_cuda_time = m_cuda_timer.get_duration(); const auto cur_cpu_time = m_cpu_timer.get_duration(); m_cuda_times.push_back(cur_cuda_time); m_cpu_times.push_back(cur_cpu_time); m_total_cuda_time += cur_cuda_time; m_total_cpu_time += cur_cpu_time; ++m_total_samples; // Compute convergence statistics using CUDA timings: const auto mean_cuda_time = m_total_cuda_time / static_cast<nvbench::float64_t>(m_total_samples); const auto cuda_stdev = nvbench::detail::statistics::standard_deviation(m_cuda_times.cbegin(), m_cuda_times.cend(), mean_cuda_time); auto cuda_rel_stdev = cuda_stdev / mean_cuda_time; if (std::isfinite(cuda_rel_stdev)) { m_noise_tracker.push_back(cuda_rel_stdev); } } bool measure_cold_base::is_finished() { if (m_run_once) { return true; } // Check that we've gathered enough samples: if (m_total_cuda_time > m_min_time && m_total_samples > m_min_samples) { // Noise has dropped below threshold if (m_noise_tracker.back() < m_max_noise) { return true; } // Check if the noise (cuda rel stdev) has converged by inspecting a // trailing window of recorded noise measurements. // This helps identify benchmarks that are inherently noisy and would // never converge to the target stdev threshold. This check ensures that the // benchmark will end if the stdev stabilizes above the target threshold. // Gather some iterations before checking noise, and limit how often we // check this. if (m_noise_tracker.size() > 64 && (m_total_samples % 16 == 0)) { // Use the current noise as the stdev reference. const auto current_noise = m_noise_tracker.back(); const auto noise_stdev = nvbench::detail::statistics::standard_deviation( m_noise_tracker.cbegin(), m_noise_tracker.cend(), current_noise); const auto noise_rel_stdev = noise_stdev / current_noise; // If the rel stdev of the last N cuda noise measurements is less than // 5%, consider the result stable. const auto noise_threshold = 0.05; if (noise_rel_stdev < noise_threshold) { return true; } } } // Check for timeouts: m_walltime_timer.stop(); if (m_walltime_timer.get_duration() > m_timeout) { m_max_time_exceeded = true; return true; } return false; } void measure_cold_base::run_trials_epilogue() { // Only need to compute this at the end, not per iteration. const auto cpu_mean = m_total_cuda_time / static_cast<nvbench::float64_t>(m_total_samples); const auto cpu_stdev = nvbench::detail::statistics::standard_deviation(m_cpu_times.cbegin(), m_cpu_times.cend(), cpu_mean); m_cpu_noise = cpu_stdev / cpu_mean; m_walltime_timer.stop(); } void measure_cold_base::generate_summaries() { const auto d_samples = static_cast<double>(m_total_samples); { auto &summ = m_state.add_summary("Number of Samples (Cold)"); summ.set_string("hint", "sample_size"); summ.set_string("short_name", "Samples"); summ.set_string("description", "Number of kernel executions in cold time measurements."); summ.set_int64("value", m_total_samples); } const auto avg_cpu_time = m_total_cpu_time / d_samples; { auto &summ = m_state.add_summary("Average CPU Time (Cold)"); summ.set_string("hint", "duration"); summ.set_string("short_name", "CPU Time"); summ.set_string("description", "Average isolated kernel execution time observed " "from host."); summ.set_float64("value", avg_cpu_time); } { auto &summ = m_state.add_summary("CPU Relative Standard Deviation (Cold)"); summ.set_string("hint", "percentage"); summ.set_string("short_name", "Noise"); summ.set_string("description", "Relative standard deviation of the cold CPU execution " "time measurements."); summ.set_float64("value", m_cpu_noise); } const auto avg_cuda_time = m_total_cuda_time / d_samples; { auto &summ = m_state.add_summary("Average GPU Time (Cold)"); summ.set_string("hint", "duration"); summ.set_string("short_name", "GPU Time"); summ.set_string("description", "Average isolated kernel execution time as measured " "by CUDA events."); summ.set_float64("value", avg_cuda_time); } { auto &summ = m_state.add_summary("GPU Relative Standard Deviation (Cold)"); summ.set_string("hint", "percentage"); summ.set_string("short_name", "Noise"); summ.set_string("description", "Relative standard deviation of the cold GPU execution " "time measurements."); summ.set_float64("value", m_noise_tracker.empty() ? std::numeric_limits<nvbench::float64_t>::infinity() : m_noise_tracker.back()); } if (const auto items = m_state.get_element_count(); items != 0) { auto &summ = m_state.add_summary("Element Throughput"); summ.set_string("hint", "item_rate"); summ.set_string("short_name", "Elem/s"); summ.set_string("description", "Number of input elements handled per second."); summ.set_float64("value", static_cast<double>(items) / avg_cuda_time); } if (const auto bytes = m_state.get_global_memory_rw_bytes(); bytes != 0) { const auto avg_used_gmem_bw = static_cast<double>(bytes) / avg_cuda_time; { auto &summ = m_state.add_summary("Average Global Memory Throughput"); summ.set_string("hint", "byte_rate"); summ.set_string("short_name", "GlobalMem BW"); summ.set_string("description", "Number of bytes read/written per second to the CUDA " "device's global memory."); summ.set_float64("value", avg_used_gmem_bw); } { const auto peak_gmem_bw = static_cast<double>( m_state.get_device()->get_global_memory_bus_bandwidth()); auto &summ = m_state.add_summary("Percent Peak Global Memory Throughput"); summ.set_string("hint", "percentage"); summ.set_string("short_name", "BWPeak"); summ.set_string("description", "Global device memory throughput as a percentage of the " "device's peak bandwidth."); summ.set_float64("value", avg_used_gmem_bw / peak_gmem_bw); } } // Log if a printer exists: if (auto printer_opt_ref = m_state.get_benchmark().get_printer(); printer_opt_ref.has_value()) { auto &printer = printer_opt_ref.value().get(); if (m_max_time_exceeded) { const auto timeout = m_walltime_timer.get_duration(); if (!m_noise_tracker.empty() && m_noise_tracker.back() > m_max_noise) { printer.log(nvbench::log_level::warn, fmt::format("Current measurement timed out ({:0.2f}s) " "while over noise threshold ({:0.2f}% > " "{:0.2f}%)", timeout, m_noise_tracker.back() * 100, m_max_noise * 100)); } if (m_total_samples < m_min_samples) { printer.log(nvbench::log_level::warn, fmt::format("Current measurement timed out ({:0.2f}s) " "before accumulating min_samples ({} < {})", timeout, m_total_samples, m_min_samples)); } if (m_total_cuda_time < m_min_time) { printer.log(nvbench::log_level::warn, fmt::format("Current measurement timed out ({:0.2f}s) " "before accumulating min_time ({:0.2f}s < " "{:0.2f}s)", timeout, m_total_cuda_time, m_min_time)); } } // Log to stdout: printer.log(nvbench::log_level::pass, fmt::format("Cold: {:0.6f}ms GPU, {:0.6f}ms CPU, {:0.2f}s " "total GPU, {}x", avg_cuda_time * 1e3, avg_cpu_time * 1e3, m_total_cuda_time, m_total_samples)); } } void measure_cold_base::check_skip_time(nvbench::float64_t warmup_time) { if (m_skip_time > 0. && warmup_time < m_skip_time) { auto reason = fmt::format("Warmup time did not meet skip_time limit: " "{:0.3f}us < {:0.3f}us.", warmup_time * 1e6, m_skip_time * 1e6); m_state.skip(reason); NVBENCH_THROW(std::runtime_error, "{}", std::move(reason)); } } void measure_cold_base::block_stream() { m_blocker.block(m_launch.get_stream(), m_state.get_blocking_kernel_timeout()); } } // namespace nvbench::detail
the_stack
#include <stdlib.h> #include <stdio.h> #include "cuda.h" extern int nblock_size; extern int maxgsx; static cudaError_t crc; extern "C" void gpu_deallocate(void *g_d, int *irc); extern "C" void gpu_iallocate(int **g_i, int nsize, int *irc); /*--------------------------------------------------------------------*/ __device__ void liscan2(int *isdata, int nths) { /* performs local prefix reduction of integer data shared by threads */ /* using binary tree method. */ /* local data */ int l, mb, kxs, lb, kb; l = threadIdx.x; mb = l; kxs = 1; while (kxs < nths) { lb = kxs*mb; kb = 2*lb + kxs - 1; lb += l + kxs; if (lb < nths) { isdata[lb] += isdata[kb]; } __syncthreads(); mb >>= 1; kxs <<= 1; } return; } /*--------------------------------------------------------------------*/ __device__ void lsum2(float *sdata, int n) { /* finds local sum of nths data items shared by threads */ /* using binary tree method. input is modified. */ /* local data */ int l, k; float s; l = threadIdx.x; k = blockDim.x >> 1; s = 0.0f; if (l < n) s = sdata[l]; while (k > 0) { if (l < k) { if ((l+k) < n) { s += sdata[l+k]; sdata[l] = s; } } __syncthreads(); k >>= 1; } return; } /*--------------------------------------------------------------------*/ __global__ void gpuppgppush2l(float ppart[], float fxy[], int kpic[], int noff, int nyp, float qbm, float dt, float *ek, int nx, int ny, int mx, int my, int idimp, int nppmx, int nxv, int nypmx, int mx1, int mxyp1, int ipbc) { /* for 2d code, this subroutine updates particle co-ordinates and velocities using leap-frog scheme in time and first-order linear interpolation in space, with various boundary conditions threaded version using guard cells, for distributed data data read in tiles particles stored segmented array 42 flops/particle, 12 loads, 4 stores input: all except ihole, output: ppart, ek equations used are: vx(t+dt/2) = vx(t-dt/2) + (q/m)*fx(x(t),y(t))*dt, vy(t+dt/2) = vy(t-dt/2) + (q/m)*fy(x(t),y(t))*dt, where q/m is charge/mass, and x(t+dt) = x(t) + vx(t+dt/2)*dt, y(t+dt) = y(t) + vy(t+dt/2)*dt fx(x(t),y(t)) and fy(x(t),y(t)) are approximated by interpolation from the nearest grid points: fx(x,y) = (1-dy)*((1-dx)*fx(n,m)+dx*fx(n+1,m)) + dy*((1-dx)*fx(n,m+1) + dx*fx(n+1,m+1)) fy(x,y) = (1-dy)*((1-dx)*fy(n,m)+dx*fy(n+1,m)) + dy*((1-dx)*fy(n,m+1) + dx*fy(n+1,m+1)) where n,m = leftmost grid points and dx = x-n, dy = y-m ppart[m][0][n] = position x of particle n in partition in tile m ppart[m][1][n] = position y of particle n in partition in tile m ppart[m][2][n] = velocity vx of particle n in partition in tile m ppart[m][3][n] = velocity vy of particle n in partition in tile m fxy[k][j][0] = x component of force/charge at grid (j,kk) fxy[k][j][1] = y component of force/charge at grid (j,kk) in other words, fxy are the convolutions of the electric field over the particle shape, where kk = k + noff kpic = number of particles per tile noff = lowermost global gridpoint in particle partition. nyp = number of primary (complete) gridpoints in particle partition qbm = particle charge/mass ratio dt = time interval between successive calculations kinetic energy/mass at time t is also calculated, using ek = .125*sum((vx(t+dt/2)+vx(t-dt/2))**2+(vy(t+dt/2)+vy(t-dt/2))**2) nx/ny = system length in x/y direction mx/my = number of grids in sorting cell in x/y idimp = size of phase space = 4 nppmx = maximum number of particles in tile nxv = first dimension of field array, must be >= nx+1 nypmx = maximum size of particle partition, including guard cells. mx1 = (system length in x direction - 1)/mx + 1 mxyp1 = mx1*myp1, where myp1=(partition length in y direction-1)/my+1 ipbc = particle boundary condition = (0,1,2,3) = (none,2d periodic,2d reflecting,mixed reflecting/periodic) local data */ int noffp, moffp, npoff, nppp, mxv; int mnoff, i, j, k, ii, nn, mm; float qtm, edgelx, edgely, edgerx, edgery, dxp, dyp, amx, amy; float x, y, dx, dy, vx, vy; /* The sizes of the shared memory arrays are as follows: */ /* float sfxy[2*(mx+1)*(my+1)], sek[blockDim.x]; */ /* to conserve memory, sek overlaps with sfxy */ /* and the name sfxy is used instead of sek */ extern __shared__ float sfxy[]; double sum1; qtm = qbm*dt; sum1 = 0.0; /* set boundary values */ edgelx = 0.0f; edgely = 1.0f; edgerx = (float) (nx); edgery = (float) (ny-1); if ((ipbc==2) || (ipbc==3)) { edgelx = 1.0f; edgerx = (float) (nx-1); } mxv = mx + 1; /* k = tile number */ k = blockIdx.x + gridDim.x*blockIdx.y; /* loop over tiles */ if (k < mxyp1) { noffp = k/mx1; moffp = my*noffp; noffp = mx*(k - mx1*noffp); nppp = kpic[k]; npoff = idimp*nppmx*k; mnoff = moffp + noff; /* load local fields from global array */ nn = (mx < nx-noffp ? mx : nx-noffp) + 1; mm = (my < nyp-moffp ? my : nyp-moffp) + 1; ii = threadIdx.x; while (ii < mxv*(my+1)) { j = ii/mxv; i = ii - mxv*j; if ((i < nn) && (j < mm)) { sfxy[2*ii] = fxy[2*(i+noffp+nxv*(j+moffp))]; sfxy[1+2*ii] = fxy[1+2*(i+noffp+nxv*(j+moffp))]; } ii += blockDim.x; } /* synchronize threads */ __syncthreads(); /* loop over particles in tile */ j = threadIdx.x; while (j < nppp) { /* find interpolation weights */ x = ppart[j+npoff]; nn = x; y = ppart[j+npoff+nppmx]; mm = y; dxp = x - (float) nn; dyp = y - (float) mm; nn = 2*(nn - noffp) + 2*mxv*(mm - mnoff); amx = 1.0f - dxp; amy = 1.0f - dyp; /* find acceleration */ dx = amx*sfxy[nn]; dy = amx*sfxy[1+nn]; dx = amy*(dxp*sfxy[2+nn] + dx); dy = amy*(dxp*sfxy[3+nn] + dy); nn += 2*mxv; vx = amx*sfxy[nn]; vy = amx*sfxy[1+nn]; dx += dyp*(dxp*sfxy[2+nn] + vx); dy += dyp*(dxp*sfxy[3+nn] + vy); /* new velocity */ vx = ppart[j+npoff+nppmx*2]; vy = ppart[j+npoff+nppmx*3]; dx = vx + qtm*dx; dy = vy + qtm*dy; /* average kinetic energy */ vx += dx; vy += dy; sum1 += (double) (vx*vx + vy*vy); ppart[j+npoff+nppmx*2] = dx; ppart[j+npoff+nppmx*3] = dy; /* new position */ dx = x + dx*dt; dy = y + dy*dt; /* reflecting boundary conditions */ if (ipbc==2) { if ((dx < edgelx) || (dx >= edgerx)) { dx = ppart[j+npoff]; ppart[j+npoff+nppmx*2] = -ppart[j+npoff+nppmx*2]; } if ((dy < edgely) || (dy >= edgery)) { dy = ppart[j+npoff+nppmx]; ppart[j+npoff+nppmx*3] = -ppart[j+npoff+nppmx*3]; } } /* mixed reflecting/periodic boundary conditions */ else if (ipbc==3) { if ((dx < edgelx) || (dx >= edgerx)) { dx = ppart[j+npoff]; ppart[j+npoff+nppmx*2] = -ppart[j+npoff+nppmx*2]; } } /* set new position */ ppart[j+npoff] = dx; ppart[j+npoff+nppmx] = dy; j += blockDim.x; } /* synchronize threads */ __syncthreads(); /* add kinetic energies in tile */ sfxy[threadIdx.x] = (float) sum1; /* synchronize threads */ __syncthreads(); lsum2(sfxy,blockDim.x); /* normalize kinetic energy of tile */ if (threadIdx.x==0) { ek[k] = 0.125f*sfxy[0]; } } return; } /*--------------------------------------------------------------------*/ __global__ void gpu2ppgppost2l(float ppart[], float q[], int kpic[], int noff, float qm, int idimp, int nppmx, int mx, int my, int nxv, int nypmx, int mx1, int mxyp1) { /* for 2d code, this subroutine calculates particle charge density using first-order linear interpolation, periodic boundaries threaded version using guard cells, for distributed data data deposited in tiles particles stored segmented array 17 flops/particle, 6 loads, 4 stores input: all, output: q charge density is approximated by values at the nearest grid points q(n,m)=qm*(1.-dx)*(1.-dy) q(n+1,m)=qm*dx*(1.-dy) q(n,m+1)=qm*(1.-dx)*dy q(n+1,m+1)=qm*dx*dy where n,m = leftmost grid points and dx = x-n, dy = y-m ppart[m][n][0] = position x of particle n in partition in tile m ppart[m][n][1] = position y of particle n in partition in tile m q[k][j] = charge density at grid point (j,kk), where kk = k + noff kpic = number of particles per tile noff = lowermost global gridpoint in particle partition. qm = charge on particle, in units of e idimp = size of phase space = 4 nppmx = maximum number of particles in tile mx/my = number of grids in sorting cell in x/y nxv = first dimension of charge array, must be >= nx+1 nypmx = maximum size of particle partition, including guard cells. mx1 = (system length in x direction - 1)/mx + 1 mxyp1 = mx1*myp1, where myp1=(partition length in y direction-1)/my+1 local data */ int noffp, moffp, npoff, nppp, mxv; int mnoff, i, j, k, ii, nn, np, mm, mp; float dxp, dyp, amx, amy; /* The size of the shared memory array is as follows: */ /* float sq[(mx+1)*(my+1)] */ extern __shared__ float sq[]; mxv = mx + 1; /* k = tile number */ k = blockIdx.x + gridDim.x*blockIdx.y; /* loop over tiles */ if (k < mxyp1) { noffp = k/mx1; moffp = my*noffp; noffp = mx*(k - mx1*noffp); nppp = kpic[k]; npoff = idimp*nppmx*k; mnoff = moffp + noff; /* zero out local accumulator */ i = threadIdx.x; while (i < mxv*(my+1)) { sq[i] = 0.0f; i += blockDim.x; } /* synchronize threads */ __syncthreads(); /* loop over particles in tile */ j = threadIdx.x; while (j < nppp) { /* find interpolation weights */ dxp = ppart[j+npoff]; nn = dxp; dyp = ppart[j+npoff+nppmx]; mm = dyp; dxp = qm*(dxp - (float) nn); dyp = dyp - (float) mm; nn = nn - noffp; mm = mxv*(mm - mnoff); amx = qm - dxp; mp = mm + mxv; amy = 1.0f - dyp; np = nn + 1; /* deposit charge within tile to local accumulator */ /* original deposit charge, has data hazard on GPU */ /* sq[np+mp] += dxp*dyp; */ /* sq[nn+mp] += amx*dyp; */ /* sq[np+mm] += dxp*amy; */ /* sq[nn+mm] += amx*amy; */ /* for devices with compute capability 2.x */ atomicAdd(&sq[np+mp],dxp*dyp); atomicAdd(&sq[nn+mp],amx*dyp); atomicAdd(&sq[np+mm],dxp*amy); atomicAdd(&sq[nn+mm],amx*amy); j += blockDim.x; } /* synchronize threads */ __syncthreads(); /* deposit charge to global array */ nn = mxv < nxv-noffp ? mxv : nxv-noffp; mm = my+1 < nypmx-moffp ? my+1 : nypmx-moffp; ii = threadIdx.x; while (ii < mxv*(my+1)) { j = ii/mxv; i = ii - mxv*j; if ((i < nn) && (j < mm)) { /* original deposit charge, has data hazard on GPU */ /* q[i+noffp+nxv*(j+moffp)] += sq[ii]; */ /* for devices with compute capability 2.x */ atomicAdd(&q[i+noffp+nxv*(j+moffp)],sq[ii]); } ii += blockDim.x; } } return; } /*--------------------------------------------------------------------*/ __global__ void gpuppcaguard2xl(float2 qc[], float2 scs[], float q[], int nyp, int nx, int nxe, int nypmx, int nxvh, int kypd) { /* copy and accumulate extended periodic scalar field q in x direction into complex output fields qc, scs linear interpolation, for distributed data scs[j] = data to send to another processor nyp = number of primary (complete) gridpoints in particle partition nx = system length in x direction nxe = first dimension of input field array q, must be >= nx+1 nypmx = maximum size of particle partition, including guard cells nxvh = first dimension of output field array qc, must be >= nx/2+1 kypd = second dimension of output field array qc, must be >= nyp */ /* local data */ int j, k, nxh; float at1; float2 a; nxh = nx/2; k = blockIdx.x; /* copy interior points */ if (k < nyp) { j = threadIdx.x; while (j < nxh) { at1 = 0.0f; if (j==0) { at1 = q[nx+nxe*k]; } a.x = q[2*j+nxe*k] + at1; a.y = q[2*j+1+nxe*k]; qc[j+nxvh*k] = a; j += blockDim.x; } } /* copy exterior points */ if (k==0) { j = threadIdx.x; while (j < nxh) { at1 = 0.0f; if (j==0) { at1 = q[nx+nxe*nyp]; } a.x = q[2*j+nxe*nyp] + at1; a.y = q[2*j+1+nxe*nyp]; scs[j] = a; j += blockDim.x; } } return; } /*--------------------------------------------------------------------*/ __global__ void gpuppcaguard2yl(float2 fc[], float2 scr[], int nx, int nxvh, int kypd) { /* this subroutine adds data from guard cells from remote processors fc[k][j] = complex data for grid j,k in particle partition. output: fc scr[j] = complex input array for arriving data nx = system length in x direction nxvh = first dimension of fc, must be >= nx/2+1 kypd = maximum size of field partition, including guard cells. linear interpolation, for distributed data local data */ int j, nxh; float2 a, b; nxh = nx/2; j = threadIdx.x+blockDim.x*blockIdx.x; /* add up the guard cells from remote processors */ if (j < nxh) { a = fc[j]; b = scr[j]; a.x += b.x; a.y += b.y; fc[j] = a; } return; } /*--------------------------------------------------------------------*/ __global__ void gpuppccguard2xl(float2 fxyc[], float2 scs[], float fxy[], int nyp, int nx, int nxe, int nypmx, int nxvh, int kypd) { /* copy and replicate complex input 2d vector field fxyc in x direction into extended periodic fields fxy, scs linear interpolation, for distributed data scs[2][j] = data to send to another processor nyp = number of primary (complete) gridpoints in particle partition nx = system length in x direction nxe = second dimension of input field array fxy, must be >= nx+1 nypmx = maximum size of particle partition, including guard cells nxvh = first dimension of input field array fxyc, must be >= nx/2+1 kypd = third dimension of input field array fxyc, must be >= nyp+1 */ /* local data */ int j, k, nxh; float2 a, b; nxh = nx/2; k = blockIdx.x; /* copy interior points */ if (k < nyp) { j = threadIdx.x; while (j < nxh) { a = fxyc[j+nxvh*2*k]; b = fxyc[j+nxvh*(1+2*k)]; fxy[2*(2*j+nxe*k)] = a.x; fxy[1+2*(2*j+nxe*k)] = b.x; fxy[2*(2*j+1+nxe*k)] = a.y; fxy[1+2*(2*j+1+nxe*k)] = b.y; j += blockDim.x; } } /* copy edges of extended field */ if (blockIdx.x==0) { k = threadIdx.x; while (k < nyp) { a = fxyc[nxvh*2*k]; b = fxyc[nxvh*(1+2*k)]; fxy[2*(nx+nxe*k)] = a.x; fxy[1+2*(nx+nxe*k)] = b.x; k += blockDim.x; } /* copy exterior points */ j = threadIdx.x; while (j < nxh) { scs[j] = fxyc[j]; scs[j+nxvh] = fxyc[j+nxvh]; j += blockDim.x; } /* copy edges of extended field */ if (threadIdx.x==0) { a = fxyc[0]; b = fxyc[nxvh]; a.y = 0.0f; b.y = 0.0f; scs[nxh] = a; scs[nxh+nxvh] = b; } } return; } /*--------------------------------------------------------------------*/ __global__ void gpuppccguard2yl(float fxy[], float2 scr[], int nyp, int nx, int nxe, int nxvh, int nypmx) { /* this subroutine copies data to guard cells from remote processors fxy[k][j] = real data for grid j,k in particle partition. the grid is non-uniform and includes one extra guard cell. output: fxy scr[2][j] = complex input array for arriving data nyp = number of primary gridpoints in field partition it is assumed the nyp > 0. nx = system length in x direction nxe = second dimension of input field array fxy, must be >= nx+1 nxvh = first dimension of scr, must be >= nx/2+1 nypmx = maximum size of field partition, including guard cell. linear interpolation, for distributed data local data */ int j, nxh; float2 a, b; nxh = nx/2; j = threadIdx.x+blockDim.x*blockIdx.x; /* copy to guard cells */ if (j < nxh) { a = scr[j]; b = scr[j+nxvh]; fxy[2*(2*j+nxe*nyp)] = a.x; fxy[1+2*(2*j+nxe*nyp)] = b.x; fxy[2*(2*j+1+nxe*nyp)] = a.y; fxy[1+2*(2*j+1+nxe*nyp)] = b.y; } if (j==0) { a = scr[nxh]; b = scr[nxh+nxvh]; fxy[2*(nx+nxe*nyp)] = a.x; fxy[1+2*(nx+nxe*nyp)] = b.x; } return; } /*--------------------------------------------------------------------*/ __global__ void gpupppfnd2l(float ppart[], int kpic[], int ncl[], int ihole[], int noff, int nyp, int idimp, int nppmx, int nx, int ny, int mx, int my, int mx1, int myp1, int ntmax, int *irc) { /* this subroutine performs first step of a particle sort by x,y grid in tiles of mx, my, where one finds the particles leaving tile and stores their number, location, and destination in ncl and ihole. linear interpolation, with periodic boundary conditions for distributed data, with 1d domain decomposition in y. tiles are assumed to be arranged in 2D linear memory input: all except ncl, ihole, irc output: ncl, ihole, irc ppart[k][0][n] = position x of particle n in tile k ppart[k][1][n] = position y of particle n in tile k kpic[k] = number of particles in tile k ncl[k][i] = number of particles going to destination i, tile k ihole[k][:][0] = location of hole in array left by departing particle ihole[k][:][1] = destination of particle leaving hole ihole[k][0][0] = ih, number of holes left (error, if negative) noff = lowermost global gridpoint in particle partition. nyp = number of primary (complete) gridpoints in particle partition idimp = size of phase space = 4 nppmx = maximum number of particles in tile nx/ny = system length in x/y direction mx/my = number of grids in sorting cell in x/y mx1 = (system length in x direction - 1)/mx + 1 myp1 = (partition length in y direction - 1)/my + 1 ntmax = size of hole array for particles leaving tiles irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int mxyp1, noffp, moffp, nppp, j, k, ih, ist, nn, mm, nths; float anx, any, edgelx, edgely, edgerx, edgery, dx, dy; /* The sizes of the shared memory arrays are as follows: */ /* int sncl[8], sih[blockDim.x], nh[1]; */ int *sncl, *sih, *nh; extern __shared__ int shm[]; sncl = (int *)&shm[0]; sih = (int *)&shm[8]; nh = (int *)&shm[8+blockDim.x]; mxyp1 = mx1*myp1; anx = (float) nx; any = (float) ny; /* k = tile number */ k = blockIdx.x + gridDim.x*blockIdx.y; /* find and count particles leaving tiles and determine destination */ /* update ppart, ihole, ncl */ /* loop over tiles */ if (k < mxyp1) { noffp = k/mx1; moffp = my*noffp; noffp = mx*(k - mx1*noffp); nppp = kpic[k]; nn = nx - noffp; nn = mx < nn ? mx : nn; mm = nyp - moffp; mm = my < mm ? my : mm; edgelx = noffp; edgerx = noffp + nn; edgely = noff + moffp; edgery = noff + moffp + mm; /* clear counters */ j = threadIdx.x; while (j < 8) { sncl[j] = 0; j += blockDim.x; } if (threadIdx.x==0) { nh[0] = 0; } /* synchronize threads */ __syncthreads(); /* loop over particles in tile */ mm = (nppp - 1)/(int) blockDim.x + 1; noffp = 0; for (nn = 0; nn < mm; nn++) { j = threadIdx.x + blockDim.x*nn; sih[threadIdx.x] = 0; if (j < nppp) { dx = ppart[j+nppmx*(idimp*k)]; dy = ppart[j+nppmx*(1+idimp*k)]; /* find particles going out of bounds */ ist = 0; /* count how many particles are going in each direction in ncl */ /* save their address and destination in ihole */ /* use periodic boundary conditions and check for roundoff error */ /* ist = direction particle is going */ if (dx >= edgerx) { if (dx >= anx) ppart[j+nppmx*(idimp*k)] = dx - anx; ist = 2; } else if (dx < edgelx) { if (dx < 0.0f) { dx += anx; if (dx < anx) ist = 1; else dx = 0.0f; ppart[j+nppmx*(idimp*k)] = dx; } else { ist = 1; } } if (dy >= edgery) { if (dy >= any) ppart[j+nppmx*(1+idimp*k)] = dy - any; ist += 6; } else if (dy < edgely) { if (dy < 0.0f) { dy += any; if (dy < any) ist += 3; else dy = 0.0f; ppart[j+nppmx*(1+idimp*k)] = dy; } else { ist += 3; } } /* using prefix scan for ih to keep holes ordered */ if (ist > 0) { atomicAdd(&sncl[ist-1],1); sih[threadIdx.x] = 1; } } /* synchronize threads */ __syncthreads(); nths = nppp - blockDim.x*nn; if (nths > blockDim.x) nths = blockDim.x; /* perform local prefix reduction */ liscan2(sih,nths); if (j < nppp) { ih = sih[threadIdx.x]; moffp = 0; if (threadIdx.x > 0) moffp = sih[threadIdx.x-1]; /* this thread has a hole present */ if (ih > moffp) { ih += noffp; if (ih <= ntmax) { ihole[2*(ih+(ntmax+1)*k)] = j + 1; ihole[1+2*(ih+(ntmax+1)*k)] = ist; } else { nh[0] = 1; } } } /* update number of holes in this iteration */ if (nths > 0) noffp += sih[nths-1]; /* synchronize threads */ __syncthreads(); } /* write out counters */ j = threadIdx.x; while (j < 8) { ncl[j+8*k] = sncl[j]; j += blockDim.x; } /* set error and end of file flag */ if (threadIdx.x==0) { /* ihole overflow */ ih = noffp; if (nh[0] > 0) { *irc = ih; ih = -ih; } ihole[2*(ntmax+1)*k] = ih; } } return; } /*--------------------------------------------------------------------*/ __global__ void gpupppmov2l(float ppart[], float ppbuff[], int ncl[], int ihole[], int idimp, int nppmx, int mx1, int myp1, int npbmx, int ntmax, int *irc) { /* this subroutine performs second step of a particle sort by x,y grid in tiles of mx, my, where prefix scan of ncl is performed and departing particles are buffered in ppbuff in direction order. linear interpolation, with periodic boundary conditions for distributed data, with 1d domain decomposition in y. tiles are assumed to be arranged in 2D linear memory input: all except ppbuff, irc output: ppbuff, ncl, irc ppart[k][i][n] = i co-ordinate of particle n in tile k ppbuff[k][i][n] = i co-ordinate of particle n in tile k ncl[k][i] = number of particles going to destination i, tile k ihole[k][:][0] = location of hole in array left by departing particle ihole[k][:][1] = direction destination of particle leaving hole all for tile k ihole[k][0][0] = ih, number of holes left (error, if negative) idimp = size of phase space = 4 nppmx = maximum number of particles in tile mx1 = (system length in x direction - 1)/mx + 1 myp1 = (partition length in y direction - 1)/my + 1 npbmx = size of buffer array ppbuff ntmax = size of hole array for particles leaving tiles irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int mxyp1, i, j, k, ii, nh, ist, j1, ierr; /* The sizes of the shared memory arrays are as follows: */ /* int sncl[8], ip[1]; */ /* blockDim.x should be >= 8 */ int *sncl, *ip; extern __shared__ int shm[]; sncl = (int *)&shm[0]; ip = (int *)&shm[8]; mxyp1 = mx1*myp1; ierr = 0; /* k = tile number */ k = blockIdx.x + gridDim.x*blockIdx.y; j = threadIdx.x; /* buffer particles that are leaving tile: update ppbuff, ncl */ /* loop over tiles */ if (k < mxyp1) { /* find address offset for ordered ppbuff array */ if (j < 8) { ist = ncl[j+8*k]; sncl[j] = ist; } if (threadIdx.x==0) ip[0] = 0; /* synchronize threads */ __syncthreads(); /* perform local prefix reduction */ liscan2(sncl,8); if (j < 8) sncl[j] -= ist; /* synchronize threads */ __syncthreads(); nh = ihole[2*(ntmax+1)*k]; /* loop over particles leaving tile */ while (j < nh) { /* buffer particles that are leaving tile, in direction order */ j1 = ihole[2*(j+1+(ntmax+1)*k)] - 1; ist = ihole[1+2*(j+1+(ntmax+1)*k)]; ii = atomicAdd(&sncl[ist-1],1); if (ii < npbmx) { for (i = 0; i < idimp; i++) { ppbuff[ii+npbmx*(i+idimp*k)] = ppart[j1+nppmx*(i+idimp*k)]; } } else { ip[0] = 1; } j += blockDim.x; } /* synchronize threads */ __syncthreads(); /* write out counters */ j = threadIdx.x; if (j < 8) { ncl[j+8*k] = sncl[j]; } /* set error */ if (threadIdx.x==0) { if (ip[0] > 0) ierr = ierr > sncl[7] ? ierr : sncl[7]; } } /* ppbuff overflow */ if (ierr > 0) *irc = ierr; return; } /*--------------------------------------------------------------------*/ __global__ void nciscan2(int ncl[], int ncll[], int nclr[], int nscr[], int mx1, int myp1) { /* calculate number number offsets for particles leaving processor by performing prefix scan (running sum) for each block. the last value of each block is written to nscr to add to each block later. ncl[k][i] = number of particles going to destination i, tile k ncll = number offset being sent to lower processor nclr = number offset being sent to upper processor nscr = scratch integer array, of size 2*((mx1-1)/blockDim.x+1) mx1 = (system length in x direction - 1)/mx + 1 myp1 = (partition length in y direction - 1)/my + 1 local data */ int l, koff, ii, jj, kk, nths; /* The size of the shared memory array are as follows: */ /* int isdata[2*blockDim.x]; */ int *isdata; extern __shared__ int shm[]; isdata = (int *)&shm[0]; l = threadIdx.x; koff = blockDim.x*blockIdx.x; kk = mx1*(myp1 - 1) + koff; nths = mx1 - koff; if (nths > blockDim.x) nths = blockDim.x; if ((l+koff) < mx1) { ii = ncl[4+8*(l+koff)] - ncl[1+8*(l+koff)]; isdata[l] = ii; jj = ncl[7+8*(l+kk)] - ncl[4+8*(l+kk)]; isdata[l+blockDim.x] = jj; } /* synchronize threads */ __syncthreads(); /* perform local prefix reductions */ liscan2(isdata,nths); liscan2(&isdata[blockDim.x],nths); if ((l+koff) < mx1) { ncll[3*(l+koff)] = ii; ncll[3*(l+koff)+1] = isdata[l] - ii; nclr[3*(l+koff)] = jj; nclr[3*(l+koff)+1] = isdata[l+blockDim.x] - jj; } if (l==0) { ii = 0; jj = 0; if (nths > 0) { ii = isdata[nths-1]; jj = isdata[nths+blockDim.x-1]; } nscr[blockIdx.x] = ii; nscr[blockIdx.x+gridDim.x] = jj; } return; } /*--------------------------------------------------------------------*/ __global__ void gpupppbuf2l(float ppbuff[], float sbufl[], float sbufr[], int ncl[], int ncll[], int nclr[], int nscr[], int idimp, int mx1, int myp1, int npbmx, int nbmax, int *irc) { /* this subroutine performs third step of a particle sort by x,y grid in tiles of mx, my, where particles leaving the processor are buffered in sbufl and sbufr, and particle number offsets are stored in ncll and nclr. gpupppbuf2l and nciscan2 should use the same blocksize. linear interpolation, with periodic boundary conditions for distributed data, with 1d domain decomposition in y. tiles are assumed to be arranged in 2D linear memory input: all except sbufl, sbufr, ncll, nclr, irc output: sbufl, sbufr, ncll, nclr, irc ppbuff[k][i][n] = i co-ordinate of particle n in tile k sbufl = buffer for particles being sent to lower processor sbufr = buffer for particles being sent to upper processor kpic[k] = number of particles in tile k ncl[k][i] = number of particles going to destination i, tile k ncll = number offset being sent to lower processor nclr = number offset being sent to upper processor nscr = scratch integer array, of size 2*((mx1-1)/blockDim.x+1) idimp = size of phase space = 4 mx1 = (system length in x direction - 1)/mx + 1 myp1 = (partition length in y direction - 1)/my + 1 npbmx = size of buffer array ppbuff nbmax = size of buffers for passing particles between processors irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int i, j, k, ii, jj, nl, nr, nn, mm, nbl, kk, ll, im; k = blockIdx.x; /* buffer particles and their number leaving the node: */ /* update sbufl, sbufr, ncll, nclr */ nbl = (mx1 - 1)/blockDim.x + 1; nl = 0; nr = 0; nn = 0; mm = 0; kk = mx1*(myp1 - 1); /* loop over row of tiles */ if (k < mx1) { j = k/blockDim.x + 1; /* find how many particles must be buffered */ for (i = 1; i < nbl; i++) { nl += nscr[i-1]; nr += nscr[i+nbl-1]; /* save offsets */ if (i==(j-1)) { nn = nl; mm = nr; } } nl += nscr[nbl-1]; nr += nscr[2*nbl-1]; ii = ncll[3*k]; nn += ncll[3*k+1]; im = nclr[3*k]; mm += nclr[3*k+1]; /* synchronize threads */ __syncthreads(); ll = ncl[1+8*k]; jj = nl - nn; jj = ii < jj ? ii : jj; j = threadIdx.x; while (j < jj) { for (i = 0; i < idimp; i++) { sbufl[j+nn+nl*i] = ppbuff[j+ll+npbmx*(i+idimp*k)]; } j += blockDim.x; } ll = nn - ll; if (threadIdx.x < 3) { ncll[threadIdx.x+3*k] = ncl[threadIdx.x+2+8*k] + ll; } nn += ii; ii = im; ll = ncl[4+8*(k+kk)]; jj = nr - mm; jj = ii < jj ? ii : jj; j = threadIdx.x; while (j < jj) { for (i = 0; i < idimp; i++) { sbufr[j+mm+nr*i] = ppbuff[j+ll+npbmx*(i+idimp*(k+kk))]; } j += blockDim.x; } ll = mm - ll; if (threadIdx.x < 3) { nclr[threadIdx.x+3*k] = ncl[threadIdx.x+5+8*(k+kk)] + ll; } mm += ii; } /* sbufl or sbufr overflow */ ii = nn > mm ? nn : mm; if (ii > nbmax) *irc = ii; return; } /*--------------------------------------------------------------------*/ __global__ void gpupppord2l(float ppart[], float ppbuff[], float rbufl[], float rbufr[], int kpic[], int ncl[], int ihole[], int mcll[], int mclr[], int idimp, int nppmx, int mx1, int myp1, int npbmx, int ntmax, int nbmax, int *irc) { /* this subroutine performs third step of a particle sort by x,y grid in tiles of mx, my, where incoming particles from other tiles are copied into ppart from ppbuff, rbufl, and rbufr linear interpolation, with periodic boundary conditions for distributed data, with 1d domain decomposition in y. tiles are assumed to be arranged in 2D linear memory input: all except irc output: ppart, kpic, irc ppart[k][i][n] = i co-ordinate of particle n in tile k ppbuff[k][i][n] = i co-ordinate of particle n in tile k rbufl = buffer for particles being received from lower processor rbufr = buffer for particles being received from upper processor kpic[k] = number of particles in tile k ncl[k][i] = number of particles going to destination i, tile k ihole[k][:][0] = location of hole in array left by departing particle ihole[k][:][1] = direction destination of particle leaving hole all for tile k ihole[k][0][0] = ih, number of holes left (error, if negative) mcll = number offset being received from lower processor mclr = number offset being received from upper processor idimp = size of phase space = 4 nppmx = maximum number of particles in tile mx1 = (system length in x direction - 1)/mx + 1 myp1 = (partition length in y direction - 1)/my + 1 npbmx = size of buffer array ppbuff ntmax = size of hole array for particles leaving tiles nbmax = size of buffers for passing particles between processors irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int mxyp1, nppp, ncoff, noff, moff, i, j, k, ii, jj, kx, ky, ni, nh; int nn, mm, ll, ip, j1, j2, kxl, kxr, kk, kl, kr, nr, mr; int nths; /* The sizes of the shared memory arrays are as follows: */ /* int ks[8], sip[8], sj[blockDim.x], sj1[1], ist[1]; */ int *ks, *sip, *sj, *sj1, *ist; extern __shared__ int shm[]; ks = (int *)&shm[0]; sip = (int *)&shm[8]; sj = (int *)&shm[16]; sj1 = (int *)&shm[16+blockDim.x]; ist = (int *)&shm[17+blockDim.x]; mxyp1 = mx1*myp1; noff = 0; moff = 0; /* k = tile number */ k = blockIdx.x + gridDim.x*blockIdx.y; /* copy incoming particles from buffer into ppart: update ppart, kpic */ /* loop over tiles */ if (k < mxyp1) { nppp = kpic[k]; ky = k/mx1; /* loop over tiles in y */ kk = ky*mx1; /* find tile above */ kl = (ky - 1)*mx1; /* find tile below */ kr = (ky + 1)*mx1; /* loop over tiles in x, assume periodic boundary conditions */ kx = k - ky*mx1; kxl = kx - 1; if (kxl < 0) kxl += mx1; kxr = kx + 1; if (kxr >= mx1) kxr -= mx1; /* find tile number for different directions */ if (threadIdx.x==0) { ks[0] = kxr + kk; ks[1] = kxl + kk; ks[2] = kx + kr; ks[3] = kxr + kr; ks[4] = kxl + kr; ks[5] = kx + kl; ks[6] = kxr + kl; ks[7] = kxl + kl; sj1[0] = 0; ist[0] = 0; } /* synchronize threads */ __syncthreads(); /* find number of incoming particles */ kk = 0; if (ky==0) { nr = mcll[3*mx1-1]; if (kx > 0) noff = mcll[3*kx-1]; } if (ky==(myp1-1)) { mr = mclr[3*mx1-1]; if (kx > 0) moff = mclr[3*kx-1]; } ncoff = 0; ip = 0; ii = threadIdx.x; if (ii < 8) { kk = ks[ii]; /* ip = number of particles coming from direction ii */ if (kk < 0) { if (ii > 5) noff = mcll[ii-6+3*(kk+mx1)]; ip = mcll[ii-5+3*(kk+mx1)] - noff; kk = noff; } else if (kk >= mxyp1) { if (ii > 2) moff = mclr[ii-3+3*(kk-mxyp1)]; ip = mclr[ii-2+3*(kk-mxyp1)] - moff; kk = moff; } else { if (ii > 0) ncoff = ncl[ii-1+8*kk]; ip = ncl[ii+8*kk] - ncoff; kk = ncoff + idimp*npbmx*kk; } sip[ii] = ip; } /* synchronize threads */ __syncthreads(); /* perform local prefix reduction */ liscan2(sip,8); ni = sip[7]; /* loop over directions */ nh = ihole[2*(ntmax+1)*k]; j1 = 0; mm = (ni - 1)/(int) blockDim.x + 1; for (nn = 0; nn < mm; nn++) { j = threadIdx.x + blockDim.x*nn; sj[threadIdx.x] = 0; if (threadIdx.x==0) sj[0] = sj1[0]; /* synchronize threads */ __syncthreads(); /* calculate offset for reading from particle buffer */ if (ii < 8) { /* mark next location where direction ii changes */ jj = sip[ii] - blockDim.x*nn; if ((jj >= 0) && (jj < blockDim.x)) { if (ip > 0) sj[jj] -= kk + ip; } } /* synchronize threads */ __syncthreads(); /* calculate offset for reading from particle buffer */ if (ii < 8) { /* mark location where direction ii starts */ jj -= ip; if ((jj >= 0) && (jj < blockDim.x)) { if (ip > 0) sj[jj] += kk; } } nths = ni - blockDim.x*nn; if (nths > blockDim.x) nths = blockDim.x; /* synchronize threads */ __syncthreads(); /* perform local prefix reduction */ liscan2(sj,nths); /* save last value for next time */ if (threadIdx.x==0) { jj = 0; if (nths > 0) jj = sj[nths-1]; sj1[0] = jj; } if (j < ni) { /* insert incoming particles into holes */ if (j < nh) { j1 = ihole[2*(j+1+(ntmax+1)*k)] - 1; } /* place overflow at end of array */ else { j1 = nppp + (j - nh); } if (j1 < nppmx) { jj = sj[threadIdx.x]; if ((ky==0) && (j>=sip[4]) && (j<sip[7])) { for (i = 0; i < idimp; i++) { ppart[j1+nppmx*(i+idimp*k)] = rbufl[j+jj+nr*i]; } } else if ((ky==(myp1-1)) && (j>=sip[1]) && (j<sip[4])) { for (i = 0; i < idimp; i++) { ppart[j1+nppmx*(i+idimp*k)] = rbufr[j+jj+mr*i]; } } else { for (i = 0; i < idimp; i++) { ppart[j1+nppmx*(i+idimp*k)] = ppbuff[j+jj+npbmx*i]; } } } else { ist[0] = 1; } } /* synchronize threads */ __syncthreads(); } /* update particle number if all holes have been filled */ jj = ni - nh; if (jj > 0) nppp += jj; /* fill up remaining holes in particle array with particles from end */ ip = nh - ni; if (ip > 0) { mm = (ip - 1)/(int) blockDim.x + 1; kk = 0; ll = 0; /* loop over holes */ for (nn = 0; nn < mm; nn++) { j = threadIdx.x + blockDim.x*nn; /* j1 = locations of particles to fill holes, in decreasing order */ j1 = 0; if (j < ip) { j1 = nppp - j - 1; } /* j2 = locations of holes at the end, in decreasing order */ j2 = 0; jj = nh - ll - threadIdx.x; if (jj > 0) { j2 = ihole[2*(jj+(ntmax+1)*k)] - 1; } /* holes with locations greater than nppp-ip do not need to be filled */ /* identify such holes */ sj[threadIdx.x] = 1; /* synchronize threads */ __syncthreads(); /* omit particles at end that are holes */ ii = nppp - (j2 + blockDim.x*nn) - 1; if ((ii >= 0) && (ii < blockDim.x)) sj[ii] = 0; nths = ip - blockDim.x*nn; if (nths > blockDim.x) nths = blockDim.x; /* synchronize threads */ __syncthreads(); /* perform local prefix reduction */ liscan2(sj,nths); /* ii = number particles at end to be moved */ ii = 0; if (nths > 0) ii = sj[nths-1]; /* identify which particles at end to be moved */ if (ii < nths) { ncoff = 0; if (j < ip) { if (threadIdx.x > 0) ncoff = sj[threadIdx.x-1]; jj = sj[threadIdx.x]; } /* synchronize threads */ __syncthreads(); if (j < ip) { if (jj > ncoff) { sj[jj-1] = j1; } } /* synchronize threads */ __syncthreads(); } /* j2 = locations of holes to be filled in increasing order */ j2 = 0; if (j < ip) { j1 = nppp - j - 1; jj = threadIdx.x + ni + kk + 1; if (jj <= nh) j2 = ihole[2*(jj+(ntmax+1)*k)] - 1; } /* move particles from end into remaining holes */ if (j < (ii+blockDim.x*nn)) { if (ii < nths) j1 = sj[threadIdx.x]; for (i = 0; i < idimp; i++) { ppart[j2+nppmx*(i+idimp*k)] = ppart[j1+nppmx*(i+idimp*k)]; } } /* accumulate number of holes filled */ kk += ii; /* accumulate number of holes skipped over */ ii = nths - ii; ll += ii; } /* update number of particles */ nppp -= ip; } /* set error and update particle */ if (threadIdx.x==0) { /* ppart overflow */ if (ist[0] > 0) *irc = nppp; kpic[k] = nppp; } } return; } /*--------------------------------------------------------------------*/ __global__ void gpuppois22t(float2 qt[], float2 fxyt[], float2 ffct[], float *we, int nx, int ny, int kstrt, int nyv, int kxp1, int nyhd) { /* this subroutine solves 2d poisson's equation in fourier space for force/charge (or convolution of electric field over particle shape) with periodic boundary conditions, for distributed data. vector length is second dimension. input: qt,ffct,nx,ny,nyv,kxp1,nyhd, output: fxyt,we approximate flop count is: 33*nxc*nyc + 15*(nxc + nyc) where nxc = (nx/2-1)/nvp, nyc = ny/2 - 1, and nvp = number of procs the equation used is: fx[ky][kx] = -sqrt(-1)*kx*g[ky][kx]*s[ky][kx]*q[ky][kx], fy[ky][kx] = -sqrt(-1)*ky*g[ky][kx]*s[ky][kx]*q[ky][kx], where kx = 2pi*j/nx, ky = 2pi*k/ny, and j,k = fourier mode numbers, g[ky][kx] = (affp/(kx**2+ky**2))*s[ky][kx], s[ky][kx] = exp(-((kx*ax)**2+(ky*ay)**2)/2), except for fx(kx=pi) = fy(kx=pi) = fx(ky=pi) = fy(ky=pi) = 0, and fx(kx=0,ky=0) = fy(kx=0,ky=0) = 0. qt[j][k] = complex charge density for fourier mode (jj,k) fxyt[j][0][k] = x component of complex force/charge, fxyt[j][1][k] = y component of complex force/charge, for fourier mode (jj,k), where jj = j + kxp1*(kstrt - 1) kxp1 = number of data values per block for unpacked field data kstrt = starting data block number aimag(ffct[j][k]) = finite-size particle shape factor s real(ffct[j][k])) = potential green's function g for fourier mode (jj,k), where jj = j + kxp1*(kstrt - 1) electric field energy is also calculated, using we = nx*ny*sum((affp/(kx**2+ky**2))*|q[ky][kx]*s[ky][kx]|**2) where affp = nx*ny/np, where np=number of particles nx/ny = system length in x/y direction nyv = first dimension of field arrays, must be >= ny nyhd = first dimension of form factor array, must be >= nyh local data */ int nxh, nyh, ks, joff, kxps, j, jj, jk, k, j0, j1, k1, jk2; float dnx, dny, dkx, at1, at2, at3, at4; float2 zero, zt1, zt2, zt3; /* The size of the shared memory array is as follows: */ /* float ss[blockDim.x]; */ extern __shared__ float ss[]; double wp; nxh = nx/2; nyh = 1 > ny/2 ? 1 : ny/2; ks = kstrt - 1; joff = kxp1*ks; j1 = nxh + 1; kxps = j1 - joff; kxps = 0 > kxps ? 0 : kxps; kxps = kxp1 < kxps ? kxp1 : kxps; dnx = 6.28318530717959f/(float) nx; dny = 6.28318530717959f/(float) ny; zero.x = 0.0f; zero.y = 0.0f; /* calculate force/charge and sum field energy */ wp = 0.0; if (kstrt <= j1) { /* mode numbers 0 < kx < nx/2 and 0 < ky < ny/2 */ /* for (j = 0; j < kxps; j++) { */ j = blockIdx.x; j0 = j + joff; dkx = dnx*(float) j0; jj = nyhd*j; jk = nyv*j; jk2 = 2*jk; if ((j0 > 0) && (j0 < nxh)) { /* for (k = 1; k < nyh; k++) { */ k = threadIdx.x; while (k < nyh) { if (k > 0) { k1 = ny - k; zt1 = ffct[k+jj]; at1 = zt1.x*zt1.y; at2 = at1*dkx; at3 = at1*dny*(float) k; zt1 = qt[k+jk]; at4 = zt1.x; zt1.x = zt1.y; zt1.y = -at4; zt2 = qt[k1+jk]; at4 = zt2.x; zt2.x = zt2.y; zt2.y = -at4; zt3.x = at2*zt1.x; zt3.y = at2*zt1.y; fxyt[k+jk2] = zt3; zt3.x = at2*zt2.x; zt3.y = at2*zt2.y; fxyt[k1+jk2] = zt3; zt3.x = at3*zt1.x; zt3.y = at3*zt1.y; fxyt[k+nyv+jk2] = zt3; zt3.x = -at3*zt2.x; zt3.y = -at3*zt2.y; fxyt[k1+nyv+jk2] = zt3; wp += (double) (at1*(zt1.x*zt1.x + zt1.y*zt1.y + zt2.x*zt2.x + zt2.y*zt2.y)); } k += blockDim.x; } } /* mode numbers ky = 0, ny/2 */ if (blockIdx.x==0) { k1 = nyh; /* for (j = 1; j < kxps; j++) { */ j = threadIdx.x; while (j < kxps) { j0 = j + joff; dkx = dnx*(float) j0; jj = nyhd*j; jk = nyv*j; jk2 = 2*jk; if ((j0 > 0) && (j0 < nxh)) { zt1 = ffct[jj]; at1 = zt1.x*zt1.y; at2 = dkx*at1; zt1 = qt[jk]; at4 = zt1.x; zt3.x = at2*zt1.y; zt3.y = -at2*at4; fxyt[jk2] = zt3; fxyt[k1+jk2] = zero; fxyt[nyv+jk2] = zero; fxyt[k1+nyv+jk2] = zero; wp += (double) (at1*(zt1.x*zt1.x + zt1.y*zt1.y)); } j += blockDim.x; } /* mode numbers kx = 0 */ if (ks==0) { /* for (k = 1; k < nyh; k++) { */ k = threadIdx.x; while (k < nyh) { if (k > 0) { k1 = ny - k; zt1 = ffct[k]; at1 = zt1.x*zt1.y; at3 = at1*dny*(float) k; zt1 = qt[k]; at4 = zt1.x; zt3.x = at3*zt1.y; zt3.y = -at3*at4; fxyt[k] = zero; fxyt[k1] = zero; fxyt[k+nyv] = zt3; zt3.y = -zt3.y; fxyt[k1+nyv] = zt3; wp += (double) (at1*(zt1.x*zt1.x + zt1.y*zt1.y)); } k += blockDim.x; } if (threadIdx.x==0) { k1 = nyh; fxyt[0] = zero; fxyt[k1] = zero; fxyt[nyv] = zero; fxyt[k1+nyv] = zero; } } /* mode numbers kx = nx/2 */ if (ks==(nxh/kxp1)) { jk = 2*nyv*(kxps-1); /* for (k = 0; k < ny; k++) { */ k = threadIdx.x; while (k < ny) { fxyt[k+jk] = zero; fxyt[k+nyv+jk] = zero; k += blockDim.x; } } } } j = blockIdx.x; if (j < kxps) { /* sum potential energies for each x co-ordinate */ ss[threadIdx.x] = (float) wp; /* synchronize threads */ __syncthreads(); lsum2(ss,blockDim.x); /* normalize potential energy for each x co-ordinate */ if (threadIdx.x==0) we[j] = ss[0]*((float) nx)*((float) ny); } return; } /*--------------------------------------------------------------------*/ __global__ void gpufft2rcxs(float2 f[], int isign, int mixup[], float2 sct[], int indx, int indy, int nyi, int nyp, int nxhd, int nyd, int nxhyd, int nxyhd, int nsize) { /* this subroutine performs the x part of a two dimensional real to complex fast fourier transform and its inverse, for a subset of y, using complex arithmetic. for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny indx/indy = exponent which determines length in x/y direction, where nx=2**indx, ny=2**indy if isign = -1, an inverse fourier transform in x is performed f[m][n] = (1/nx*ny)*sum(f[k][j]*exp(-sqrt(-1)*2pi*n*j/nx)) if isign = 1, a forward fourier transform in x is performed f[k][j] = sum(f[m][n]*exp(sqrt(-1)*2pi*n*j/nx)) mixup = array of bit reversed addresses sct = sine/cosine table nyi = initial y index used nyp = number of y indices used nxhd = first dimension of f >= nx/2+1 nyd = second dimension of f >= ny nxhyd = maximum of (nx/2,ny) nxyhd = maximum of (nx,ny)/2 nsize = amount of scratch complex memory used fourier coefficients are stored as follows: f[k][j].x, f[k][j].y = real, imaginary part of mode j,k, where 0 <= j < nx/2+1 and 0 <= k < ny written by viktor k. decyk, ucla local data */ int indx1, indx1y, nx, nxh, nxhh, ny, nxy, nxhy, nyt; int nrx, i, j, k, l, j1, j2, k1, k2, ns, ns2, km, kmr, jj, kk; int n, nn, in, nt, nh; float ani, at1, at2; float2 t1, t2, t3; /* The size of the shared memory array is as follows: */ /* float2 s[nsize]; */ extern __shared__ float2 s[]; indx1 = indx - 1; indx1y = indx1 > indy ? indx1 : indy; nx = 1L<<indx; nxh = nx/2; nxhh = nx/4; ny = 1L<<indy; nxy = nx > ny ? nx : ny; nxhy = 1L<<indx1y; nyt = nyi + nyp - 1; /* calculate extent of shared memory usage: */ /* nn = size of shared memory in x */ nn = nxh; in = 0; while (nn > nsize) { nn = nn/2; in += 1; } /* nt = number of iterations in x */ nt = 1L<<in; in = indx1 - in; nh = nn/2; /* inverse fourier transform */ if (isign < 0) { /* bit-reverse array elements in x */ nrx = nxhy/nxh; /* for (k = nyi-1; k < nyt; k++) { */ k = blockIdx.x + nyi - 1; if (k < nyt) { jj = nxhd*k; /* for (j = 0; j < nxh; j++) { */ j = threadIdx.x; while (j < nxh) { j1 = (mixup[j] - 1)/nrx; if (j < j1) { t1 = f[j1+jj]; f[j1+jj] = f[j+jj]; f[j+jj] = t1; } j += blockDim.x; } /* synchronize threads */ __syncthreads(); } /* copy data to local memory */ nrx = nxy/nxh; /* for (i = nyi-1; i < nyt; i++) { */ i = blockIdx.x + nyi - 1; if (i < nyt) { jj = nxhd*i; for (n = 0; n < nt; n++) { /* for (kk = 0; kk < nn; kk++) { */ kk = threadIdx.x; while (kk < nn) { s[kk] = f[kk+nn*n+jj]; kk += blockDim.x; } /* synchronize threads */ __syncthreads(); /* transform using local data in x */ ns = 1; for (l = 0; l < in; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; /* for (kk = 0; kk < nh; kk++) { */ kk = threadIdx.x; while (kk < nh) { k = kk/ns; j = kk - ns*k; k1 = ns2*k; k2 = k1 + ns; j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; t2 = s[j2]; at1 = t1.x*t2.x - t1.y*t2.y; at2 = t1.x*t2.y + t1.y*t2.x; t2 = s[j1]; t3.x = t2.x - at1; t3.y = t2.y - at2; s[j2] = t3; t3.x = t2.x + at1; t3.y = t2.y + at2; s[j1] = t3; kk += blockDim.x; } ns = ns2; /* synchronize threads */ __syncthreads(); } /* copy data to global memory */ /* for (kk = 0; kk < nn; kk++) { */ kk = threadIdx.x; while (kk < nn) { f[kk+nn*n+jj] = s[kk]; kk += blockDim.x; } /* synchronize threads */ __syncthreads(); } /* transform using global data in x */ ns = 1L<<in; for (l = in; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; /* for (kk = 0; kk < nxhh; kk++) { */ kk = threadIdx.x; while (kk < nxhh) { k = kk/ns; j = kk - ns*k; k1 = ns2*k; k2 = k1 + ns; j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; t2 = f[j2+jj]; at1 = t1.x*t2.x - t1.y*t2.y; at2 = t1.x*t2.y + t1.y*t2.x; t2 = f[j1+jj]; t3.x = t2.x - at1; t3.y = t2.y - at2; f[j2+jj] = t3; t3.x = t2.x + at1; t3.y = t2.y + at2; f[j1+jj] = t3; kk += blockDim.x; } ns = ns2; /* synchronize threads */ __syncthreads(); } } /* unscramble coefficients and normalize */ kmr = nxy/nx; ani = 0.5f/(((float) nx)*((float) ny)); /* for (k = nyi-1; k < nyt; k++) */ k = blockIdx.x + nyi - 1; if (k < nyt) { jj = nxhd*k; /* for (j = 1; j < nxhh; j++) { */ j = threadIdx.x; while (j < nxhh) { if (j > 0) { t3 = sct[kmr*j]; at1 = t3.y; at2 = -t3.x; t2 = f[nxh-j+jj]; t2.y = -t2.y; t3 = f[j+jj]; t1.x = t3.x + t2.x; t1.y = t3.y + t2.y; t3.x -= t2.x; t3.y -= t2.y; t2.x = t3.x*at1 - t3.y*at2; t2.y = t3.x*at2 + t3.y*at1; t3.x = ani*(t1.x + t2.x); t3.y = ani*(t1.y + t2.y); f[j+jj] = t3; t3.x = ani*(t1.x - t2.x); t3.y = ani*(t2.y - t1.y); f[nxh-j+jj] = t3; } j += blockDim.x; } if (threadIdx.x==0) { ani = 2.0f*ani; t3 = f[nxhh+jj]; t3.x = ani*t3.x; t3.y = -ani*t3.y; f[nxhh+jj] = t3; t3 = f[jj]; at1 = t3.x; at2 = t3.y; t3.x = ani*(at1 - at2); t3.y = 0.0f; f[nxh+jj] = t3; t3.x = ani*(at1 + at2); f[jj] = t3; } /* synchronize threads */ __syncthreads(); } } /* forward fourier transform */ if (isign > 0) { /* scramble coefficients */ kmr = nxy/nx; /* for (k = nyi-1; k < nyt; k++) { */ k = blockIdx.x + nyi - 1; if (k < nyt) { jj = nxhd*k; /* for (j = 1; j < nxhh; j++) { */ j = threadIdx.x; while (j < nxhh) { if (j > 0) { t3 = sct[kmr*j]; at1 = t3.y; at2 = t3.x; t2 = f[nxh-j+jj]; t2.y = -t2.y; t3 = f[j+jj]; t1.x = t3.x + t2.x; t1.y = t3.y + t2.y; t3.x -= t2.x; t3.y -= t2.y; t2.x = t3.x*at1 - t3.y*at2; t2.y = t3.x*at2 + t3.y*at1; t3.x = t1.x + t2.x; t3.y = t1.y + t2.y; f[j+jj] = t3; t3.x = t1.x - t2.x; t3.y = t2.y - t1.y; f[nxh-j+jj] = t3; } j += blockDim.x; } if (threadIdx.x==0) { t3 = f[nxhh+jj]; t3.x = 2.0f*t3.x; t3.y = -2.0f*t3.y; f[nxhh+jj] = t3; t3 = f[jj]; at1 = t3.x; t3 = f[nxh+jj]; at2 = t3.x; t3.x = at1 + at2; t3.y = at1 - at2; f[jj] = t3; } /* synchronize threads */ __syncthreads(); } /* bit-reverse array elements in x */ nrx = nxhy/nxh; /* for (k = nyi-1; k < nyt; k++) { */ k = blockIdx.x + nyi - 1; if (k < nyt) { jj = nxhd*k; /* for (j = 0; j < nxh; j++) { */ j = threadIdx.x; while (j < nxh) { j1 = (mixup[j] - 1)/nrx; if (j < j1) { t1 = f[j1+jj]; f[j1+jj] = f[j+jj]; f[j+jj] = t1; } j += blockDim.x; } /* synchronize threads */ __syncthreads(); } /* copy data to local memory */ nrx = nxy/nxh; /* for (i = nyi-1; i < nyt; i++) { */ i = blockIdx.x + nyi - 1; if (i < nyt) { jj = nxhd*i; for (n = 0; n < nt; n++) { /* for (kk = 0; kk < nn; kk++) { */ kk = threadIdx.x; while (kk < nn) { s[kk] = f[kk+nn*n+jj]; kk += blockDim.x; } /* synchronize threads */ __syncthreads(); /* transform using local data in x */ ns = 1; for (l = 0; l < in; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; /* for (kk = 0; kk < nh; kk++) { */ kk = threadIdx.x; while (kk < nh) { k = kk/ns; j = kk - ns*k; k1 = ns2*k; k2 = k1 + ns; j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; t1.y = -t1.y; t2 = s[j2]; at1 = t1.x*t2.x - t1.y*t2.y; at2 = t1.x*t2.y + t1.y*t2.x; t2 = s[j1]; t3.x = t2.x - at1; t3.y = t2.y - at2; s[j2] = t3; t3.x = t2.x + at1; t3.y = t2.y + at2; s[j1] = t3; kk += blockDim.x; } ns = ns2; /* synchronize threads */ __syncthreads(); } /* copy data to global memory */ /* for (kk = 0; kk < nn; kk++) { */ kk = threadIdx.x; while (kk < nn) { f[kk+nn*n+jj] = s[kk]; kk += blockDim.x; } /* synchronize threads */ __syncthreads(); } /* transform using global data in x */ ns = 1L<<in; for (l = in; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; /* for (kk = 0; kk < nxhh; kk++) { */ kk = threadIdx.x; while (kk < nxhh) { k = kk/ns; j = kk - ns*k; k1 = ns2*k; k2 = k1 + ns; j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; t1.y = -t1.y; t2 = f[j2+jj]; at1 = t1.x*t2.x - t1.y*t2.y; at2 = t1.x*t2.y + t1.y*t2.x; t2 = f[j1+jj]; t3.x = t2.x - at1; t3.y = t2.y - at2; f[j2+jj] = t3; t3.x = t2.x + at1; t3.y = t2.y + at2; f[j1+jj] = t3; kk += blockDim.x; } ns = ns2; /* synchronize threads */ __syncthreads(); } } } return; } /*--------------------------------------------------------------------*/ __global__ void gpufft2rcys(float2 g[], int isign, int mixup[], float2 sct[], int indx, int indy, int nxi, int nxp, int nxhd, int nyd, int nxhyd, int nxyhd, int nsize) { /* this subroutine performs the y part of a two dimensional real to complex fast fourier transform and its inverse, for a subset of x, using complex arithmetic, with data not packed for isign = (-1,1), input: all, output: g for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny indx/indy = exponent which determines length in x/y direction, where nx=2**indx, ny=2**indy if isign = -1, an inverse fourier transform in y is performed g[n][m] = sum(g[j][k]*exp(-sqrt(-1)*2pi*m*k/ny)) if isign = 1, a forward fourier transform in y is performed g[j][k] = sum(g[n][m]*exp(sqrt(-1)*2pi*m*k/ny)) mixup = array of bit reversed addresses sct = sine/cosine table nxi = initial x index used nxp = number of x indices used nxhd = second dimension of g >= nx/2+1 nyd = first dimension of g >= ny nxhyd = maximum of (nx/2,ny) nxyhd = maximum of (nx,ny)/2 nsize = amount of scratch complex memory used fourier coefficients are stored as follows: g[j][k] = real, imaginary part of mode j,k, where 0 <= j < nx/2+1 and 0 <= k < ny written by viktor k. decyk, ucla local data */ int indx1, indx1y, nx, ny, nyh, nxy, nxhy, nxt; int nry, i, j, k, l, j1, j2, k1, k2, ns, ns2, km, kmr, koff, kk; int n, nn, in, nt, nh; float at1, at2; float2 t1, t2, t3; /* The size of the shared memory array is as follows: */ /* float2 s[nsize]; */ extern __shared__ float2 s[]; indx1 = indx - 1; indx1y = indx1 > indy ? indx1 : indy; nx = 1L<<indx; ny = 1L<<indy; nyh = ny/2; nxy = nx > ny ? nx : ny; nxhy = 1L<<indx1y; nxt = nxi + nxp - 1; /* calculate extent of shared memory usage: */ /* nn = size of shared memory in y */ nn = ny; in = 0; while (nn > nsize) { nn = nn/2; in += 1; } /* nt = number of iterations in y */ nt = 1L<<in; in = indy - in; nh = nn/2; /* bit-reverse array elements in y */ nry = nxhy/ny; /* for (j = nxi-1; j < nxt; j++) { */ j = blockIdx.x + nxi - 1; if (j < nxt) { kk = nyd*j; /* for (k = 0; k < ny; k++) { */ k = threadIdx.x; while (k < ny) { k1 = (mixup[k] - 1)/nry; if (k < k1) { t1 = g[k1+kk]; g[k1+kk] = g[k+kk]; g[k+kk] = t1; } k += blockDim.x; } /* synchronize threads */ __syncthreads(); } nry = nxy/ny; /* inverse fourier transform in y */ if (isign < 0) { /* copy data to local memory */ /* for (i = nxi-1; i < nxt; i++) { */ i = blockIdx.x + nxi - 1; if (i < nxt) { koff = nyd*i; for (n = 0; n < nt; n++) { /* for (kk = 0; kk < nn; kk++) { */ kk = threadIdx.x; while (kk < nn) { s[kk] = g[kk+nn*n+koff]; kk += blockDim.x; } /* synchronize threads */ __syncthreads(); /* transform using local data in y */ ns = 1; for (l = 0; l < in; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; /* for (kk = 0; kk < nh; kk++) { */ kk = threadIdx.x; while (kk < nh) { k = kk/ns; j = kk - ns*k; k1 = ns2*k; k2 = k1 + ns; j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; t2 = s[j2]; at1 = t1.x*t2.x - t1.y*t2.y; at2 = t1.x*t2.y + t1.y*t2.x; t3.x = t2.x - at1; t3.y = t2.y - at2; t2 = s[j1]; t3.x = t2.x - at1; t3.y = t2.y - at2; s[j2] = t3; t3.x = t2.x + at1; t3.y = t2.y + at2; s[j1] = t3; kk += blockDim.x; } ns = ns2; /* synchronize threads */ __syncthreads(); } /* copy data to global memory */ /* for (kk = 0; kk < nn; kk++) { */ kk = threadIdx.x; while (kk < nn) { g[kk+nn*n+koff] = s[kk]; kk += blockDim.x; } /* synchronize threads */ __syncthreads(); } /* transform using global data in y */ ns = 1L<<in; for (l = in; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; /* for (kk = 0; kk < nyh; kk++) { */ kk = threadIdx.x; while (kk < nyh) { k = kk/ns; j = kk - ns*k; k1 = ns2*k; k2 = k1 + ns; j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; t2 = g[j2+koff]; at1 = t1.x*t2.x - t1.y*t2.y; at2 = t1.x*t2.y + t1.y*t2.x; t3.x = t2.x - at1; t3.y = t2.y - at2; t2 = g[j1+koff]; t3.x = t2.x - at1; t3.y = t2.y - at2; g[j2+koff] = t3; t3.x = t2.x + at1; t3.y = t2.y + at2; g[j1+koff] = t3; kk += blockDim.x; } ns = ns2; /* synchronize threads */ __syncthreads(); } } } /* forward fourier transform in y */ if (isign > 0) { /* copy data to local memory */ /* for (i = nxi-1; i < nxt; i++) { */ i = blockIdx.x + nxi - 1; if (i < nxt) { koff = nyd*i; for (n = 0; n < nt; n++) { /* for (kk = 0; kk < nn; kk++) { */ kk = threadIdx.x; while (kk < nn) { s[kk] = g[kk+nn*n+koff]; kk += blockDim.x; } /* synchronize threads */ __syncthreads(); /* transform using local data in y */ ns = 1; for (l = 0; l < in; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; /* for (kk = 0; kk < nh; kk++) { */ kk = threadIdx.x; while (kk < nh) { k = kk/ns; j = kk - ns*k; k1 = ns2*k; k2 = k1 + ns; j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; t1.y = -t1.y; t2 = s[j2]; at1 = t1.x*t2.x - t1.y*t2.y; at2 = t1.x*t2.y + t1.y*t2.x; t3.x = t2.x - at1; t3.y = t2.y - at2; t2 = s[j1]; t3.x = t2.x - at1; t3.y = t2.y - at2; s[j2] = t3; t3.x = t2.x + at1; t3.y = t2.y + at2; s[j1] = t3; kk += blockDim.x; } ns = ns2; /* synchronize threads */ __syncthreads(); } /* copy data to global memory */ /* for (kk = 0; kk < nn; kk++) { */ kk = threadIdx.x; while (kk < nn) { g[kk+nn*n+koff] = s[kk]; kk += blockDim.x; } /* synchronize threads */ __syncthreads(); } /* transform using global data in y */ ns = 1L<<in; for (l = in; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; /* for (kk = 0; kk < nyh; kk++) { */ kk = threadIdx.x; while (kk < nyh) { k = kk/ns; j = kk - ns*k; k1 = ns2*k; k2 = k1 + ns; j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; t1.y = -t1.y; t2 = g[j2+koff]; at1 = t1.x*t2.x - t1.y*t2.y; at2 = t1.x*t2.y + t1.y*t2.x; t3.x = t2.x - at1; t3.y = t2.y - at2; t2 = g[j1+koff]; t3.x = t2.x - at1; t3.y = t2.y - at2; g[j2+koff] = t3; t3.x = t2.x + at1; t3.y = t2.y + at2; g[j1+koff] = t3; kk += blockDim.x; } ns = ns2; /* synchronize threads */ __syncthreads(); } } } return; } /*--------------------------------------------------------------------*/ __global__ void gpuppmtposes(float2 f[], float2 sm[], int nx, int kxp, int kyps, int kstrt, int nvp, int kxyp, int nxv, int kypd) { /* extract data to send */ /* local data */ int ks, j, k, n, nn, id, joff, ld; ks = kstrt - 1; /* for (n = 0; n < nvp; n++) { */ n = blockIdx.y; if (n < nvp) { id = n - ks; if (id < 0) id += nvp; /* find which node sends to itself */ nn = 2*ks; if (nn >= nvp) nn -= nvp; /* adjust counter */ if (n > nn) n -= 1; /* do not send local data */ if (id != ks) { joff = kxp*id; ld = nx - joff; ld = 0 > ld ? 0 : ld; ld = kxp < ld ? kxp : ld; /* for (k = 0; k < kyps; k++) { */ k = blockIdx.x; if (k < kyps) { /* for (j = 0; j < ld; j++) { */ j = threadIdx.x; while (j < ld) { sm[j+ld*k+kxyp*n] = f[j+joff+nxv*k]; j += blockDim.x; } } } } return; } /*--------------------------------------------------------------------*/ __global__ void gpuppmtposer(float2 g[], float2 tm[], int ny, int kyp, int kxps, int kstrt, int nvp, int kxyp, int nyv, int kxpd) { /* transpose data received */ /* local data */ int kt, mxv, j, k, n, nn, id, koff, ld, js, ks, jj, kk; /* The size of the shared memory array is as follows: */ /* float2 s2[(mx + 1)*mx]; */ extern __shared__ float2 s2[]; kt = kstrt - 1; mxv = blockDim.x + 1; /* for (n = 0; n < nvp; n++) { */ n = blockIdx.z; if (n < nvp) { id = n - kt; if (id < 0) id += nvp; /* find which node sends to itself */ nn = 2*kt; if (nn >= nvp) nn -= nvp; /* adjust counter */ if (n > nn) n -= 1; /* do not transpose local data */ if (id != kt) { koff = kyp*id; ld = ny - koff; ld = 0 > ld ? 0 : ld; ld = kyp < ld ? kyp : ld; js = threadIdx.x; ks = threadIdx.y; jj = blockDim.x*blockIdx.x; kk = blockDim.y*blockIdx.y; j = js + jj; k = ks + kk; if ((j < kxps) && (k < ld)) { s2[js+mxv*ks] = tm[j+kxps*k+kxyp*n]; } /* synchronize threads */ __syncthreads(); j = ks + jj; k = js + kk; if ((j < kxps) && (k < ld)) { g[k+koff+nyv*j] = s2[ks+mxv*js]; } } } return; } /*--------------------------------------------------------------------*/ __global__ void gpuppmtposesn(float2 fn[], float2 sm[], int nx, int kxp, int kyps, int kstrt, int nvp, int ndim, int kxyp, int nxv, int kypd) { /* extract vector data to send */ /* local data */ int ks, i, j, k, n, nn, id, joff, ld, nnxv, nkxyp; ks = kstrt - 1; nnxv = ndim*nxv; nkxyp = ndim*kxyp; /* for (n = 0; n < nvp; n++) { */ n = blockIdx.y; if (n < nvp) { id = n - ks; if (id < 0) id += nvp; /* find which node sends to itself */ nn = 2*ks; if (nn >= nvp) nn -= nvp; /* adjust counter */ if (n > nn) n -= 1; /* do not send local data */ if (id != ks) { joff = kxp*id; ld = nx - joff; ld = 0 > ld ? 0 : ld; ld = kxp < ld ? kxp : ld; /* for (k = 0; k < kyps; k++) { */ k = blockIdx.x; if (k < kyps) { /* for (j = 0; j < ld; j++) { */ j = threadIdx.x; while (j < ld) { for (i = 0; i < ndim; i++) { sm[j+ld*(i+ndim*k)+nkxyp*n] = fn[j+joff+nxv*i+nnxv*k]; } j += blockDim.x; } } } } return; } /*--------------------------------------------------------------------*/ __global__ void gpuppmtposern(float2 gn[], float2 tm[], int ny, int kyp, int kxps, int kstrt, int nvp, int ndim, int kxyp, int nyv, int kxpd) { /* transpose vector data received */ /* local data */ int kt, mxv, i, j, k, n, nn, id, koff, ld, js, ks, jj, kk; int nnyv, nkxyp; /* The size of the shared memory array is as follows: */ /* float2 s2n[ndim*(mx + 1)*mx]; */ extern __shared__ float2 s2n[]; kt = kstrt - 1; mxv = blockDim.x + 1; nnyv = ndim*nyv; nkxyp = ndim*kxyp; /* for (n = 0; n < nvp; n++) { */ n = blockIdx.z; if (n < nvp) { id = n - kt; if (id < 0) id += nvp; /* find which node sends to itself */ nn = 2*kt; if (nn >= nvp) nn -= nvp; /* adjust counter */ if (n > nn) n -= 1; /* do not transpose local data */ if (id != kt) { koff = kyp*id; ld = ny - koff; ld = 0 > ld ? 0 : ld; ld = kyp < ld ? kyp : ld; js = threadIdx.x; ks = threadIdx.y; jj = blockDim.x*blockIdx.x; kk = blockDim.y*blockIdx.y; j = js + jj; k = ks + kk; if ((j < kxps) && (k < ld)) { for (i = 0; i < ndim; i++) { s2n[js+mxv*(i+ndim*ks)] = tm[j+kxps*(i+ndim*k)+nkxyp*n]; } } /* synchronize threads */ __syncthreads(); j = ks + jj; k = js + kk; if ((j < kxps) && (k < ld)) { for (i = 0; i < ndim; i++) { gn[k+koff+nyv*i+nnyv*j] = s2n[ks+mxv*(i+ndim*js)]; } } } } return; } /*--------------------------------------------------------------------*/ __global__ void gpuppltpose(float2 f[], float2 g[], int nx, int ny, int kxp, int kyp, int kstrt, int nxv, int nyv) { /* transpose local data */ /* local data */ int mxv, j, k, ks, kxps, kyps, joff, koff, js, jj, kk; /* The size of the shared memory array is as follows: */ /* float2 s2[(mx + 1)*mx]; */ extern __shared__ float2 s2[]; mxv = blockDim.x + 1; ks = kstrt - 1; joff = kxp*ks; koff = kyp*ks; kxps = nx - joff; kxps = 0 > kxps ? 0 : kxps; kxps = kxp < kxps ? kxp : kxps; kyps = ny - koff; kyps = 0 > kyps ? 0 : kyps; kyps = kyp < kyps ? kyp : kyps; js = threadIdx.x; ks = threadIdx.y; jj = blockDim.x*blockIdx.x; kk = blockDim.y*blockIdx.y; j = js + jj; k = ks + kk; if ((j < kxps) && (k < kyps)) { s2[js+mxv*ks] = f[j+joff+nxv*k]; } /* synchronize threads */ __syncthreads(); j = ks + jj; k = js + kk; if ((j < kxps) && (k < kyps)) { g[k+koff+nyv*j] = s2[ks+mxv*js]; } return; } /*--------------------------------------------------------------------*/ __global__ void gpuppltposen(float2 fn[], float2 gn[], int nx, int ny, int kxp, int kyp, int kstrt, int ndim, int nxv, int nyv) { /* transpose local vector data */ /* local data */ int mxv, i, j, k, ks, kxps, kyps, joff, koff, js, jj, kk; int nnxv, nnyv; /* The size of the shared memory array is as follows: */ /* float2 s2n[ndim*(mx + 1)*mx]; */ extern __shared__ float2 s2n[]; mxv = blockDim.x + 1; ks = kstrt - 1; nnxv = ndim*nxv; nnyv = ndim*nyv; joff = kxp*ks; koff = kyp*ks; kxps = nx - joff; kxps = 0 > kxps ? 0 : kxps; kxps = kxp < kxps ? kxp : kxps; kyps = ny - koff; kyps = 0 > kyps ? 0 : kyps; kyps = kyp < kyps ? kyp : kyps; js = threadIdx.x; ks = threadIdx.y; jj = blockDim.x*blockIdx.x; kk = blockDim.y*blockIdx.y; j = js + jj; k = ks + kk; if ((j < kxps) && (k < kyps)) { for (i = 0; i < ndim; i++) { s2n[js+mxv*(i+ndim*ks)] = fn[j+joff+nxv*i+nnxv*k]; } } /* synchronize threads */ __syncthreads(); j = ks + jj; k = js + kk; if ((j < kxps) && (k < kyps)) { for (i = 0; i < ndim; i++) { gn[k+koff+nyv*i+nnyv*j] = s2n[ks+mxv*(i+ndim*js)]; } } return; } /*--------------------------------------------------------------------*/ __global__ void gpusum1(float a[], float *sa, int nx) { /* 1d serial sum reduction */ /* nx = length of data */ /* sa = sum(a) */ /* local data */ int j, js, jb, mx, joff, mxm; float t; /* The size of the shared memory array is as follows: */ /* ss[blockDim.x]; */ extern __shared__ float ss[]; mx = blockDim.x; js = threadIdx.x; jb = blockIdx.x; joff = mx*jb; j = js + joff; /* copy global data to shared memory */ if (j < nx) ss[js] = a[j]; /* synchronize to make sure each thread in block has the data */ __syncthreads(); if (js==0) { mxm = nx - joff; if (mxm > mx) mxm = mx; /* perform serial local sum reduction: result in t */ t = 0.0f; for (j = 0; j < mxm; j++) { t += ss[j]; } /* accumulate results to global memory for each block */ /* for devices with compute capability 2.x */ atomicAdd(&sa[0],t); } return; } /*--------------------------------------------------------------------*/ __global__ void gpusum2(float a[], float d[], int nx) { /* segmented 1d sum reductions, each of length mx = blockDim.x */ /* nx = length of data */ /* forall (j = 1:nbx); d(j) = sum(a(1+mx*(j-1):min(nx,mx*j))) */ /* local data */ int j, js, jb, mx, joff, mxm; /* The size of the shared memory array is as follows: */ /* ss[blockDim.x]; */ extern __shared__ float ss[]; mx = blockDim.x; js = threadIdx.x; jb = blockIdx.x; joff = mx*jb; j = js + joff; /* copy global data to shared memory */ if (j < nx) ss[js] = a[j]; /* synchronize to make sure each thread in block has the data */ __syncthreads(); mxm = nx - joff; if (mxm > mx) mxm = mx; /* perform parallel local sum reduction: result in ss[0] */ lsum2(ss,mxm); /* write out result to global memory for each block */ if (js==0) d[jb] = ss[0]; return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppgppush2l(float *ppart, float *fxy, int *kpic, int noff, int nyp, float qbm, float dt, float *ek, int nx, int ny, int mx, int my, int idimp, int nppmx, int nxv, int nypmx, int mx1, int mxyp1, int ipbc) { /* Push Interface for C */ int n, m, ns; dim3 dimBlock(nblock_size); n = mxyp1; m = (n - 1)/maxgsx + 1; n = n < maxgsx ? n : maxgsx; dim3 dimGrid(n,m); ns = 2*(mx + 1)*(my + 1)*sizeof(float); n = nblock_size*sizeof(float); ns = ns > n ? ns : n; crc = cudaGetLastError(); gpuppgppush2l<<<dimGrid,dimBlock,ns>>>(ppart,fxy,kpic,noff,nyp,qbm, dt,ek,nx,ny,mx,my,idimp,nppmx, nxv,nypmx,mx1,mxyp1,ipbc); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpuppgppush2l error=%d:%s\n",crc,cudaGetErrorString(crc)); exit(1); } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpu2ppgppost2l(float *ppart, float *q, int *kpic, int noff, float qm, int idimp, int nppmx, int mx, int my, int nxv, int nypmx, int mx1, int mxyp1) { /* Deposit Interface for C */ int n, m, ns; dim3 dimBlock(nblock_size); n = mxyp1; m = (n - 1)/maxgsx + 1; n = n < maxgsx ? n : maxgsx; dim3 dimGrid(n,m); ns = (mx + 1)*(my + 1)*sizeof(float); crc = cudaGetLastError(); gpu2ppgppost2l<<<dimGrid,dimBlock,ns>>>(ppart,q,kpic,noff,qm,idimp, nppmx,mx,my,nxv,nypmx,mx1, mxyp1); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpu2ppgppost2l error=%d:%s\n",crc,cudaGetErrorString(crc)); exit(1); } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppcaguard2xl(float2 *qc, float2 *scs, float *q, int nyp, int nx, int nxe, int nypmx, int nxvh, int kypd) { /* Guard Cell Interface for C */ dim3 dimBlock(nblock_size); dim3 dimGrid(nyp); crc = cudaGetLastError(); gpuppcaguard2xl<<<dimGrid,dimBlock>>>(qc,scs,q,nyp,nx,nxe,nypmx,nxvh, kypd); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpuppcaguard2xl error=%d:%s\n",crc, cudaGetErrorString(crc)); exit(1); } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppcaguard2yl(float2 *qc, float2 *scr, int nx, int nxvh, int kypd) { /* Guard Cell Interface for C */ int nxh; nxh = nx/2; dim3 dimBlock(nblock_size); dim3 dimGrid((nxh - 1)/nblock_size+1); crc = cudaGetLastError(); gpuppcaguard2yl<<<dimGrid,dimBlock>>>(qc,scr,nx,nxvh,kypd); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpuppcaguard2yl error=%d:%s\n",crc, cudaGetErrorString(crc)); exit(1); } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppccguard2xl(float2 *fxyc, float2 *scs, float *fxy, int nyp, int nx, int nxe, int nypmx, int nxvh, int kypd) { /* Guard Cell Interface for C */ dim3 dimBlock(nblock_size); dim3 dimGrid(nyp); crc = cudaGetLastError(); gpuppccguard2xl<<<dimGrid,dimBlock>>>(fxyc,scs,fxy,nyp,nx,nxe,nypmx, nxvh,kypd); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpuppccguard2xl error=%d:%s\n",crc, cudaGetErrorString(crc)); exit(1); } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppccguard2yl(float *fxy, float2 *scr, int nyp, int nx, int nxe, int nxvh, int nypmx) { /* Guard Cell Interface for C */ int nxh; nxh = nx/2; dim3 dimBlock(nblock_size); dim3 dimGrid((nxh - 1)/nblock_size+1); crc = cudaGetLastError(); gpuppccguard2yl<<<dimGrid,dimBlock>>>(fxy,scr,nyp,nx,nxe,nxvh,nypmx); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpuppccguard2yl error=%d:%s\n",crc, cudaGetErrorString(crc)); exit(1); } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpupppord2la(float *ppart, float *ppbuff, float *sbufl, float *sbufr, int *kpic, int *ncl, int *ihole, int *ncll, int *nclr, int noff, int nyp, int idimp, int nppmx, int nx, int ny, int mx, int my, int mx1, int myp1, int npbmx, int ntmax, int nbmax, int *irc) { /* Sort Interface for C */ int mxyp1, n, m, ns, nbl, ierr; static int *g_block = NULL; static int lg_block = 0; dim3 dimBlock(nblock_size); mxyp1 = mx1*myp1; m = (mxyp1 - 1)/maxgsx + 1; n = mxyp1 < maxgsx ? mxyp1 : maxgsx; dim3 dimGrid(n,m); /* find which particles are leaving tile */ ns = (nblock_size+9)*sizeof(int); crc = cudaGetLastError(); gpupppfnd2l<<<dimGrid,dimBlock,ns>>>(ppart,kpic,ncl,ihole,noff,nyp, idimp,nppmx,nx,ny,mx,my,mx1, myp1,ntmax,irc); /* cudaThreadSynchronize(); */ crc = cudaGetLastError(); if (crc) { printf("gpupppfnd2l error=%d:%s\n",crc,cudaGetErrorString(crc)); exit(1); } /* buffer particles that are leaving tile and sum ncl */ ns = 9*sizeof(int); crc = cudaGetLastError(); gpupppmov2l<<<dimGrid,dimBlock,ns>>>(ppart,ppbuff,ncl,ihole,idimp, nppmx,mx1,myp1,npbmx,ntmax,irc); /* cudaThreadSynchronize(); */ crc = cudaGetLastError(); if (crc) { printf("gpupppmov2l error=%d:%s\n",crc,cudaGetErrorString(crc)); exit(1); } /* find address offsets */ nbl = (mx1 - 1)/nblock_size + 1; dim3 dimGrids(nbl); /* allocate scratch memory needed by prefix scan */ ierr = 0; if (lg_block < nbl) { if (lg_block > 0) gpu_deallocate((void *)g_block,&ierr); lg_block = 0; gpu_iallocate(&g_block,2*nbl,&ierr); if (ierr != 0) { printf("GPU g_block allocate error!\n"); exit(1); } lg_block = nbl; } ns = 2*nblock_size*sizeof(int); crc = cudaGetLastError(); nciscan2<<<dimGrids,dimBlock,ns>>>(ncl,ncll,nclr,g_block,mx1,myp1); /* cudaThreadSynchronize(); */ crc = cudaGetLastError(); if (crc) { printf("nciscan2 error=%d:%s\n",crc,cudaGetErrorString(crc)); exit(1); } /* copy particles and offsets leaving processor */ /* gpupppbuf2l and nciscan2 should use the same blocksize */ dim3 dimGridg(mx1); crc = cudaGetLastError(); gpupppbuf2l<<<dimGridg,dimBlock>>>(ppbuff,sbufl,sbufr,ncl,ncll,nclr, g_block,idimp,mx1,myp1,npbmx, nbmax,irc); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpupppbuf2l error=%d:%s\n",crc,cudaGetErrorString(crc)); exit(1); } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpupppord2lb(float *ppart, float *ppbuff, float *rbufl, float *rbufr, int *kpic, int *ncl, int *ihole, int *mcll, int *mclr, int idimp, int nppmx, int mx1, int myp1, int npbmx, int ntmax, int nbmax, int *irc) { /* Sort Interface for C */ int mxyp1, n, m, ns; dim3 dimBlock(nblock_size); mxyp1 = mx1*myp1; m = (mxyp1 - 1)/maxgsx + 1; n = mxyp1 < maxgsx ? mxyp1 : maxgsx; dim3 dimGrid(n,m); /* copy incoming particles from ppbuff, rbufl, and rbufr into ppart */ /* and update kpic */ ns = (nblock_size+18)*sizeof(int); crc = cudaGetLastError(); gpupppord2l<<<dimGrid,dimBlock,ns>>>(ppart,ppbuff,rbufl,rbufr,kpic, ncl,ihole,mcll,mclr,idimp,nppmx, mx1,myp1,npbmx,ntmax,nbmax,irc); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpupppord2l error=%d:%s\n",crc,cudaGetErrorString(crc)); exit(1); } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppois22t(float2 *qt, float2 *fxyt, float2 *ffct, float *we, int nx, int ny, int kstrt, int nyv, int kxp1, int nyhd) { /* Poisson Solver Interface for C */ int nxh1, ks, kxpp, ns; dim3 dimBlock(nblock_size); nxh1 = nx/2 + 1; ks = kstrt - 1; kxpp = nxh1 - kxp1*ks; kxpp = 0 > kxpp ? 0 : kxpp; kxpp = kxp1 < kxpp ? kxp1 : kxpp; if (kxpp <= 0) return; dim3 dimGrid(kxpp); ns = nblock_size*sizeof(float); crc = cudaGetLastError(); gpuppois22t<<<dimGrid,dimBlock,ns>>>(qt,fxyt,ffct,we,nx,ny,kstrt,nyv, kxp1,nyhd); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpuppois22t error=%d:%s\n",crc,cudaGetErrorString(crc)); exit(1); } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuwppfft2rcsx(float2 *f, float2 *bsm, int isign, int *mixup, float2 *sct, int indx, int indy, int kstrt, int nvp, int kxp1, int kyp, int nxhd, int kypd, int nxhyd, int nxyhd) { /* wrapper function for parallel real to complex fft in x, */ /* without packed data */ /* nxhd must be >= nx/2 + 1 */ /* local data */ int nxh, nxh1, ny, ks, kypp, kxyp, nsize, ns; static int kypi = 1, mx = 16; dim3 dimBlock(nblock_size); dim3 dimBlockt(mx,mx); /* calculate range of indices */ nxh = 1L<<(indx - 1); nxh1 = nxh + 1; ny = 1L<<indy; ks = kstrt - 1; kypp = ny - kyp*ks; kypp = 0 > kypp ? 0 : kypp; kypp = kyp < kypp ? kyp : kypp; if (kypp <= 0) return; kxyp = kxp1*kyp; dim3 dimGridy(kypp); dim3 dimGrids(kypp,nvp); dim3 dimGridty((kyp-1)/mx+1,(kxp1-1)/mx+1,nvp); /* inverse fourier transform */ if (isign < 0) { nsize = nxh < 1024 ? nxh : 1024; ns = nsize*sizeof(float2); /* perform x fft */ if (kstrt <= ny) { crc = cudaGetLastError(); gpufft2rcxs<<<dimGridy,dimBlock,ns>>>(f,isign,mixup,sct,indx, indy,kypi,kypp,nxhd,kypd, nxhyd,nxyhd,nsize); /* cudaThreadSynchronize(); */ crc = cudaGetLastError(); if (crc) { printf("gpufft2rcxs error=%d:%s\n", crc,cudaGetErrorString(crc)); exit(1); } } /* extract data to send */ crc = cudaGetLastError(); gpuppmtposes<<<dimGrids,dimBlock>>>(f,bsm,nxh1,kxp1,kypp,kstrt, nvp,kxyp,nxhd,kypd); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpuppmtposes error=%d:%s\n",crc, cudaGetErrorString(crc)); exit(1); } } /* forward fourier transform */ else if (isign > 0) { ns = (mx+1)*mx*sizeof(float2); /* transpose data received */ crc = cudaGetLastError(); gpuppmtposer<<<dimGridty,dimBlockt,ns>>>(f,bsm,nxh1,kxp1,kypp, kstrt,nvp,kxyp,nxhd, kypd); /* cudaThreadSynchronize(); */ crc = cudaGetLastError(); if (crc) { printf("gpuppmtposer error=%d:%s\n",crc, cudaGetErrorString(crc)); exit(1); } /* perform x fft */ nsize = nxh < 1024 ? nxh : 1024; ns = nsize*sizeof(float2); if (kstrt <= ny) { gpufft2rcxs<<<dimGridy,dimBlock,ns>>>(f,isign,mixup,sct,indx, indy,kypi,kypp,nxhd,kypd, nxhyd,nxyhd,nsize); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpufft2rcxs error=%d:%s\n", crc,cudaGetErrorString(crc)); exit(1); } } } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuwppfft2rcsy(float2 *g, float2 *brm, int isign, int *mixup, float2 *sct, int indx, int indy, int kstrt, int nvp, int kxp1, int kyp, int nyd, int nxhyd, int nxyhd) { /* wrapper function for parallel real to complex fft in y, */ /* without packed data */ /* nyd must be >= ny */ /* local data */ int nxh, nxh1, ny, ks, kxpp, kxyp, nsize, ns; static int kxpi = 1, mx = 16; /* double dtime; */ dim3 dimBlock(nblock_size); dim3 dimBlockt(mx,mx); /* calculate range of indices */ nxh = 1L<<(indx - 1); nxh1 = nxh + 1; ny = 1L<<indy; ks = kstrt - 1; kxpp = nxh1 - kxp1*ks; kxpp = 0 > kxpp ? 0 : kxpp; kxpp = kxp1 < kxpp ? kxp1 : kxpp; if (kxpp <= 0) return; kxyp = kxp1*kyp; dim3 dimGridx(kxpp); dim3 dimGrids(kxpp,nvp); dim3 dimGridtx((kxp1-1)/mx+1,(kyp-1)/mx+1,nvp); /* inverse fourier transform */ if (isign < 0) { ns = (mx+1)*mx*sizeof(float2); /* transpose data received */ crc = cudaGetLastError(); gpuppmtposer<<<dimGridtx,dimBlockt,ns>>>(g,brm,ny,kyp,kxpp,kstrt, nvp,kxyp,nyd,kxp1); /* cudaThreadSynchronize(); */ crc = cudaGetLastError(); if (crc) { printf("gpuppmtposer error=%d:%s\n",crc, cudaGetErrorString(crc)); exit(1); } /* perform y fft */ nsize = ny < 1024 ? ny : 1024; ns = nsize*sizeof(float2); if (kstrt <= nxh1) { crc = cudaGetLastError(); gpufft2rcys<<<dimGridx,dimBlock,ns>>>(g,isign,mixup,sct,indx, indy,kxpi,kxpp,kxp1,nyd, nxhyd,nxyhd,nsize); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpufft2rcys error=%d:%s\n", crc,cudaGetErrorString(crc)); exit(1); } } } /* forward fourier transform */ else if (isign > 0) { nsize = ny < 1024 ? ny : 1024; ns = nsize*sizeof(float2); /* perform y fft */ if (kstrt <= nxh1) { crc = cudaGetLastError(); gpufft2rcys<<<dimGridx,dimBlock,ns>>>(g,isign,mixup,sct,indx, indy,kxpi,kxpp,kxp1,nyd, nxhyd,nxyhd,nsize); /* cudaThreadSynchronize(); */ crc = cudaGetLastError(); if (crc) { printf("gpufft2rcys error=%d:%s\n", crc,cudaGetErrorString(crc)); exit(1); } } /* extract data to send */ crc = cudaGetLastError(); gpuppmtposes<<<dimGrids,dimBlock>>>(g,brm,ny,kyp,kxpp,kstrt, nvp,kxyp,nyd,kxp1); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpuppmtposes error=%d:%s\n",crc, cudaGetErrorString(crc)); exit(1); } } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuwppfft2rcsxn(float2 *fn, float2 *bsm, int isign, int *mixup, float2 *sct, int indx, int indy, int ndim, int kstrt, int nvp, int kxp1, int kyp, int nxhd, int kypd, int nxhyd, int nxyhd) { /* wrapper function for multiple parallel real to complex ffts in x, */ /* without packed data */ /* ndim = vector dimension */ /* nxhd must be >= nx/2 + 1 */ /* local data */ int nxh, nxh1, ny, ks, kypp, kxyp, nkypd, nkypp, nsize, ns; static int kypi = 1, mx = 16; dim3 dimBlock(nblock_size); dim3 dimBlockt(mx,mx); /* calculate range of indices */ nxh = 1L<<(indx - 1); nxh1 = nxh + 1; ny = 1L<<indy; ks = kstrt - 1; kypp = ny - kyp*ks; kypp = 0 > kypp ? 0 : kypp; kypp = kyp < kypp ? kyp : kypp; if (kypp <= 0) return; kxyp = kxp1*kyp; nkypd = ndim*kypd; nkypp = ndim*kypp; dim3 dimGridy(nkypp); dim3 dimGrids(kypp,nvp); dim3 dimGridty((kyp-1)/mx+1,(kxp1-1)/mx+1,nvp); /* inverse fourier transform */ if (isign < 0) { nsize = nxh < 1024 ? nxh : 1024; ns = nsize*sizeof(float2); /* perform x fft */ if (kstrt <= ny) { crc = cudaGetLastError(); gpufft2rcxs<<<dimGridy,dimBlock,ns>>>(fn,isign,mixup,sct,indx, indy,kypi,nkypp,nxhd, nkypd,nxhyd,nxyhd,nsize); /* cudaThreadSynchronize(); */ crc = cudaGetLastError(); if (crc) { printf("gpufft2rcxs error=%d:%s\n", crc,cudaGetErrorString(crc)); exit(1); } } /* extract data to send */ crc = cudaGetLastError(); gpuppmtposesn<<<dimGrids,dimBlock>>>(fn,bsm,nxh1,kxp1,kypp,kstrt, nvp,ndim,kxyp,nxhd,kypd); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpuppmtposesn error=%d:%s\n",crc, cudaGetErrorString(crc)); exit(1); } } /* forward fourier transform */ else if (isign > 0) { ns = ndim*(mx+1)*mx*sizeof(float2); /* transpose data received */ crc = cudaGetLastError(); gpuppmtposern<<<dimGridty,dimBlockt,ns>>>(fn,bsm,nxh1,kxp1,kypp, kstrt,nvp,ndim,kxyp, nxhd,kypd); /* cudaThreadSynchronize(); */ crc = cudaGetLastError(); if (crc) { printf("gpuppmtposern error=%d:%s\n",crc, cudaGetErrorString(crc)); exit(1); } /* perform x fft */ nsize = nxh < 1024 ? nxh : 1024; ns = nsize*sizeof(float2); if (kstrt <= ny) { crc = cudaGetLastError(); gpufft2rcxs<<<dimGridy,dimBlock,ns>>>(fn,isign,mixup,sct,indx, indy,kypi,nkypp,nxhd, nkypd,nxhyd,nxyhd,nsize); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpufft2rcxs error=%d:%s\n", crc,cudaGetErrorString(crc)); exit(1); } } } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuwppfft2rcsyn(float2 *gn, float2 *brm, int isign, int *mixup, float2 *sct, int indx, int indy, int ndim, int kstrt, int nvp, int kxp1, int kyp, int nyd, int nxhyd, int nxyhd) { /* wrapper function for multiple parallel real to complex ffts in y, */ /* without packed data */ /* ndim = vector dimension */ /* nyd must be >= ny */ /* local data */ int nxh, nxh1, ny, ks, kxpp, kxyp, nkxp1, nkxpp, nsize, ns; static int kxpi = 1, mx = 16; /* double dtime; */ dim3 dimBlock(nblock_size); dim3 dimBlockt(mx,mx); /* calculate range of indices */ nxh = 1L<<(indx - 1); nxh1 = nxh + 1; ny = 1L<<indy; ks = kstrt - 1; kxpp = nxh1 - kxp1*ks; kxpp = 0 > kxpp ? 0 : kxpp; kxpp = kxp1 < kxpp ? kxp1 : kxpp; if (kxpp <= 0) return; kxyp = kxp1*kyp; nkxp1 = ndim*kxp1; nkxpp = ndim*kxpp; dim3 dimGridx(nkxpp); dim3 dimGrids(kxpp,nvp); dim3 dimGridtx((kxp1-1)/mx+1,(kyp-1)/mx+1,nvp); /* inverse fourier transform */ if (isign < 0) { ns = ndim*(mx+1)*mx*sizeof(float2); /* transpose data received */ crc = cudaGetLastError(); gpuppmtposern<<<dimGridtx,dimBlockt,ns>>>(gn,brm,ny,kyp,kxpp, kstrt,nvp,ndim,kxyp,nyd, kxp1); /* cudaThreadSynchronize(); */ crc = cudaGetLastError(); if (crc) { printf("gpuppmtposern error=%d:%s\n",crc, cudaGetErrorString(crc)); exit(1); } /* perform y fft */ nsize = ny < 1024 ? ny : 1024; ns = nsize*sizeof(float2); if (kstrt <= nxh1) { crc = cudaGetLastError(); gpufft2rcys<<<dimGridx,dimBlock,ns>>>(gn,isign,mixup,sct,indx, indy,kxpi,nkxpp,nkxp1, nyd,nxhyd,nxyhd,nsize); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpufft2rcys error=%d:%s\n", crc,cudaGetErrorString(crc)); exit(1); } } } /* forward fourier transform */ else if (isign > 0) { /* perform y fft */ nsize = ny < 1024 ? ny : 1024; ns = nsize*sizeof(float2); if (kstrt <= nxh1) { crc = cudaGetLastError(); gpufft2rcys<<<dimGridx,dimBlock,ns>>>(gn,isign,mixup,sct,indx, indy,kxpi,nkxpp,nkxp1, nyd,nxhyd,nxyhd,nsize); /* cudaThreadSynchronize(); */ crc = cudaGetLastError(); if (crc) { printf("gpufft2rcys error=%d:%s\n", crc,cudaGetErrorString(crc)); exit(1); } } /* extract data to send */ crc = cudaGetLastError(); gpuppmtposesn<<<dimGrids,dimBlock>>>(gn,brm,ny,kyp,kxpp,kstrt, nvp,ndim,kxyp,nyd,kxp1); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpuppmtposesn error=%d:%s\n",crc, cudaGetErrorString(crc)); exit(1); } } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppltpose(float2 *f, float2 *g, int nx, int ny, int kxp, int kyp, int kstrt, int nxv, int nyv) { /* local complex transpose using blocking algorithm with gaps */ /* input = f, output = g */ /* local data */ int ns; static int mx = 16; dim3 dimBlockt(mx,mx); /* calculate range of indices */ dim3 dimGridtx((kxp-1)/mx+1,(kyp-1)/mx+1); ns = (mx+1)*mx*sizeof(float2); /* local transpose f to g */ crc = cudaGetLastError(); gpuppltpose<<<dimGridtx,dimBlockt,ns>>>(f,g,nx,ny,kxp,kyp,kstrt,nxv, nyv); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpuppltpose error=%d:%s\n",crc,cudaGetErrorString(crc)); exit(1); } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppltposen(float2 *fn, float2 *gn, int nx, int ny, int kxp, int kyp, int kstrt, int ndim, int nxv, int nyv) { /* local complex vector transpose */ /* input = fn, output = gn */ /* local data */ int ns; static int mx = 16; dim3 dimBlockt(mx,mx); /* calculate range of indices */ dim3 dimGridtx((kxp-1)/mx+1,(kyp-1)/mx+1); ns = ndim*(mx+1)*mx*sizeof(float2); /* local transpose f to g */ crc = cudaGetLastError(); gpuppltposen<<<dimGridtx,dimBlockt,ns>>>(fn,gn,nx,ny,kxp,kyp,kstrt, ndim,nxv,nyv); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpuppltposen error=%d:%s\n",crc,cudaGetErrorString(crc)); exit(1); } return; } /*--------------------------------------------------------------------*/ extern "C" void cgpusum2(float *a, float *sa, int nx) { /* segmented 1d parallel sum reduction of input array a, of length nx */ /* first reduce individual blocks in parallel, writing result to scr */ /* then reduce scr serially, result is written to sa */ /* local data */ int nbx, nbs, ns; void *gptr; static int len = 0; static float *scr = NULL; nbx = (nx - 1)/nblock_size + 1; dim3 dimBlock(nblock_size); dim3 dimGrid(nbx); nbs = (nbx - 1)/nblock_size + 1; dim3 dimGrid1(nbs); /* create scratch array */ if (len < nbx) { if (len > 0) crc = cudaFree((void *)scr); crc = cudaMalloc(&gptr,sizeof(float)*nbx); if (crc) { printf("cudaMalloc cgpusum2 float Error=%d:%s,l=%d\n",crc, cudaGetErrorString(crc),nbx); exit(1); } scr = (float *)gptr; len = nbx; } /* reduce individual blocks in parallel */ ns = nblock_size*sizeof(float); crc = cudaGetLastError(); gpusum2<<<dimGrid,dimBlock,ns>>>(a,scr,nx); /* cudaThreadSynchronize(); */ crc = cudaGetLastError(); if (crc) { printf("gpusum2 error=%d:%s\n",crc,cudaGetErrorString(crc)); exit(1); } /* 1d serial reduction */ crc = cudaGetLastError(); gpusum1<<<dimGrid1,dimBlock,ns>>>(scr,sa,nbx); cudaThreadSynchronize(); crc = cudaGetLastError(); if (crc) { printf("gpusum1 error=%d:%s\n",crc,cudaGetErrorString(crc)); exit(1); } return; } /* Interfaces to Fortran */ /*--------------------------------------------------------------------*/ extern "C" void cgpuppgppush2l_(unsigned long *gp_ppart, unsigned long *gp_fxy, unsigned long *gp_kpic, int *noff, int *nyp, float *qbm, float *dt, unsigned long *gp_ek, int *nx, int *ny, int *mx, int *my, int *idimp, int *nppmx, int *nxv, int *nypmx, int *mx1, int *mxyp1, int *ipbc) { float *ppart, *fxy, *ek; int *kpic; ppart = (float *)*gp_ppart; fxy = (float *)*gp_fxy; kpic = (int *)*gp_kpic; ek = (float *)*gp_ek; cgpuppgppush2l(ppart,fxy,kpic,*noff,*nyp,*qbm,*dt,ek,*nx,*ny,*mx,*my, *idimp,*nppmx,*nxv,*nypmx,*mx1,*mxyp1,*ipbc); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpu2ppgppost2l_(unsigned long *gp_ppart, unsigned long *gp_q, unsigned long *gp_kpic, int *noff, float *qm, int *idimp, int *nppmx, int *mx, int *my, int *nxv, int *nypmx, int *mx1, int *mxyp1) { float *ppart, *q; int *kpic; ppart = (float *)*gp_ppart; q = (float *)*gp_q; kpic = (int *)*gp_kpic; cgpu2ppgppost2l(ppart,q,kpic,*noff,*qm,*idimp,*nppmx,*mx,*my,*nxv, *nypmx,*mx1,*mxyp1); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppcaguard2xl_(unsigned long *gp_qc, unsigned long *gp_scs, unsigned long *gp_q, int *nyp, int *nx, int *nxe, int *nypmx, int *nxvh, int *kypd) { float2 *qc, *scs; float *q; qc = (float2 *)*gp_qc; scs = (float2 *)*gp_scs; q = (float *)*gp_q; cgpuppcaguard2xl(qc,scs,q,*nyp,*nx,*nxe,*nypmx,*nxvh,*kypd); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppcaguard2yl_(unsigned long *gp_fc, unsigned long *gp_scr, int *nx, int *nxvh, int *kypd) { float2 *fc, *scr; fc = (float2 *)*gp_fc; scr = (float2 *)*gp_scr; cgpuppcaguard2yl(fc,scr,*nx,*nxvh,*kypd); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppccguard2xl_(unsigned long *gp_fxyc, unsigned long *gp_scs, unsigned long *gp_fxy, int *nyp, int *nx, int *nxe, int *nypmx, int *nxvh, int *kypd) { float2 *fxyc, *scs; float *fxy; fxyc = (float2 *)*gp_fxyc; scs = (float2 *)*gp_scs; fxy = (float *)*gp_fxy; cgpuppccguard2xl(fxyc,scs,fxy,*nyp,*nx,*nxe,*nypmx,*nxvh,*kypd); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppccguard2yl_(unsigned long *gp_fxy, unsigned long *gp_scr, int *nyp, int *nx, int *nxe, int *nxvh, int *nypmx) { float *fxy; float2 *scr; fxy = (float *)*gp_fxy; scr = (float2 *)*gp_scr; cgpuppccguard2yl(fxy,scr,*nyp,*nx,*nxe,*nxvh,*nypmx); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpupppord2la_(unsigned long *gp_ppart, unsigned long *gp_ppbuff, unsigned long *gp_sbufl, unsigned long *gp_sbufr, unsigned long *gp_kpic, unsigned long *gp_ncl, unsigned long *gp_ihole, unsigned long *gp_ncll, unsigned long *gp_nclr, int *noff, int *nyp, int *idimp, int *nppmx, int *nx, int *ny, int *mx, int *my, int *mx1, int *myp1, int *npbmx, int *ntmax, int *nbmax, unsigned long *gp_irc) { float *ppart, *ppbuff, *sbufl, *sbufr; int *kpic, *ncl, *ihole, *ncll, *nclr, *irc; ppart = (float *)*gp_ppart; ppbuff = (float *)*gp_ppbuff; sbufl = (float *)*gp_sbufl; sbufr = (float *)*gp_sbufr; kpic = (int *)*gp_kpic; ncl = (int *)*gp_ncl; ihole = (int *)*gp_ihole; ncll = (int *)*gp_ncll; nclr = (int *)*gp_nclr; irc = (int *)*gp_irc; cgpupppord2la(ppart,ppbuff,sbufl,sbufr,kpic,ncl,ihole,ncll,nclr, *noff,*nyp,*idimp,*nppmx,*nx,*ny,*mx,*my,*mx1,*myp1, *npbmx,*ntmax,*nbmax,irc); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpupppord2lb_(unsigned long *gp_ppart, unsigned long *gp_ppbuff, unsigned long *gp_rbufl, unsigned long *gp_rbufr, unsigned long *gp_kpic, unsigned long *gp_ncl, unsigned long *gp_ihole, unsigned long *gp_mcll, unsigned long *gp_mclr, int *idimp, int *nppmx, int *mx1, int *myp1, int *npbmx, int *ntmax, int *nbmax, unsigned long *gp_irc) { float *ppart, *ppbuff, *rbufl, *rbufr; int *kpic, *ncl, *ihole, *mcll, *mclr, *irc; ppart = (float *)*gp_ppart; ppbuff = (float *)*gp_ppbuff; rbufl = (float *)*gp_rbufl; rbufr = (float *)*gp_rbufr; kpic = (int *)*gp_kpic; ncl = (int *)*gp_ncl; ihole = (int *)*gp_ihole; mcll = (int *)*gp_mcll; mclr = (int *)*gp_mclr; irc = (int *)*gp_irc; cgpupppord2lb(ppart,ppbuff,rbufl,rbufr,kpic,ncl,ihole,mcll,mclr, *idimp,*nppmx,*mx1,*myp1,*npbmx,*ntmax,*nbmax,irc); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppois22t_(unsigned long *gp_qt, unsigned long *gp_fxyt, unsigned long *gp_ffct, unsigned long *gp_we, int *nx, int *ny, int *kstrt, int *nyv, int *kxp1, int *nyhd) { float2 *qt, *fxyt, *ffct; float *we; qt = (float2 *)*gp_qt; fxyt = (float2 *)*gp_fxyt; ffct = (float2 *)*gp_ffct; we = (float *)*gp_we; cgpuppois22t(qt,fxyt,ffct,we,*nx,*ny,*kstrt,*nyv,*kxp1,*nyhd); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuwppfft2rcsx_(unsigned long *gp_f, unsigned long *gp_bsm, int *isign, unsigned long *gp_mixup, unsigned long *gp_sct, int *indx, int *indy, int *kstrt, int *nvp, int *kxp1, int *kyp, int *nxhd, int *kypd, int *nxhyd, int *nxyhd) { float2 *f, *bsm, *sct; int *mixup; f = (float2 *)*gp_f; bsm = (float2 *)*gp_bsm; mixup = (int *)*gp_mixup; sct = (float2 *)*gp_sct; cgpuwppfft2rcsx(f,bsm,*isign,mixup,sct,*indx,*indy,*kstrt,*nvp,*kxp1, *kyp,*nxhd,*kypd,*nxhyd,*nxyhd); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuwppfft2rcsy_(unsigned long *gp_g, unsigned long *gp_brm, int *isign, unsigned long *gp_mixup, unsigned long *gp_sct, int *indx, int *indy, int *kstrt, int *nvp, int *kxp1, int *kyp, int *nyd, int *nxhyd, int *nxyhd) { float2 *g, *brm, *sct; int *mixup; g = (float2 *)*gp_g; brm = (float2 *)*gp_brm; mixup = (int *)*gp_mixup; sct = (float2 *)*gp_sct; cgpuwppfft2rcsy(g,brm,*isign,mixup,sct,*indx,*indy,*kstrt,*nvp,*kxp1, *kyp,*nyd,*nxhyd,*nxyhd); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuwppfft2rcsxn_(unsigned long *gp_fn, unsigned long *gp_bsm, int *isign, unsigned long *gp_mixup, unsigned long *gp_sct, int *indx, int *indy, int *ndim, int *kstrt, int *nvp, int *kxp1, int *kyp, int *nxhd, int *kypd, int *nxhyd, int *nxyhd) { float2 *fn, *bsm, *sct; int *mixup; fn = (float2 *)*gp_fn; bsm = (float2 *)*gp_bsm; mixup = (int *)*gp_mixup; sct = (float2 *)*gp_sct; cgpuwppfft2rcsxn(fn,bsm,*isign,mixup,sct,*indx,*indy,*ndim,*kstrt, *nvp,*kxp1,*kyp,*nxhd,*kypd,*nxhyd,*nxyhd); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuwppfft2rcsyn_(unsigned long *gp_gn, unsigned long *gp_brm, int *isign, unsigned long *gp_mixup, unsigned long *gp_sct, int *indx, int *indy, int *ndim, int *kstrt, int *nvp, int *kxp1, int *kyp, int *nyd, int *nxhyd, int *nxyhd) { float2 *gn, *brm, *sct; int *mixup; gn = (float2 *)*gp_gn; brm = (float2 *)*gp_brm; mixup = (int *)*gp_mixup; sct = (float2 *)*gp_sct; cgpuwppfft2rcsyn(gn,brm,*isign,mixup,sct,*indx,*indy,*ndim,*kstrt, *nvp,*kxp1,*kyp,*nyd,*nxhyd,*nxyhd); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppltpose_(unsigned long *gp_f, unsigned long *gp_g, int *nx, int *ny, int *kxp, int *kyp, int *kstrt, int *nxv, int *nyv) { float2 *f, *g; f = (float2 *)*gp_f; g = (float2 *)*gp_g; cgpuppltpose(f,g,*nx,*ny,*kxp,*kyp,*kstrt,*nxv,*nyv); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpuppltposen_(unsigned long *gp_fn, unsigned long *gp_gn, int *nx, int *ny, int *kxp, int *kyp, int *kstrt, int *ndim, int *nxv, int *nyv) { float2 *fn, *gn; fn = (float2 *)*gp_fn; gn = (float2 *)*gp_gn; cgpuppltposen(fn,gn,*nx,*ny,*kxp,*kyp,*kstrt,*ndim,*nxv,*nyv); return; } /*--------------------------------------------------------------------*/ extern "C" void cgpusum2_(unsigned long *gp_a, unsigned long *gp_sa, int *nx) { float *a, *sa; a = (float *)*gp_a; sa = (float *)*gp_sa; cgpusum2(a,sa,*nx); return; }
the_stack
#include <cublas.h> #define TRAINING_SIZE 5000 #define TEST_SIZE 1000 #define IMAGE_SIZE 784 float ONE=1.0; float ZERO=0.0; float *BIASES; float *WEIGHTS; float *D__BIASES; float *D__WEIGHTS; float *NABLA_B; float *NABLA_W; float *D__NABLA_B; float *D__NABLA_W; float *DELTA_NABLA_B; float *DELTA_NABLA_W; float *D__DELTA_NABLA_B; float *D__DELTA_NABLA_W; int MINI_BATCH_SIZE; int TBS; int TWS; float ETA; int NUM_LAYERS; int *SIZES; float **ACTIVATIONS; float **ZS; float *ACTIVATIONS_2D; float **D__ACTIVATIONS_2D_TRAINING; float **D__ZS_2D_TRAINING; float **D__ACTIVATIONS_2D_TEST; float **D__ZS_2D_TEST; float **TRAINING_DATA_X; int *TRAINING_DATA_Y; float *D__TRAINING_DATA_X_2D; float **TEST_DATA_X; int *TEST_DATA_Y; float *D__TEST_DATA_X_2D; float **D__TEST_DATA_X; int I,J; __global__ void kernelUpdateBiases(float *nabla_b,float *biases,float eta,float mini_batch_size) { float rate=eta/mini_batch_size; biases[threadIdx.x]-=rate*nabla_b[threadIdx.x]; } __global__ void kernelUpdateWeights(float *nabla_w,float *weights,int tws,float eta,float mini_batch_size) { float rate=eta/mini_batch_size; if ((blockIdx.x*blockDim.x+threadIdx.x)<tws) { weights[blockIdx.x*blockDim.x+threadIdx.x]-=rate*nabla_w[blockIdx.x*blockDim.x+threadIdx.x]; } } __global__ void kernelUpdateNablaB(float *nabla_b,float *delta_nabla_b) { nabla_b[threadIdx.x]+=delta_nabla_b[threadIdx.x]; } __global__ void kernelUpdateNablaW(float *nabla_w,float *delta_nabla_w,int tws) { if ((blockIdx.x*blockDim.x+threadIdx.x)<tws) { nabla_w[blockIdx.x*blockDim.x+threadIdx.x]+=delta_nabla_w[blockIdx.x*blockDim.x+threadIdx.x]; } } __global__ void kernelInitNablaB(float *nabla_b) { nabla_b[threadIdx.x]=0.0; } __global__ void kernelInitNablaW(float *nabla_w,int tws) { if ((blockIdx.x*blockDim.x+threadIdx.x)<tws) { nabla_w[blockIdx.x*blockDim.x+threadIdx.x]=0.0; } } __global__ void kernelBackprop3a(float *delta_nabla_b,int b_off,int bound,int b_off_old,float *weights,int w_off_old) { int j; delta_nabla_b[b_off+threadIdx.x]=0.0; for (j=0; j<bound; j++) { delta_nabla_b[b_off+threadIdx.x]+=delta_nabla_b[b_off_old+j]*weights[w_off_old+(j*blockDim.x)+threadIdx.x]; } } __global__ void kernelBackprop3b(float *delta_nabla_b,int b_off,float *zs) { delta_nabla_b[b_off+threadIdx.x]*=(1.0/(1.0+expf(-zs[threadIdx.x])))*(1.0-(1.0/(1.0+expf(-zs[threadIdx.x])))); } __global__ void kernelBackprop1(float *delta_nabla_w,int w_off,float *activations,float *delta_nabla_b,int b_off) { delta_nabla_w[w_off+(blockIdx.x*blockDim.x)+threadIdx.x]=activations[threadIdx.x]*delta_nabla_b[b_off+blockIdx.x]; //delta_nabla_w[w_off+(threadIdx.x*gridDim.x)+blockIdx.x]=activations[threadIdx.x]*delta_nabla_b[b_off+blockIdx.x]; } __global__ void kernelBackprop2(float *delta_nabla_b,int b_off,float *activations,float *zs,float y) { int y_[10]={0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; y_[(int)(y+0.1)]=1.0; delta_nabla_b[b_off+threadIdx.x]=(activations[threadIdx.x]-y_[threadIdx.x])*(1.0/(1.0+expf(-zs[threadIdx.x])))*(1.0-(1.0/(1.0+expf(-zs[threadIdx.x])))); } __global__ void kernelFeedForward1(float *zs,int bound2,float *weights,int w_off,float *activations1) { int i; zs[threadIdx.x]=0.0; for (i=0; i<bound2; i++) { zs[threadIdx.x]+=weights[w_off+(threadIdx.x*bound2)+i]*activations1[i]; } } __global__ void kernelFeedForward1b(float *zs,int bound,float *weights,int w_off,float *activations) { int i; zs[(blockIdx.x*blockDim.x)+threadIdx.x]=0.0; for (i=0; i<bound; i++) { zs[(blockIdx.x*blockDim.x)+threadIdx.x]+=weights[w_off+(threadIdx.x*bound)+i]*activations[(blockIdx.x*bound)+i]; } } __global__ void kernelFeedForward3(float *zs,float *biases,int b_off,float *activations) { zs[(blockIdx.x*blockDim.x)+threadIdx.x]+=biases[b_off+threadIdx.x]; activations[(blockIdx.x*blockDim.x)+threadIdx.x]=1.0/(1.0+expf(-zs[(blockIdx.x*blockDim.x)+threadIdx.x])); } __global__ void kernelFeedForward2(float *zs,float *biases,int b_off,float *activations) { zs[threadIdx.x]+=biases[b_off+threadIdx.x]; activations[threadIdx.x]=1.0/(1.0+expf(-zs[threadIdx.x])); } void cublasCheck(cublasStatus_t status, const char *fn_name) { if(status != CUBLAS_STATUS_SUCCESS) { fprintf(stderr,"cublas error returned %d from %s. exiting...\n", status, fn_name); exit(EXIT_FAILURE); } } float normal() { int i; float uniform=0.0; for (i=0; i<12; i++) { uniform+=(float)rand()/(float)RAND_MAX; } return uniform-6.0; } float sigmoid(float z) { return 1.0/(1.0+expf(-z)); } float sigmoid_prime(float z) { return sigmoid(z)*(1.0-sigmoid(z)); } void backprop(float y) { int i,k; int b_offset=0,w_offset=0,w_offset_old,b_offset_old; if (I==0) { D__ACTIVATIONS_2D_TRAINING[0]=&D__TRAINING_DATA_X_2D[J*MINI_BATCH_SIZE*IMAGE_SIZE]; // Feed forward using all training sets in mini batch for (k=1; k<NUM_LAYERS; k++) { cublasSgemm('t','n',SIZES[k],MINI_BATCH_SIZE,SIZES[k-1],1,&D__WEIGHTS[w_offset],SIZES[k-1],D__ACTIVATIONS_2D_TRAINING[k-1],SIZES[k-1],0,D__ZS_2D_TRAINING[k-1],SIZES[k]); {dim3 dimBlock(SIZES[k],1,1); dim3 dimGrid(MINI_BATCH_SIZE,1,1); kernelFeedForward3<<< dimGrid, dimBlock >>>(D__ZS_2D_TRAINING[k-1],D__BIASES,b_offset,D__ACTIVATIONS_2D_TRAINING[k]);} b_offset+=SIZES[k]; w_offset+=SIZES[k-1]*SIZES[k]; } } b_offset=0; w_offset=0; for (i=1; i<(NUM_LAYERS-1); i++) { b_offset+=SIZES[i]; w_offset+=SIZES[i-1]*SIZES[i]; } {dim3 dimBlock(SIZES[NUM_LAYERS-1],1,1); dim3 dimGrid(1,1,1); kernelBackprop2<<< dimGrid, dimBlock >>>(D__DELTA_NABLA_B,b_offset,&D__ACTIVATIONS_2D_TRAINING[NUM_LAYERS-1][I*SIZES[NUM_LAYERS-1]], &D__ZS_2D_TRAINING[NUM_LAYERS-2][I*SIZES[NUM_LAYERS-1]],y);} {dim3 dimBlock(SIZES[NUM_LAYERS-2],1,1); dim3 dimGrid(SIZES[NUM_LAYERS-1],1,1); kernelBackprop1<<< dimGrid, dimBlock >>>(D__DELTA_NABLA_W,w_offset,&D__ACTIVATIONS_2D_TRAINING[NUM_LAYERS-2][I*SIZES[NUM_LAYERS-2]],D__DELTA_NABLA_B,b_offset);} for (k=2; k<NUM_LAYERS; k++) { b_offset_old=b_offset; b_offset-=SIZES[NUM_LAYERS-k]; w_offset_old=w_offset; w_offset-=SIZES[NUM_LAYERS-k]*SIZES[NUM_LAYERS-k-1]; {dim3 dimBlock(SIZES[NUM_LAYERS-k],1,1); dim3 dimGrid(1,1,1); kernelBackprop3a<<< dimGrid, dimBlock >>>(D__DELTA_NABLA_B,b_offset,SIZES[NUM_LAYERS-k+1],b_offset_old,D__WEIGHTS,w_offset_old);} {dim3 dimBlock(SIZES[NUM_LAYERS-k],1,1); dim3 dimGrid(1,1,1); kernelBackprop3b<<< dimGrid, dimBlock >>>(D__DELTA_NABLA_B,b_offset,&D__ZS_2D_TRAINING[NUM_LAYERS-k-1][I*SIZES[NUM_LAYERS-k]]);} {dim3 dimBlock(SIZES[NUM_LAYERS-k-1],1,1); dim3 dimGrid(SIZES[NUM_LAYERS-k],1,1); kernelBackprop1<<< dimGrid, dimBlock >>>(D__DELTA_NABLA_W,w_offset,&D__ACTIVATIONS_2D_TRAINING[NUM_LAYERS-k-1][I*SIZES[NUM_LAYERS-k-1]],D__DELTA_NABLA_B,b_offset);} } } void update_mini_batch(int *mini_batch_y) { int i; {dim3 dimBlock(TBS,1,1); dim3 dimGrid(1,1,1); kernelInitNablaB<<< dimGrid, dimBlock >>>(D__NABLA_B);} {dim3 dimBlock(1024,1,1); dim3 dimGrid((TWS/1024)+1,1,1); kernelInitNablaW<<< dimGrid, dimBlock >>>(D__NABLA_W,TWS);} for (i=0; i<MINI_BATCH_SIZE; i++) { I=i; backprop(mini_batch_y[i]); cublasSaxpy(TBS,1,D__DELTA_NABLA_B,1,D__NABLA_B,1); cublasSaxpy(TWS,1,D__DELTA_NABLA_W,1,D__NABLA_W,1); } cublasSaxpy(TBS,-(ETA/MINI_BATCH_SIZE),D__NABLA_B,1,D__BIASES,1); cublasSaxpy(TWS,-(ETA/MINI_BATCH_SIZE),D__NABLA_W,1,D__WEIGHTS,1); } void shuffle(float **d__x, float **x, int *y, int n) { int i,swap,itmp; float *ftmp; for (i=n-1; i>0; i--) { swap=rand()/(RAND_MAX/(i+1)+1); ftmp=d__x[swap]; d__x[swap]=d__x[i]; d__x[i]=ftmp; ftmp=x[swap]; x[swap]=x[i]; x[i]=ftmp; itmp=y[swap]; y[swap]=y[i]; y[i]=itmp; } } #ifdef __DEVICE_EMULATION__ #define __SYNC __syncthreads(); #else #define __SYNC ; #endif using namespace std; // **************************************************************************** // Function: addBenchmarkSpecOptions // // Purpose: // Add benchmark specific options parsing // // Arguments: // op: the options parser / parameter database // // Returns: nothing // // Programmer: Kyle Spafford // Creation: August 13, 2009 // // Modifications: // // **************************************************************************** void addBenchmarkSpecOptions(OptionParser &op) { ; } // **************************************************************************** // Function: RunBenchmark // // Purpose: // Executes the neural net benchmark // // Arguments: // resultDB: results from the benchmark are stored in this db // op: the options parser / parameter database // // Returns: nothing, results are stored in resultDB // // Programmer: Mitch Horton // Creation: December 1st, 2014 // // Modifications: // // **************************************************************************** void RunBenchmark(ResultDatabase &resultDB, OptionParser &op) { long i,j; NUM_LAYERS=3; SIZES=(int*)malloc(NUM_LAYERS*sizeof(int)); SIZES[0]=784; SIZES[1]=30; SIZES[2]=10; int num_epochs=10; MINI_BATCH_SIZE=10; ETA=3.0; float percent_correct; //printf("%d %d %f\n",num_epochs,MINI_BATCH_SIZE,ETA); FILE *f_training_data_x = fopen("nn_data/training_data_x","r"); FILE *f_training_data_y = fopen("nn_data/training_data_y","r"); FILE *f_test_data_x = fopen("nn_data/test_data_x","r"); FILE *f_test_data_y = fopen("nn_data/test_data_y","r"); if(f_training_data_x == NULL) { cout<<"Input training file not found - please check data directory!"<<endl; return; } TRAINING_DATA_X=(float**)malloc(TRAINING_SIZE*sizeof(float*)); for (i=0; i<TRAINING_SIZE; i++) { TRAINING_DATA_X[i] = (float*)malloc(IMAGE_SIZE*sizeof(float)); } CUDA_SAFE_CALL(cudaMalloc((void**)&D__TRAINING_DATA_X_2D,TRAINING_SIZE*IMAGE_SIZE*sizeof(float))); TEST_DATA_X=(float**)malloc(10000*sizeof(float*)); for (i=0; i<TEST_SIZE; i++) { TEST_DATA_X[i] = (float*)malloc(IMAGE_SIZE*sizeof(float)); } CUDA_SAFE_CALL(cudaMalloc((void**)&D__TEST_DATA_X_2D,TEST_SIZE*IMAGE_SIZE*sizeof(float))); D__TEST_DATA_X=(float**)malloc(TEST_SIZE*sizeof(float*)); for (i=0; i<TEST_SIZE; i++) { CUDA_SAFE_CALL(cudaMalloc((void**)&D__TEST_DATA_X[i],IMAGE_SIZE*sizeof(float))); } TRAINING_DATA_Y = (int*)malloc(TRAINING_SIZE*sizeof(int)); TEST_DATA_Y = (int*)malloc(TEST_SIZE*sizeof(int)); ACTIVATIONS=(float**)malloc(NUM_LAYERS*sizeof(float*)); ZS =(float**)malloc((NUM_LAYERS-1)*sizeof(float*)); D__ACTIVATIONS_2D_TRAINING=(float**)malloc(NUM_LAYERS*sizeof(float*)); D__ZS_2D_TRAINING =(float**)malloc((NUM_LAYERS-1)*sizeof(float*)); D__ACTIVATIONS_2D_TEST=(float**)malloc(NUM_LAYERS*sizeof(float*)); D__ZS_2D_TEST =(float**)malloc((NUM_LAYERS-1)*sizeof(float*)); for (i=1; i<NUM_LAYERS; i++) { CUDA_SAFE_CALL(cudaMalloc((void**)&D__ACTIVATIONS_2D_TRAINING[i],SIZES[i]*MINI_BATCH_SIZE*sizeof(float))); } for (i=1; i<NUM_LAYERS; i++) { CUDA_SAFE_CALL(cudaMalloc((void**)&D__ACTIVATIONS_2D_TEST[i],SIZES[i]*TEST_SIZE*sizeof(float))); } ACTIVATIONS_2D=(float*)malloc(SIZES[NUM_LAYERS-1]*TEST_SIZE*sizeof(float)); for (i=1; i<NUM_LAYERS; i++) { CUDA_SAFE_CALL(cudaMalloc((void**)&D__ZS_2D_TRAINING[i-1],SIZES[i]*MINI_BATCH_SIZE*sizeof(float))); } for (i=1; i<NUM_LAYERS; i++) { CUDA_SAFE_CALL(cudaMalloc((void**)&D__ZS_2D_TEST[i-1],SIZES[i]*TEST_SIZE*sizeof(float))); } for (i=1; i<NUM_LAYERS; i++) { ACTIVATIONS[i]=(float*)malloc(SIZES[i]*10*sizeof(float)); } for (i=1; i<NUM_LAYERS; i++) { ZS[i-1]=(float*)malloc(SIZES[i]*10*sizeof(float)); } for (i=0; i<TRAINING_SIZE; i++) { fread(TRAINING_DATA_X[i],sizeof(float),IMAGE_SIZE,f_training_data_x); } fclose(f_training_data_x); for (i=0; i<TEST_SIZE; i++) { fread(TEST_DATA_X[i],sizeof(float),IMAGE_SIZE,f_test_data_x); } fclose(f_test_data_x); fread(TRAINING_DATA_Y,sizeof(int),TRAINING_SIZE,f_training_data_y); fclose(f_training_data_y); fread(TEST_DATA_Y,sizeof(int),TEST_SIZE,f_test_data_y); fclose(f_test_data_y); TBS=0; TWS=0; for (i=1; i<NUM_LAYERS; i++) { TBS+=SIZES[i]; TWS+=SIZES[i-1]*SIZES[i]; } BIASES =(float*)malloc(TBS*sizeof(float)); WEIGHTS=(float*)malloc(TWS*sizeof(float)); CUDA_SAFE_CALL(cudaMalloc((void**)&D__BIASES,TBS*sizeof(float))); CUDA_SAFE_CALL(cudaMalloc((void**)&D__WEIGHTS,TWS*sizeof(float))); srand(7777); for (i=0; i<TBS; i++) { BIASES[i]=normal(); } for (i=0; i<TWS; i++) { WEIGHTS[i]=normal(); } NABLA_B =(float*)malloc(TBS*sizeof(float)); NABLA_W=(float*)malloc(TWS*sizeof(float)); DELTA_NABLA_B =(float*)malloc(TBS*sizeof(float)); DELTA_NABLA_W=(float*)malloc(TWS*sizeof(float)); CUDA_SAFE_CALL(cudaMalloc((void**)&D__NABLA_B,TBS*sizeof(float))); CUDA_SAFE_CALL(cudaMalloc((void**)&D__NABLA_W,TWS*sizeof(float))); CUDA_SAFE_CALL(cudaMalloc((void**)&D__DELTA_NABLA_B,TBS*sizeof(float))); CUDA_SAFE_CALL(cudaMalloc((void**)&D__DELTA_NABLA_W,TWS*sizeof(float))); cublasInit(); ////int probSizes[4] = { 1, 8, 48, 96 }; ////int size = probSizes[op.getOptionInt("size")-1]; int iterations = op.getOptionInt("passes"); iterations=2; cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); for (int it = 0; it < iterations; it++) { // Copy inputs to GPU double transferTime = 0.; cudaEventRecord(start, 0); for (i=0; i<TRAINING_SIZE; i++) { CUDA_SAFE_CALL(cudaMemcpy(&D__TRAINING_DATA_X_2D[i*IMAGE_SIZE], TRAINING_DATA_X[i], sizeof(float)*IMAGE_SIZE, cudaMemcpyHostToDevice)); } for (i=0; i<TEST_SIZE; i++) { CUDA_SAFE_CALL(cudaMemcpy(&D__TEST_DATA_X_2D[i*IMAGE_SIZE], TEST_DATA_X[i], sizeof(float)*IMAGE_SIZE, cudaMemcpyHostToDevice)); } for (i=0; i<TEST_SIZE; i++) { CUDA_SAFE_CALL(cudaMemcpy(D__TEST_DATA_X[i], TEST_DATA_X[i], sizeof(float)*IMAGE_SIZE, cudaMemcpyHostToDevice)); } CUDA_SAFE_CALL(cudaMemcpy(TEST_DATA_X[1], &D__TEST_DATA_X_2D[1*IMAGE_SIZE], sizeof(float)*IMAGE_SIZE, cudaMemcpyDeviceToHost)); CUDA_SAFE_CALL(cudaMemcpy(D__BIASES, BIASES, sizeof(float)*TBS, cudaMemcpyHostToDevice)); CUDA_SAFE_CALL(cudaMemcpy(D__WEIGHTS, WEIGHTS, sizeof(float)*TWS, cudaMemcpyHostToDevice)); cudaEventRecord(stop, 0); CUDA_SAFE_CALL(cudaEventSynchronize(stop)); float elapsedTime; cudaEventElapsedTime(&elapsedTime, start, stop); transferTime += elapsedTime * 1.e-3; // convert to seconds cudaEventRecord(start, 0); // loop over epochs for (i=0; i<num_epochs; i++) { //shuffle(D__TRAINING_DATA_X,TRAINING_DATA_X,TRAINING_DATA_Y,TRAINING_SIZE); // loop over mini-batches for (j=0; j<TRAINING_SIZE/MINI_BATCH_SIZE; j++) { J=j; update_mini_batch(&TRAINING_DATA_Y[j*MINI_BATCH_SIZE]); } ///* if (i == (num_epochs-1)) { // test current weights and biases int total_correct=0,highest; long k,b_offset,w_offset; D__ACTIVATIONS_2D_TEST[0]=D__TEST_DATA_X_2D; b_offset=w_offset=0; for (k=1; k<NUM_LAYERS; k++) { cublasSgemm('t','n',SIZES[k],TEST_SIZE,SIZES[k-1],1,&D__WEIGHTS[w_offset],SIZES[k-1],D__ACTIVATIONS_2D_TEST[k-1],SIZES[k-1],0,D__ZS_2D_TEST[k-1],SIZES[k]); {dim3 dimBlock(SIZES[k],1,1); dim3 dimGrid(TEST_SIZE,1,1); kernelFeedForward3<<< dimGrid, dimBlock >>>(D__ZS_2D_TEST[k-1],D__BIASES,b_offset,D__ACTIVATIONS_2D_TEST[k]);} b_offset+=SIZES[k]; w_offset+=SIZES[k-1]*SIZES[k]; } CUDA_SAFE_CALL(cudaMemcpy(ACTIVATIONS_2D, D__ACTIVATIONS_2D_TEST[NUM_LAYERS-1], sizeof(float)*SIZES[NUM_LAYERS-1]*TEST_SIZE, cudaMemcpyDeviceToHost)); for (j=0; j<TEST_SIZE; j++) { highest=0; for (k=1; k<SIZES[NUM_LAYERS-1]; k++) { if (ACTIVATIONS_2D[(j*SIZES[NUM_LAYERS-1])+k]>ACTIVATIONS_2D[(j*SIZES[NUM_LAYERS-1])+highest]) { highest=k; } } if (highest==TEST_DATA_Y[j]) { total_correct++; } } printf("%d %d %d\n",(int)i,total_correct,TEST_SIZE); percent_correct=(float)(total_correct)/(float)(TEST_SIZE); } //*/ } cudaEventRecord(stop, 0); CUDA_SAFE_CALL(cudaEventSynchronize(stop)); cudaEventElapsedTime(&elapsedTime, start, stop); double kernelTime = elapsedTime * 1.e-3; // Test to make sure neural net reached threshold; if not, return if (percent_correct<.8) { return; } char atts[1024]; sprintf(atts, "%d training_sets", TRAINING_SIZE*num_epochs); resultDB.AddResult("Learning-Rate", atts, "training_sets/s", TRAINING_SIZE*num_epochs / kernelTime); resultDB.AddResult("Learning-Rate_PCIe", atts, "training_sets/s", TRAINING_SIZE*num_epochs / (transferTime+kernelTime)); } // Clean up free(BIASES); free(WEIGHTS); free(NABLA_B); free(NABLA_W); free(DELTA_NABLA_B); free(DELTA_NABLA_W); free(ACTIVATIONS_2D); free(SIZES); free(TEST_DATA_Y); free(TRAINING_DATA_Y); for (i=0; i<NUM_LAYERS; i++) { free(ACTIVATIONS[i]); } free(ACTIVATIONS); for (i=0; i<(NUM_LAYERS-1); i++) { free(ZS[i]); } free(ZS); for (i=1; i<NUM_LAYERS; i++) { CUDA_SAFE_CALL(cudaFree(D__ACTIVATIONS_2D_TRAINING[i])); } free(D__ACTIVATIONS_2D_TRAINING); for (i=1; i<(NUM_LAYERS-1); i++) { CUDA_SAFE_CALL(cudaFree(D__ZS_2D_TEST[i])); } free(D__ZS_2D_TEST); for (i=1; i<(NUM_LAYERS-1); i++) { CUDA_SAFE_CALL(cudaFree(D__ZS_2D_TRAINING[i])); } free(D__ZS_2D_TRAINING); for (i=0; i<TEST_SIZE; i++) { CUDA_SAFE_CALL(cudaFree(D__TEST_DATA_X[i])); } free(D__TEST_DATA_X); for (i=1; i<NUM_LAYERS; i++) { CUDA_SAFE_CALL(cudaFree(D__ACTIVATIONS_2D_TEST[i])); } free(D__ACTIVATIONS_2D_TEST); for (i=0; i<TRAINING_SIZE; i++) { free(TRAINING_DATA_X[i]); } free(TRAINING_DATA_X); for (i=0; i<TEST_SIZE; i++) { free(TEST_DATA_X[i]); } free(TEST_DATA_X); CUDA_SAFE_CALL(cudaFree(D__BIASES)); CUDA_SAFE_CALL(cudaFree(D__WEIGHTS)); CUDA_SAFE_CALL(cudaFree(D__NABLA_B)); CUDA_SAFE_CALL(cudaFree(D__NABLA_W)); CUDA_SAFE_CALL(cudaFree(D__DELTA_NABLA_B)); CUDA_SAFE_CALL(cudaFree(D__DELTA_NABLA_W)); CUDA_SAFE_CALL(cudaFree(D__TRAINING_DATA_X_2D)); CUDA_SAFE_CALL(cudaFree(D__TEST_DATA_X_2D)); CUDA_SAFE_CALL(cudaEventDestroy(start)); CUDA_SAFE_CALL(cudaEventDestroy(stop)); }
the_stack
#define NUM_RND_BLOCKS 96 #define NUM_RND_THREADS_PER_BLOCK 128 #define NUM_RND_STREAMS (NUM_RND_BLOCKS * NUM_RND_THREADS_PER_BLOCK) /* * Defines for getting the values at the lower and upper 32 bits * of a 64-bit number. */ #define LOW_BITS(x) ((x) & 0xffffffff) #define HIGH_BITS(x) ((x) >> 32) /* * Number of iterations to run random number generator upon initialization. */ #define NUM_RND_BURNIN 100 #define COPY_BLOCK_SIZE 16 # #define NUM_VECTOR_OP_BLOCKS 4096 #define NUM_VECTOR_OP_THREADS_PER_BLOCK 512 #define NUM_VECTOR_OP_LOOPS_PER_THREAD 1 #define PI 3.1415926535897932f #ifndef DIVUP #define DIVUP(x, y) (((x) + (y) - 1) / (y)) #endif #ifndef MIN #define MIN(x,y) ((x < y) ? x : y) #endif #ifndef MAX #define MAX(x,y) ((x > y) ? x : y) #endif __device__ float device_val; __device__ void reduceToSumLocal(float* sdata, unsigned int tid); __device__ void reduceToMax(float* sdata, unsigned int tid); __global__ void kSeedRandom(unsigned int* randMults, unsigned long long* randWords, unsigned int seed); __global__ void kRandomUniform(unsigned int* randMults, unsigned long long* randWords, float* gData, unsigned int numElements); __global__ void kRandomGaussian(unsigned int* rndMults, unsigned long long* rndWords, float* gData, unsigned int numElements); __global__ void kRandomDropout(unsigned int* randMults, unsigned long long* randWords, float* gData, unsigned int numElements, float dropprob, float val, float scale); __global__ void kRandomGaussianDropout(unsigned int* rndMults, unsigned long long* rndWords, float* gData, unsigned int numElements, float scale); __global__ void kSampleBernoulli(unsigned int* randMults, unsigned long long* randWords, float* gData, float* target, unsigned int numElements); __global__ void kSampleBernoulliTanh(unsigned int* randMults, unsigned long long* randWords, float* gData, float* target, unsigned int numElements); __global__ void kSamplePoisson(unsigned int* randMults, unsigned long long* randWords, float* gData, float* target, unsigned int numElements); __global__ void kSampleGaussian(unsigned int* randMults, unsigned long long* randWords, float* gData, float* target, unsigned int numElements, float mult); __global__ void kPerturbProb(unsigned int* randMults, unsigned long long* randWords, float* gData, float* target, unsigned int numElements); __global__ void kPerturbEnergy(unsigned int* randMults, unsigned long long* randWords, float* gData, float* target, unsigned int numElements); __global__ void kGetRowSlice(float* source, float* target, int start, int end, int width, int height); __global__ void kTranspose(float *odata, float *idata, int width, int height); __global__ void kTransposeBig(float *odata, float *idata, int height, int width); __global__ void kSetRowSlice(float* source, float* target, int start, int end, int width, int height); __global__ void kLessThan(float* mat1, float* mat2, float* target, unsigned int len); __global__ void kLessThanEq(float* mat1, float* mat2, float* target, unsigned int len); __global__ void kLessThanScalar(float* mat, float val, float* target, unsigned int len); __global__ void kLessThanEqScalar(float* mat, float val, float* target, unsigned int len); __global__ void kGreaterThan(float* mat1, float* mat2, float* target, unsigned int len); __global__ void kGreaterThanEq(float* mat1, float* mat2, float* target, unsigned int len); __global__ void kGreaterThanScalar(float* mat, float val, float* target, unsigned int len); __global__ void kGreaterThanEqScalar(float* mat, float val, float* target, unsigned int len); __global__ void kUpperBound(float* mat1, float* mat2, float* target, unsigned int len); __global__ void kLowerBound(float* mat1, float* mat2, float* target, unsigned int len); __global__ void kUpperBoundScalar(float* mat, float val, float* target, unsigned int len); __global__ void kLowerBoundScalar(float* mat, float val, float* target, unsigned int len); __global__ void kUpperBoundModScalar(float* mat, float val, float* target, unsigned int len); __global__ void kMaxColumnwise(float* mat, float* target, unsigned int width, unsigned int height); __global__ void kArgMaxColumnwise(float* mat, float* target, unsigned int width, unsigned int height); __global__ void kSumColumnwise(float* mat, float* target, unsigned int width, unsigned int height, float mult, float p); __global__ void kSumAll(float* mat, float* target, unsigned int len, unsigned int len_per_block, unsigned int left_over); __global__ void kSumRowwise(float* mat, float* target, unsigned int width, unsigned int height, float mult, float p); __global__ void kSqSumColumnwise(float* mat, float* target, unsigned int width, unsigned int height, float mult, float p); __global__ void kSqSumRowwise(float* mat, float* target, unsigned int width, unsigned int height, float mult, float p); __global__ void kNormLimitColumnwise(float* mat, float* target, float norm, unsigned int width, unsigned int height, int constraint); __global__ void kNormalizeColumnwise(float* mat, float* target, unsigned int width, unsigned int height); __global__ void kNormLimitRowwise(float* mat, float* target, float norm, unsigned int width, unsigned int height, int constraint); __global__ void kSumAll(float* mat, unsigned int len); __global__ void kSparseDot(int m, int n, int k, float *data, int* indptr, int* indices, float *dense_data, float* target, float beta, float alpha); __global__ void kSign(float* mat, float* target, unsigned int len); __global__ void kApplySigmoid(float* mat, float* target, unsigned int len); __global__ void kApplySin(float* mat, float* target, unsigned int len); __global__ void kApplyCos(float* mat, float* target, unsigned int len); __global__ void kApplyTanh(float* mat, float* target, unsigned int len); __global__ void kApplyAbs(float* mat, float* target, unsigned int len); __global__ void kApplyLog1PlusExp(float* mat, float* target, unsigned int len); __global__ void kApplyLog1PlusExpExact(float* mat, float* target, unsigned int len); __global__ void kSquashRelu(float* mat, float* target, unsigned int len, float lambda); __global__ void kLog(float* mat, float* target, unsigned int len, float tiny); __global__ void kExp(float* mat, float* target, unsigned int len); __global__ void kCeil(float* mat, float* target, unsigned int len); __global__ void kFloor(float* mat, float* target, unsigned int len); __global__ void kSqrt(float* mat, float* target, unsigned int len); __global__ void kPow(float* mat, float pow, float* target, unsigned int len); __global__ void kPowMatrix(float* mat, float* pow, float* target, unsigned int len); __global__ void kCrossEntropy(float* mat, float* p, float* target, unsigned int len, float tiny); __global__ void kCrossEntropyBernoulli(float* mat, float* p, float* target, unsigned int len, float tiny); __global__ void kCorrectPreds(float* mat, float* p, float* target, unsigned int len, float cutoff); __global__ void kReciprocal(float* mat, float* target, unsigned int len); __global__ void kAddDiagonal(float* mat, float* vec, float* tgtMat, unsigned int width); __global__ void kAddDiagonalScalar(float* mat, float val, float* tgtMat, unsigned int width); __global__ void kMultDiagonal(float* mat, float* vec, float* tgtMat, unsigned int width); __global__ void kMultDiagonalScalar(float* mat, float val, float* tgtMat, unsigned int width); __global__ void kAddColVector(float* mat, float* vec, float* tgtMat, unsigned int width, unsigned int height); __global__ void kAddRowVector(float* mat, float* vec, float* tgtMat, unsigned int width, unsigned int height); __global__ void kAddColMult(float* mat, float* vec, float* tgtMat, float mult, unsigned int width, unsigned int height); __global__ void kAddRowMult(float* mat, float* vec, float* tgtMat, float mult, unsigned int width, unsigned int height); __global__ void kAddToEachPixel(float* mat1, float* mat2, float* tgtMat, float mult, unsigned int width, unsigned int height, unsigned int num_pix); __global__ void kMultByColVector(float* mat, float* vec, float* tgtMat, unsigned int width, unsigned int height); __global__ void kMultByRowVector(float* mat, float* vec, float* tgtMat, unsigned int width, unsigned int height); __global__ void kDivByColVector(float* mat, float* vec, float* tgtMat, unsigned int width, unsigned int height); __global__ void kDivByRowVector(float* mat, float* vec, float* tgtMat, unsigned int width, unsigned int height); __global__ void kAddMultSign(float* a, float* b, unsigned int numEls, float mult); __global__ void kAdd(float* a, float* b, float* dest, unsigned int numEls); __global__ void kSubtract(float* a, float* b, float* dest, unsigned int numEls); __global__ void kMult(float* a, float* b, float* dest, unsigned int numEls, float scale_targets); __global__ void kLogisticDeriv(float* a, float* b, float* dest, unsigned int numEls); __global__ void kLogisticGrad(float* mat, float* targets, float* out_grad, unsigned int numEls); __global__ void kSinDeriv(float* a, float* b, float* dest, unsigned int numEls); __global__ void kCosDeriv(float* a, float* b, float* dest, unsigned int numEls); __global__ void kTanhDeriv(float* a, float* b, float* dest, unsigned int numEls); __global__ void kRectifiedLinearDeriv(float* a, float* b, float* dest, unsigned int numEls); __global__ void kRectifiedLinearSmoothDeriv(float* a, float* b, float* dest, unsigned int numEls); __global__ void kDivide(float* a, float* b, float* dest, unsigned int numEls); __global__ void kMultScalar(float* mat, float alpha, float* dest, unsigned int len, float scale_targets); __global__ void kAssignScalar(float* dest, float alpha, unsigned int len); __global__ void kDivideScalar(float* mat, float alpha, float* dest, unsigned int len); __global__ void kAddScalar(float* a, float alpha, float* dest, unsigned int numEls); __global__ void kSelectRows(float* source, float* target, float* indices, int nRowIs, int nCols, int nSourceRows); __global__ void kSetSelectedRows(float* target, float* source, float* indices, int nRowIs, int nCols, int nTargetRows); __global__ void kSwapColumns(float* target, float* source, float* indices1, float* indices2, int cols, int width, int height); __global__ void kShuffleColumns(float* source, float* target, float* indices, int width, int height); __global__ void kGenerateTranslationsBigVarOff(float* source, float* target, float* off_x_arr, float* off_y_arr, int source_w, int target_w, int num_channels); __global__ void kBlockify(float* source, float* target, int numdims, int blocksize); __global__ void kCumsum(float *mat, float *target, float *temp, unsigned int height); __global__ void kChooseMaxColumnwise(float* mat, float* target, unsigned int width, unsigned int height); __global__ void kChooseMaxAndAccumulate(float* mat, float* acc, unsigned int width, unsigned int height); __global__ void kSoftMax(float* mat, float* target, unsigned int width, unsigned int height); __global__ void kSoftMaxOverwrite(float* mat, unsigned int width, unsigned int height); __global__ void kSoftMaxRowMajor(float* mat, unsigned int width, unsigned int height); __global__ void kSoftMaxGrad(float* mat, float* labels, float* target, unsigned int width, unsigned int height); __global__ void kSoftMaxGradCLS(float* mat, int* labels, float* indices, float* target, unsigned int width, unsigned int height); __global__ void kSoftMaxGradRowMajor(float* mat, float* labels, float* target, unsigned int width, unsigned int height); __global__ void kSoftMaxCorrect(float* mat, float* labels, float* target, unsigned int width, unsigned int height); __global__ void kSoftMaxCorrectRowMajor(float* mat, float* labels, float* target, unsigned int width, unsigned int height); __global__ void kSoftMaxCorrectCLS(float* mat, int* labels, float* indices, float* target, unsigned int width, unsigned int height); __global__ void kSoftMaxCrossEntropy(float* mat, float* labels, float* target, unsigned int width, unsigned int height, float tiny); __global__ void kSoftMaxCrossEntropyRowMajor(float* mat, float* labels, float* target, unsigned int width, unsigned int height, float tiny); __global__ void kHingeQuadraticRowMajor(float* mat, float* labels, float* target, unsigned int width, unsigned int height, float margin); __global__ void kHingeLinearRowMajor(float* mat, float* labels, float* target, unsigned int width, unsigned int height, float margin); __global__ void kExpandAndAdd(float* source, float* mat, float* indices, float* target, int width, int height, float mult, int width2); __global__ void kExpand(float* source, float* indices, float* target, int height, int width, int target_width); __global__ void kAccumulateColumns(float* mat, float* indices, float* target, int mat_width, int target_width, int height, float mult, int avg); __global__ void kExtractPatches(float* images, float* patches, float* indices, float* width_offset, float* height_offset, int num_images, int img_width, int img_height, int patch_width, int patch_height, int num_colors); __global__ void kRectifyBoundingBox(float* boxes, float* width_offset, float* height_offset, float* flip, int num_images, int patch_width, int patch_height, int num_locs); __global__ void kExtractPatches2(float* images, float* patches, float* width_offset, float* height_offset, float* flip, int num_images, int img_width, int img_height, int patch_width, int patch_height, int num_colors); __global__ void kAdagrad(float *history, float *grad, float delta, int len); __global__ void kRMSProp(float *history, float *grad, float factor, int len); __global__ void kBoundingBoxLogisticGrad( float* mat, int* bbox, int* label, int* seg, float* indices, float *width_offset, float* height_offset, int size, int width, int height, int depth, float scale_width, float scale_height, float* grad); __global__ void kBoundingBoxSoftMaxGrad( float* mat, int* bbox, int* label, int* seg, float* indices, float *width_offset, float* height_offset, int size, int width, int height, int depth, float scale_width, float scale_height, float* grad); __global__ void kSoftMaxCorrectBoundingBox( float* mat, int* bbox, int* label, int* seg, float* indices, float *width_offset, float* height_offset, int size, int width, int height, int depth, float scale_width, float scale_height, float* target); __global__ void kLogisticCorrectBoundingBox( float* mat, int* bbox, int* label, int* seg, float* indices, float *width_offset, float* height_offset, int size, int width, int height, int depth, float scale_width, float scale_height, float* target, float cutoff); __global__ void kLogisticCorrectNormalized(float* mat, float* targets, float* out, unsigned int height, unsigned int width); __global__ void kLSTMFprop(float *s_in, float* s_out, float* w_diag, float* b, int numcases, int num_lstms, bool init, bool use_relu); __global__ void kLSTMBprop(float *s_in, float* s_out, float* d_in, float* d_out, float* w_diag, int numcases, int num_lstms, bool init, bool use_relu); __global__ void kLSTMOutp(float* s_in, float* s_out, float* d_out, float* dw_diag, float* db, int numcases, int num_lstms, bool init); #endif
the_stack
//needed for optionInputStruct #include "blackScholesAnalyticEngineStructs.cuh" //needed for the kernel(s) to run on the GPU #include "blackScholesAnalyticEngineKernels.cu" #include "blackScholesAnalyticEngineKernelsCpu.cu" #include <stdio.h> #include <math.h> #include <sys/time.h> #include <time.h> #include <cuda.h> #define NUM_DIFF_SETTINGS 37 //function to run the black scholes analytic engine on the gpu void runBlackScholesAnalyticEngine() { int numberOfSamples = 50000000; { int numVals = numberOfSamples;//nSamplesArray[numTime]; optionInputStruct* values = new optionInputStruct[numVals]; for (int numOption = 0; numOption < numVals; numOption++) { if ((numOption % NUM_DIFF_SETTINGS) == 0) { optionInputStruct currVal = { CALL, 40.00, 42.00, 0.08, 0.04, 0.75, 0.35, 5.0975, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 1) { optionInputStruct currVal = { CALL, 100.00, 90.00, 0.10, 0.10, 0.10, 0.15, 0.0205, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 2) { optionInputStruct currVal = { CALL, 100.00, 100.00, 0.10, 0.10, 0.10, 0.15, 1.8734, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 3) { optionInputStruct currVal = { CALL, 100.00, 110.00, 0.10, 0.10, 0.10, 0.15, 9.9413, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 4) { optionInputStruct currVal = { CALL, 100.00, 90.00, 0.10, 0.10, 0.10, 0.25, 0.3150, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 5) { optionInputStruct currVal = { CALL, 100.00, 100.00, 0.10, 0.10, 0.10, 0.25, 3.1217, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 6) { optionInputStruct currVal = { CALL, 100.00, 110.00, 0.10, 0.10, 0.10, 0.25, 10.3556, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 7) { optionInputStruct currVal = { CALL, 100.00, 90.00, 0.10, 0.10, 0.10, 0.35, 0.9474, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 8) { optionInputStruct currVal = { CALL, 100.00, 100.00, 0.10, 0.10, 0.10, 0.35, 4.3693, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 9) { optionInputStruct currVal = { CALL, 100.00, 110.00, 0.10, 0.10, 0.10, 0.35, 11.1381, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 10) { optionInputStruct currVal = { CALL, 100.00, 90.00, 0.10, 0.10, 0.50, 0.15, 0.8069, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 11) { optionInputStruct currVal = { CALL, 100.00, 100.00, 0.10, 0.10, 0.50, 0.15, 4.0232, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 12) { optionInputStruct currVal = { CALL, 100.00, 110.00, 0.10, 0.10, 0.50, 0.15, 10.5769, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 13) { optionInputStruct currVal = { CALL, 100.00, 90.00, 0.10, 0.10, 0.50, 0.25, 2.7026, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 14) { optionInputStruct currVal = { CALL, 100.00, 100.00, 0.10, 0.10, 0.50, 0.25, 6.6997, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 15) { optionInputStruct currVal = { CALL, 100.00, 110.00, 0.10, 0.10, 0.50, 0.25, 12.7857, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 16) { optionInputStruct currVal = { CALL, 100.00, 90.00, 0.10, 0.10, 0.50, 0.35, 4.9329, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 17) { optionInputStruct currVal = { CALL, 100.00, 100.00, 0.10, 0.10, 0.50, 0.35, 9.3679, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 18) { optionInputStruct currVal = { CALL, 100.00, 110.00, 0.10, 0.10, 0.50, 0.35, 15.3086, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 19) { optionInputStruct currVal = { PUT, 100.00, 90.00, 0.10, 0.10, 0.10, 0.15, 9.9210, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 20) { optionInputStruct currVal = { PUT, 100.00, 100.00, 0.10, 0.10, 0.10, 0.15, 1.8734, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 21) { optionInputStruct currVal = { PUT, 100.00, 110.00, 0.10, 0.10, 0.10, 0.15, 0.0408, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 22) { optionInputStruct currVal = { PUT, 100.00, 90.00, 0.10, 0.10, 0.10, 0.25, 10.2155, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 23) { optionInputStruct currVal = { PUT, 100.00, 100.00, 0.10, 0.10, 0.10, 0.25, 3.1217, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 24) { optionInputStruct currVal = { PUT, 100.00, 110.00, 0.10, 0.10, 0.10, 0.25, 0.4551, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 25) { optionInputStruct currVal = { PUT, 100.00, 90.00, 0.10, 0.10, 0.10, 0.35, 10.8479, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 26) { optionInputStruct currVal = { PUT, 100.00, 100.00, 0.10, 0.10, 0.10, 0.35, 4.3693, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 27) { optionInputStruct currVal = { PUT, 100.00, 110.00, 0.10, 0.10, 0.10, 0.35, 1.2376, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 28) { optionInputStruct currVal = { PUT, 100.00, 90.00, 0.10, 0.10, 0.50, 0.15, 10.3192, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 29) { optionInputStruct currVal = { PUT, 100.00, 100.00, 0.10, 0.10, 0.50, 0.15, 4.0232, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 30) { optionInputStruct currVal = { PUT, 100.00, 110.00, 0.10, 0.10, 0.50, 0.15, 1.0646, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 31) { optionInputStruct currVal = { PUT, 100.00, 90.00, 0.10, 0.10, 0.50, 0.25, 12.2149, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 32) { optionInputStruct currVal = { PUT, 100.00, 100.00, 0.10, 0.10, 0.50, 0.25, 6.6997, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 33) { optionInputStruct currVal = { PUT, 100.00, 110.00, 0.10, 0.10, 0.50, 0.25, 3.2734, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 34) { optionInputStruct currVal = { PUT, 100.00, 90.00, 0.10, 0.10, 0.50, 0.35, 14.4452, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 35) { optionInputStruct currVal = { PUT, 100.00, 100.00, 0.10, 0.10, 0.50, 0.35, 9.3679, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 36) { optionInputStruct currVal = { PUT, 100.00, 110.00, 0.10, 0.10, 0.50, 0.35, 5.7963, 1.0e-4}; values[numOption] = currVal; } } // Run GPU code //initialize the arrays //declare and allocate the input and output data on the CPU float* outputVals = (float*)malloc(numVals * sizeof(float)); printf("Number of options: %d\n\n", numVals); long seconds, useconds; float mtimeCpu, mtimeGpu; struct timeval start; gettimeofday(&start, NULL); //declare the data on the GPU optionInputStruct* optionsGpu; float* outputValsGpu; //allocate space for data on GPU cudaMalloc((void**)&optionsGpu, numVals * sizeof(optionInputStruct)); cudaMalloc((void**)&outputValsGpu, numVals * sizeof(float)); //copy the data from the CPU to the GPU cudaMemcpy(optionsGpu, values, numVals * sizeof(optionInputStruct), cudaMemcpyHostToDevice); // setup execution parameters dim3 grid( (numVals + THREAD_BLOCK_SIZE - 1)/THREAD_BLOCK_SIZE, 1, 1); dim3 threads( THREAD_BLOCK_SIZE, 1, 1); getOutValOption <<< dim3(grid), dim3(threads) >>> (optionsGpu, outputValsGpu, numVals); //copy the resulting option values back to the CPU cudaMemcpy(outputVals, outputValsGpu, numVals * sizeof(float), cudaMemcpyDeviceToHost); cudaFree(optionsGpu); cudaFree(outputValsGpu); struct timeval end; gettimeofday(&end, NULL); seconds = end.tv_sec - start.tv_sec; useconds = end.tv_usec - start.tv_usec; mtimeGpu = ((seconds) * 1000 + ((float)useconds)/1000.0) + 0.5f; printf("Run on GPU\n"); printf("Processing time on GPU: %f (ms)\n", mtimeGpu); float totResult = 0.0f; for (int i=0; i<numVals; i++) { totResult += outputVals[i]; } printf("Summation of output prices on GPU: %f\n", totResult); printf("Output price at index %d on GPU: %f\n\n", numVals/2, outputVals[numVals/2]); //run on CPU gettimeofday(&start, NULL); for (size_t numOption=0; numOption < numVals; numOption++) { getOutValOptionCpu(values, outputVals, numOption, numVals); } gettimeofday(&end, NULL); seconds = end.tv_sec - start.tv_sec; useconds = end.tv_usec - start.tv_usec; mtimeCpu = ((seconds) * 1000 + ((float)useconds)/1000.0) + 0.5f; printf("Run on CPU\n"); printf("Processing time on CPU: %f (ms)\n", mtimeCpu); totResult = 0.0f; for (int i=0; i<numVals; i++) { totResult += outputVals[i]; } printf("Summation of output prices on CPU: %f\n", totResult); printf("Output price at index %d on CPU:: %f\n\n", numVals/2, outputVals[numVals/2]); printf("Speedup on GPU: %f\n", mtimeCpu / mtimeGpu); delete [] values; free(outputVals); } } //////////////////////////////////////////////////////////////////////////////// // Program main //////////////////////////////////////////////////////////////////////////////// int main( int argc, char** argv) { runBlackScholesAnalyticEngine(); return 0; }
the_stack
typedef struct { int hashbitlen; unsigned long long databitlen; unsigned long long datasize_in_buffer; uint64_t x[8][2]; unsigned char buffer[64]; } jhHashState; __constant__ unsigned char d_JH256_H0[512]; __constant__ unsigned char d_E8_rc[42][32]; const unsigned char h_JH256_H0[128]={0xeb,0x98,0xa3,0x41,0x2c,0x20,0xd3,0xeb,0x92,0xcd,0xbe,0x7b,0x9c,0xb2,0x45,0xc1,0x1c,0x93,0x51,0x91,0x60,0xd4,0xc7,0xfa,0x26,0x0,0x82,0xd6,0x7e,0x50,0x8a,0x3,0xa4,0x23,0x9e,0x26,0x77,0x26,0xb9,0x45,0xe0,0xfb,0x1a,0x48,0xd4,0x1a,0x94,0x77,0xcd,0xb5,0xab,0x26,0x2,0x6b,0x17,0x7a,0x56,0xf0,0x24,0x42,0xf,0xff,0x2f,0xa8,0x71,0xa3,0x96,0x89,0x7f,0x2e,0x4d,0x75,0x1d,0x14,0x49,0x8,0xf7,0x7d,0xe2,0x62,0x27,0x76,0x95,0xf7,0x76,0x24,0x8f,0x94,0x87,0xd5,0xb6,0x57,0x47,0x80,0x29,0x6c,0x5c,0x5e,0x27,0x2d,0xac,0x8e,0xd,0x6c,0x51,0x84,0x50,0xc6,0x57,0x5,0x7a,0xf,0x7b,0xe4,0xd3,0x67,0x70,0x24,0x12,0xea,0x89,0xe3,0xab,0x13,0xd3,0x1c,0xd7,0x69}; const unsigned char h_E8_rc[42][32]={ {0x72,0xd5,0xde,0xa2,0xdf,0x15,0xf8,0x67,0x7b,0x84,0x15,0xa,0xb7,0x23,0x15,0x57,0x81,0xab,0xd6,0x90,0x4d,0x5a,0x87,0xf6,0x4e,0x9f,0x4f,0xc5,0xc3,0xd1,0x2b,0x40}, {0xea,0x98,0x3a,0xe0,0x5c,0x45,0xfa,0x9c,0x3,0xc5,0xd2,0x99,0x66,0xb2,0x99,0x9a,0x66,0x2,0x96,0xb4,0xf2,0xbb,0x53,0x8a,0xb5,0x56,0x14,0x1a,0x88,0xdb,0xa2,0x31}, {0x3,0xa3,0x5a,0x5c,0x9a,0x19,0xe,0xdb,0x40,0x3f,0xb2,0xa,0x87,0xc1,0x44,0x10,0x1c,0x5,0x19,0x80,0x84,0x9e,0x95,0x1d,0x6f,0x33,0xeb,0xad,0x5e,0xe7,0xcd,0xdc}, {0x10,0xba,0x13,0x92,0x2,0xbf,0x6b,0x41,0xdc,0x78,0x65,0x15,0xf7,0xbb,0x27,0xd0,0xa,0x2c,0x81,0x39,0x37,0xaa,0x78,0x50,0x3f,0x1a,0xbf,0xd2,0x41,0x0,0x91,0xd3}, {0x42,0x2d,0x5a,0xd,0xf6,0xcc,0x7e,0x90,0xdd,0x62,0x9f,0x9c,0x92,0xc0,0x97,0xce,0x18,0x5c,0xa7,0xb,0xc7,0x2b,0x44,0xac,0xd1,0xdf,0x65,0xd6,0x63,0xc6,0xfc,0x23}, {0x97,0x6e,0x6c,0x3,0x9e,0xe0,0xb8,0x1a,0x21,0x5,0x45,0x7e,0x44,0x6c,0xec,0xa8,0xee,0xf1,0x3,0xbb,0x5d,0x8e,0x61,0xfa,0xfd,0x96,0x97,0xb2,0x94,0x83,0x81,0x97}, {0x4a,0x8e,0x85,0x37,0xdb,0x3,0x30,0x2f,0x2a,0x67,0x8d,0x2d,0xfb,0x9f,0x6a,0x95,0x8a,0xfe,0x73,0x81,0xf8,0xb8,0x69,0x6c,0x8a,0xc7,0x72,0x46,0xc0,0x7f,0x42,0x14}, {0xc5,0xf4,0x15,0x8f,0xbd,0xc7,0x5e,0xc4,0x75,0x44,0x6f,0xa7,0x8f,0x11,0xbb,0x80,0x52,0xde,0x75,0xb7,0xae,0xe4,0x88,0xbc,0x82,0xb8,0x0,0x1e,0x98,0xa6,0xa3,0xf4}, {0x8e,0xf4,0x8f,0x33,0xa9,0xa3,0x63,0x15,0xaa,0x5f,0x56,0x24,0xd5,0xb7,0xf9,0x89,0xb6,0xf1,0xed,0x20,0x7c,0x5a,0xe0,0xfd,0x36,0xca,0xe9,0x5a,0x6,0x42,0x2c,0x36}, {0xce,0x29,0x35,0x43,0x4e,0xfe,0x98,0x3d,0x53,0x3a,0xf9,0x74,0x73,0x9a,0x4b,0xa7,0xd0,0xf5,0x1f,0x59,0x6f,0x4e,0x81,0x86,0xe,0x9d,0xad,0x81,0xaf,0xd8,0x5a,0x9f}, {0xa7,0x5,0x6,0x67,0xee,0x34,0x62,0x6a,0x8b,0xb,0x28,0xbe,0x6e,0xb9,0x17,0x27,0x47,0x74,0x7,0x26,0xc6,0x80,0x10,0x3f,0xe0,0xa0,0x7e,0x6f,0xc6,0x7e,0x48,0x7b}, {0xd,0x55,0xa,0xa5,0x4a,0xf8,0xa4,0xc0,0x91,0xe3,0xe7,0x9f,0x97,0x8e,0xf1,0x9e,0x86,0x76,0x72,0x81,0x50,0x60,0x8d,0xd4,0x7e,0x9e,0x5a,0x41,0xf3,0xe5,0xb0,0x62}, {0xfc,0x9f,0x1f,0xec,0x40,0x54,0x20,0x7a,0xe3,0xe4,0x1a,0x0,0xce,0xf4,0xc9,0x84,0x4f,0xd7,0x94,0xf5,0x9d,0xfa,0x95,0xd8,0x55,0x2e,0x7e,0x11,0x24,0xc3,0x54,0xa5}, {0x5b,0xdf,0x72,0x28,0xbd,0xfe,0x6e,0x28,0x78,0xf5,0x7f,0xe2,0xf,0xa5,0xc4,0xb2,0x5,0x89,0x7c,0xef,0xee,0x49,0xd3,0x2e,0x44,0x7e,0x93,0x85,0xeb,0x28,0x59,0x7f}, {0x70,0x5f,0x69,0x37,0xb3,0x24,0x31,0x4a,0x5e,0x86,0x28,0xf1,0x1d,0xd6,0xe4,0x65,0xc7,0x1b,0x77,0x4,0x51,0xb9,0x20,0xe7,0x74,0xfe,0x43,0xe8,0x23,0xd4,0x87,0x8a}, {0x7d,0x29,0xe8,0xa3,0x92,0x76,0x94,0xf2,0xdd,0xcb,0x7a,0x9,0x9b,0x30,0xd9,0xc1,0x1d,0x1b,0x30,0xfb,0x5b,0xdc,0x1b,0xe0,0xda,0x24,0x49,0x4f,0xf2,0x9c,0x82,0xbf}, {0xa4,0xe7,0xba,0x31,0xb4,0x70,0xbf,0xff,0xd,0x32,0x44,0x5,0xde,0xf8,0xbc,0x48,0x3b,0xae,0xfc,0x32,0x53,0xbb,0xd3,0x39,0x45,0x9f,0xc3,0xc1,0xe0,0x29,0x8b,0xa0}, {0xe5,0xc9,0x5,0xfd,0xf7,0xae,0x9,0xf,0x94,0x70,0x34,0x12,0x42,0x90,0xf1,0x34,0xa2,0x71,0xb7,0x1,0xe3,0x44,0xed,0x95,0xe9,0x3b,0x8e,0x36,0x4f,0x2f,0x98,0x4a}, {0x88,0x40,0x1d,0x63,0xa0,0x6c,0xf6,0x15,0x47,0xc1,0x44,0x4b,0x87,0x52,0xaf,0xff,0x7e,0xbb,0x4a,0xf1,0xe2,0xa,0xc6,0x30,0x46,0x70,0xb6,0xc5,0xcc,0x6e,0x8c,0xe6}, {0xa4,0xd5,0xa4,0x56,0xbd,0x4f,0xca,0x0,0xda,0x9d,0x84,0x4b,0xc8,0x3e,0x18,0xae,0x73,0x57,0xce,0x45,0x30,0x64,0xd1,0xad,0xe8,0xa6,0xce,0x68,0x14,0x5c,0x25,0x67}, {0xa3,0xda,0x8c,0xf2,0xcb,0xe,0xe1,0x16,0x33,0xe9,0x6,0x58,0x9a,0x94,0x99,0x9a,0x1f,0x60,0xb2,0x20,0xc2,0x6f,0x84,0x7b,0xd1,0xce,0xac,0x7f,0xa0,0xd1,0x85,0x18}, {0x32,0x59,0x5b,0xa1,0x8d,0xdd,0x19,0xd3,0x50,0x9a,0x1c,0xc0,0xaa,0xa5,0xb4,0x46,0x9f,0x3d,0x63,0x67,0xe4,0x4,0x6b,0xba,0xf6,0xca,0x19,0xab,0xb,0x56,0xee,0x7e}, {0x1f,0xb1,0x79,0xea,0xa9,0x28,0x21,0x74,0xe9,0xbd,0xf7,0x35,0x3b,0x36,0x51,0xee,0x1d,0x57,0xac,0x5a,0x75,0x50,0xd3,0x76,0x3a,0x46,0xc2,0xfe,0xa3,0x7d,0x70,0x1}, {0xf7,0x35,0xc1,0xaf,0x98,0xa4,0xd8,0x42,0x78,0xed,0xec,0x20,0x9e,0x6b,0x67,0x79,0x41,0x83,0x63,0x15,0xea,0x3a,0xdb,0xa8,0xfa,0xc3,0x3b,0x4d,0x32,0x83,0x2c,0x83}, {0xa7,0x40,0x3b,0x1f,0x1c,0x27,0x47,0xf3,0x59,0x40,0xf0,0x34,0xb7,0x2d,0x76,0x9a,0xe7,0x3e,0x4e,0x6c,0xd2,0x21,0x4f,0xfd,0xb8,0xfd,0x8d,0x39,0xdc,0x57,0x59,0xef}, {0x8d,0x9b,0xc,0x49,0x2b,0x49,0xeb,0xda,0x5b,0xa2,0xd7,0x49,0x68,0xf3,0x70,0xd,0x7d,0x3b,0xae,0xd0,0x7a,0x8d,0x55,0x84,0xf5,0xa5,0xe9,0xf0,0xe4,0xf8,0x8e,0x65}, {0xa0,0xb8,0xa2,0xf4,0x36,0x10,0x3b,0x53,0xc,0xa8,0x7,0x9e,0x75,0x3e,0xec,0x5a,0x91,0x68,0x94,0x92,0x56,0xe8,0x88,0x4f,0x5b,0xb0,0x5c,0x55,0xf8,0xba,0xbc,0x4c}, {0xe3,0xbb,0x3b,0x99,0xf3,0x87,0x94,0x7b,0x75,0xda,0xf4,0xd6,0x72,0x6b,0x1c,0x5d,0x64,0xae,0xac,0x28,0xdc,0x34,0xb3,0x6d,0x6c,0x34,0xa5,0x50,0xb8,0x28,0xdb,0x71}, {0xf8,0x61,0xe2,0xf2,0x10,0x8d,0x51,0x2a,0xe3,0xdb,0x64,0x33,0x59,0xdd,0x75,0xfc,0x1c,0xac,0xbc,0xf1,0x43,0xce,0x3f,0xa2,0x67,0xbb,0xd1,0x3c,0x2,0xe8,0x43,0xb0}, {0x33,0xa,0x5b,0xca,0x88,0x29,0xa1,0x75,0x7f,0x34,0x19,0x4d,0xb4,0x16,0x53,0x5c,0x92,0x3b,0x94,0xc3,0xe,0x79,0x4d,0x1e,0x79,0x74,0x75,0xd7,0xb6,0xee,0xaf,0x3f}, {0xea,0xa8,0xd4,0xf7,0xbe,0x1a,0x39,0x21,0x5c,0xf4,0x7e,0x9,0x4c,0x23,0x27,0x51,0x26,0xa3,0x24,0x53,0xba,0x32,0x3c,0xd2,0x44,0xa3,0x17,0x4a,0x6d,0xa6,0xd5,0xad}, {0xb5,0x1d,0x3e,0xa6,0xaf,0xf2,0xc9,0x8,0x83,0x59,0x3d,0x98,0x91,0x6b,0x3c,0x56,0x4c,0xf8,0x7c,0xa1,0x72,0x86,0x60,0x4d,0x46,0xe2,0x3e,0xcc,0x8,0x6e,0xc7,0xf6}, {0x2f,0x98,0x33,0xb3,0xb1,0xbc,0x76,0x5e,0x2b,0xd6,0x66,0xa5,0xef,0xc4,0xe6,0x2a,0x6,0xf4,0xb6,0xe8,0xbe,0xc1,0xd4,0x36,0x74,0xee,0x82,0x15,0xbc,0xef,0x21,0x63}, {0xfd,0xc1,0x4e,0xd,0xf4,0x53,0xc9,0x69,0xa7,0x7d,0x5a,0xc4,0x6,0x58,0x58,0x26,0x7e,0xc1,0x14,0x16,0x6,0xe0,0xfa,0x16,0x7e,0x90,0xaf,0x3d,0x28,0x63,0x9d,0x3f}, {0xd2,0xc9,0xf2,0xe3,0x0,0x9b,0xd2,0xc,0x5f,0xaa,0xce,0x30,0xb7,0xd4,0xc,0x30,0x74,0x2a,0x51,0x16,0xf2,0xe0,0x32,0x98,0xd,0xeb,0x30,0xd8,0xe3,0xce,0xf8,0x9a}, {0x4b,0xc5,0x9e,0x7b,0xb5,0xf1,0x79,0x92,0xff,0x51,0xe6,0x6e,0x4,0x86,0x68,0xd3,0x9b,0x23,0x4d,0x57,0xe6,0x96,0x67,0x31,0xcc,0xe6,0xa6,0xf3,0x17,0xa,0x75,0x5}, {0xb1,0x76,0x81,0xd9,0x13,0x32,0x6c,0xce,0x3c,0x17,0x52,0x84,0xf8,0x5,0xa2,0x62,0xf4,0x2b,0xcb,0xb3,0x78,0x47,0x15,0x47,0xff,0x46,0x54,0x82,0x23,0x93,0x6a,0x48}, {0x38,0xdf,0x58,0x7,0x4e,0x5e,0x65,0x65,0xf2,0xfc,0x7c,0x89,0xfc,0x86,0x50,0x8e,0x31,0x70,0x2e,0x44,0xd0,0xb,0xca,0x86,0xf0,0x40,0x9,0xa2,0x30,0x78,0x47,0x4e}, {0x65,0xa0,0xee,0x39,0xd1,0xf7,0x38,0x83,0xf7,0x5e,0xe9,0x37,0xe4,0x2c,0x3a,0xbd,0x21,0x97,0xb2,0x26,0x1,0x13,0xf8,0x6f,0xa3,0x44,0xed,0xd1,0xef,0x9f,0xde,0xe7}, {0x8b,0xa0,0xdf,0x15,0x76,0x25,0x92,0xd9,0x3c,0x85,0xf7,0xf6,0x12,0xdc,0x42,0xbe,0xd8,0xa7,0xec,0x7c,0xab,0x27,0xb0,0x7e,0x53,0x8d,0x7d,0xda,0xaa,0x3e,0xa8,0xde}, {0xaa,0x25,0xce,0x93,0xbd,0x2,0x69,0xd8,0x5a,0xf6,0x43,0xfd,0x1a,0x73,0x8,0xf9,0xc0,0x5f,0xef,0xda,0x17,0x4a,0x19,0xa5,0x97,0x4d,0x66,0x33,0x4c,0xfd,0x21,0x6a}, {0x35,0xb4,0x98,0x31,0xdb,0x41,0x15,0x70,0xea,0x1e,0xf,0xbb,0xed,0xcd,0x54,0x9b,0x9a,0xd0,0x63,0xa1,0x51,0x97,0x40,0x72,0xf6,0x75,0x9d,0xbf,0x91,0x47,0x6f,0xe2}}; #define JH_SWAP1(x) (x) = ((((x) & 0x5555555555555555ULL) << 1) | (((x) & 0xaaaaaaaaaaaaaaaaULL) >> 1)); #define JH_SWAP2(x) (x) = ((((x) & 0x3333333333333333ULL) << 2) | (((x) & 0xccccccccccccccccULL) >> 2)); #define JH_SWAP4(x) (x) = ((((x) & 0x0f0f0f0f0f0f0f0fULL) << 4) | (((x) & 0xf0f0f0f0f0f0f0f0ULL) >> 4)); #define JH_SWAP8(x) (x) = ((((x) & 0x00ff00ff00ff00ffULL) << 8) | (((x) & 0xff00ff00ff00ff00ULL) >> 8)); #define JH_SWAP16(x) (x) = ((((x) & 0x0000ffff0000ffffULL) << 16) | (((x) & 0xffff0000ffff0000ULL) >> 16)); #define JH_SWAP32(x) (x) = (((x) << 32) | ((x) >> 32)); #define JH_L(m0,m1,m2,m3,m4,m5,m6,m7) \ (m4) ^= (m1); \ (m5) ^= (m2); \ (m6) ^= (m0) ^ (m3); \ (m7) ^= (m0); \ (m0) ^= (m5); \ (m1) ^= (m6); \ (m2) ^= (m4) ^ (m7); \ (m3) ^= (m4); #define JH_SS(m0,m1,m2,m3,m4,m5,m6,m7,cc0,cc1) \ m3 = ~(m3); \ m7 = ~(m7); \ m0 ^= ((~(m2)) & (cc0)); \ m4 ^= ((~(m6)) & (cc1)); \ temp0 = (cc0) ^ ((m0) & (m1));\ temp1 = (cc1) ^ ((m4) & (m5));\ m0 ^= ((m2) & (m3)); \ m4 ^= ((m6) & (m7)); \ m3 ^= ((~(m1)) & (m2)); \ m7 ^= ((~(m5)) & (m6)); \ m1 ^= ((m0) & (m2)); \ m5 ^= ((m4) & (m6)); \ m2 ^= ((m0) & (~(m3))); \ m6 ^= ((m4) & (~(m7))); \ m0 ^= ((m1) | (m3)); \ m4 ^= ((m5) | (m7)); \ m3 ^= ((m1) & (m2)); \ m7 ^= ((m5) & (m6)); \ m1 ^= (temp0 & (m0)); \ m5 ^= (temp1 & (m4)); \ m2 ^= temp0; \ m6 ^= temp1; __device__ void cn_jh_E8(jhHashState *state) { uint64_t i,roundnumber,temp0,temp1; for (roundnumber = 0; roundnumber < 42; roundnumber = roundnumber+7) { for (i = 0; i < 2; i++) { JH_SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64_t *)d_E8_rc[roundnumber+0])[i],((uint64_t *)d_E8_rc[roundnumber+0])[i+2] ); JH_L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); JH_SWAP1(state->x[1][i]); JH_SWAP1(state->x[3][i]); JH_SWAP1(state->x[5][i]); JH_SWAP1(state->x[7][i]); } for (i = 0; i < 2; i++) { JH_SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64_t *)d_E8_rc[roundnumber+1])[i],((uint64_t *)d_E8_rc[roundnumber+1])[i+2] ); JH_L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); JH_SWAP2(state->x[1][i]); JH_SWAP2(state->x[3][i]); JH_SWAP2(state->x[5][i]); JH_SWAP2(state->x[7][i]); } for (i = 0; i < 2; i++) { JH_SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64_t *)d_E8_rc[roundnumber+2])[i],((uint64_t *)d_E8_rc[roundnumber+2])[i+2] ); JH_L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); JH_SWAP4(state->x[1][i]); JH_SWAP4(state->x[3][i]); JH_SWAP4(state->x[5][i]); JH_SWAP4(state->x[7][i]); } for (i = 0; i < 2; i++) { JH_SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64_t *)d_E8_rc[roundnumber+3])[i],((uint64_t *)d_E8_rc[roundnumber+3])[i+2] ); JH_L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); JH_SWAP8(state->x[1][i]); JH_SWAP8(state->x[3][i]); JH_SWAP8(state->x[5][i]); JH_SWAP8(state->x[7][i]); } for (i = 0; i < 2; i++) { JH_SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64_t *)d_E8_rc[roundnumber+4])[i],((uint64_t *)d_E8_rc[roundnumber+4])[i+2] ); JH_L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); JH_SWAP16(state->x[1][i]); JH_SWAP16(state->x[3][i]); JH_SWAP16(state->x[5][i]); JH_SWAP16(state->x[7][i]); } for (i = 0; i < 2; i++) { JH_SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64_t *)d_E8_rc[roundnumber+5])[i],((uint64_t *)d_E8_rc[roundnumber+5])[i+2] ); JH_L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); JH_SWAP32(state->x[1][i]); JH_SWAP32(state->x[3][i]); JH_SWAP32(state->x[5][i]); JH_SWAP32(state->x[7][i]); } for (i = 0; i < 2; i++) { JH_SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64_t *)d_E8_rc[roundnumber+6])[i],((uint64_t *)d_E8_rc[roundnumber+6])[i+2] ); JH_L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); } for (i = 1; i < 8; i = i+2) { temp0 = state->x[i][0]; state->x[i][0] = state->x[i][1]; state->x[i][1] = temp0; } } } __device__ void cn_jh_F8(jhHashState *state) { uint64_t i; for (i = 0; i < 8; i++) state->x[i >> 1][i & 1] ^= ((uint64_t *)state->buffer)[i]; cn_jh_E8(state); for (i = 0; i < 8; i++) state->x[(8+i) >> 1][(8+i) & 1] ^= ((uint64_t *)state->buffer)[i]; } __device__ void cn_jh_update(jhHashState *state, const BitSequence *data, DataLength databitlen) { DataLength index; state->databitlen += databitlen; index = 0; if ( (state->datasize_in_buffer > 0 ) && (( state->datasize_in_buffer + databitlen) < 512) ) { if ( (databitlen & 7) == 0 ) { memcpy(state->buffer + (state->datasize_in_buffer >> 3), data, 64-(state->datasize_in_buffer >> 3)) ; } else memcpy(state->buffer + (state->datasize_in_buffer >> 3), data, 64-(state->datasize_in_buffer >> 3)+1) ; state->datasize_in_buffer += databitlen; databitlen = 0; } if ( (state->datasize_in_buffer > 0 ) && (( state->datasize_in_buffer + databitlen) >= 512) ) { memcpy( state->buffer + (state->datasize_in_buffer >> 3), data, 64-(state->datasize_in_buffer >> 3) ) ; index = 64-(state->datasize_in_buffer >> 3); databitlen = databitlen - (512 - state->datasize_in_buffer); cn_jh_F8(state); state->datasize_in_buffer = 0; } for ( ; databitlen >= 512; index = index+64, databitlen = databitlen - 512) { memcpy(state->buffer, data+index, 64); cn_jh_F8(state); } if ( databitlen > 0) { if ((databitlen & 7) == 0) memcpy(state->buffer, data+index, (databitlen & 0x1ff) >> 3); else memcpy(state->buffer, data+index, ((databitlen & 0x1ff) >> 3)+1); state->datasize_in_buffer = databitlen; } } /*pad the message, process the padded block(s), truncate the hash value H to obtain the message digest*/ __device__ void cn_jh_final(jhHashState *state, BitSequence *hashval) { unsigned int i; //uint32_t *bufptr = (uint32_t *)state->buffer; if ( (state->databitlen & 0x1ff) == 0 ) { /*pad the message when databitlen is multiple of 512 bits, then process the padded block*/ memset(state->buffer, 0, 64); //for( i = 0; i < 16; i++ ) *(bufptr+i) = 0x00000000; state->buffer[0] = 0x80; state->buffer[63] = state->databitlen & 0xff; state->buffer[62] = (state->databitlen >> 8) & 0xff; state->buffer[61] = (state->databitlen >> 16) & 0xff; state->buffer[60] = (state->databitlen >> 24) & 0xff; state->buffer[59] = (state->databitlen >> 32) & 0xff; state->buffer[58] = (state->databitlen >> 40) & 0xff; state->buffer[57] = (state->databitlen >> 48) & 0xff; state->buffer[56] = (state->databitlen >> 56) & 0xff; cn_jh_F8(state); } else { /*set the rest of the bytes in the buffer to 0*/ if ( (state->datasize_in_buffer & 7) == 0) for (i = (state->databitlen & 0x1ff) >> 3; i < 64; i++) state->buffer[i] = 0; else for (i = ((state->databitlen & 0x1ff) >> 3)+1; i < 64; i++) state->buffer[i] = 0; /*pad and process the partial block when databitlen is not multiple of 512 bits, then hash the padded blocks*/ state->buffer[((state->databitlen & 0x1ff) >> 3)] |= 1 << (7- (state->databitlen & 7)); cn_jh_F8(state); memset(state->buffer, 0, 64); //for( i = 0; i < 16; i++ ) *(bufptr+i) = 0x00000000; state->buffer[63] = state->databitlen & 0xff; state->buffer[62] = (state->databitlen >> 8) & 0xff; state->buffer[61] = (state->databitlen >> 16) & 0xff; state->buffer[60] = (state->databitlen >> 24) & 0xff; state->buffer[59] = (state->databitlen >> 32) & 0xff; state->buffer[58] = (state->databitlen >> 40) & 0xff; state->buffer[57] = (state->databitlen >> 48) & 0xff; state->buffer[56] = (state->databitlen >> 56) & 0xff; cn_jh_F8(state); } memcpy(hashval,(unsigned char*)state->x+64+32,32); } __device__ void cn_jh_init(jhHashState *state, int hashbitlen) { state->databitlen = 0; state->datasize_in_buffer = 0; state->hashbitlen = hashbitlen; memcpy(state->x, d_JH256_H0, 128); } __device__ void cn_jh(const BitSequence *data, DataLength len, BitSequence *hashval) { int hashbitlen = 256; DataLength databitlen = len << 3; jhHashState state; cn_jh_init(&state, hashbitlen); cn_jh_update(&state, data, databitlen); cn_jh_final(&state, hashval); }
the_stack
#include "thundersvm/kernel/smo_kernel.h" #include <thrust/sort.h> #include <thrust/system/cuda/detail/par.h> namespace svm_kernel { template<typename T> __device__ int get_block_min(const T *values, int *index) { int tid = threadIdx.x; index[tid] = tid; __syncthreads(); //block size is always the power of 2 for (int offset = blockDim.x / 2; offset > 0; offset >>= 1) { if (tid < offset) { if (values[index[tid + offset]] < values[index[tid]]) { index[tid] = index[tid + offset]; } } __syncthreads(); } return index[0]; } __global__ void c_smo_solve_kernel(const int *label, float_type *f_val, float_type *alpha, float_type *alpha_diff, const int *working_set, int ws_size, float_type Cp, float_type Cn, const kernel_type *k_mat_rows, const kernel_type *k_mat_diag, int row_len, float_type eps, float_type *diff, int max_iter) { //"row_len" equals to the number of instances in the original training dataset. //allocate shared memory extern __shared__ int shared_mem[]; int *f_idx2reduce = shared_mem; //temporary memory for reduction float_type *f_val2reduce = (float_type *) &shared_mem[ws_size]; //f values used for reduction. float_type *alpha_i_diff = (float_type *) &shared_mem[ws_size + ws_size * sizeof(float_type) / sizeof(int)]; //delta alpha_i float_type *alpha_j_diff = &alpha_i_diff[1]; kernel_type *kd = (kernel_type *) &alpha_j_diff[1]; // diagonal elements for kernel matrix //index, f value and alpha for each instance int tid = threadIdx.x; int wsi = working_set[tid]; kd[tid] = k_mat_diag[wsi]; float_type y = label[wsi]; float_type f = f_val[wsi]; float_type a = alpha[wsi]; float_type aold = a; __syncthreads(); float_type local_eps; int numOfIter = 0; while (1) { //select fUp and fLow if (is_I_up(a, y, Cp, Cn)) f_val2reduce[tid] = f; else f_val2reduce[tid] = INFINITY; int i = get_block_min(f_val2reduce, f_idx2reduce); float_type up_value = f_val2reduce[i]; kernel_type kIwsI = k_mat_rows[row_len * i + wsi];//K[i, wsi] __syncthreads(); if (is_I_low(a, y, Cp, Cn)) f_val2reduce[tid] = -f; else f_val2reduce[tid] = INFINITY; int j1 = get_block_min(f_val2reduce, f_idx2reduce); float_type low_value = -f_val2reduce[j1]; float_type local_diff = low_value - up_value; if (numOfIter == 0) { local_eps = max(eps, 0.1f * local_diff); if (tid == 0) { diff[0] = local_diff; } } if (numOfIter > max_iter || local_diff < local_eps) { alpha[wsi] = a; alpha_diff[tid] = -(a - aold) * y; diff[1] = numOfIter; break; } __syncthreads(); //select j2 using second order heuristic if (-up_value > -f && (is_I_low(a, y, Cp, Cn))) { float_type aIJ = kd[i] + kd[tid] - 2 * kIwsI; float_type bIJ = -up_value + f; f_val2reduce[tid] = (-bIJ * bIJ / aIJ); } else f_val2reduce[tid] = INFINITY; int j2 = get_block_min(f_val2reduce, f_idx2reduce); //update alpha if (tid == i) *alpha_i_diff = y > 0 ? Cp - a : a; if (tid == j2) *alpha_j_diff = min(y > 0 ? a : Cn - a, (-up_value + f) / (kd[i] + kd[j2] - 2 * kIwsI)); __syncthreads(); float_type l = min(*alpha_i_diff, *alpha_j_diff); if (tid == i) a += l * y; if (tid == j2) a -= l * y; //update f kernel_type kJ2wsI = k_mat_rows[row_len * j2 + wsi];//K[J2, wsi] f -= l * (kJ2wsI - kIwsI); numOfIter++; } } __global__ void nu_smo_solve_kernel(const int *label, float_type *f_values, float_type *alpha, float_type *alpha_diff, const int *working_set, int ws_size, float C, const kernel_type *k_mat_rows, const kernel_type *k_mat_diag, int row_len, float_type eps, float_type *diff, int max_iter) { //"row_len" equals to the number of instances in the original training dataset. //allocate shared memory extern __shared__ int shared_mem[]; int *f_idx2reduce = shared_mem; //temporary memory for reduction float_type *f_val2reduce = (float_type *) &shared_mem[ws_size]; //f values used for reduction. float_type *alpha_i_diff = (float_type *) &shared_mem[ws_size + ws_size * sizeof(float_type) / sizeof(int)]; //delta alpha_i float_type *alpha_j_diff = &alpha_i_diff[1]; kernel_type *kd = (kernel_type *) &alpha_j_diff[1]; // diagonal elements for kernel matrix //index, f value and alpha for each instance int tid = threadIdx.x; int wsi = working_set[tid]; kd[tid] = k_mat_diag[wsi]; float_type y = label[wsi]; float_type f = f_values[wsi]; float_type a = alpha[wsi]; float_type aold = a; __syncthreads(); float_type local_eps; int numOfIter = 0; while (1) { //select I_up (y=+1) if (y > 0 && a < C) f_val2reduce[tid] = f; else f_val2reduce[tid] = INFINITY; __syncthreads(); int ip = get_block_min(f_val2reduce, f_idx2reduce); float_type up_value_p = f_val2reduce[ip]; kernel_type kIpwsI = k_mat_rows[row_len * ip + wsi];//K[i, wsi] __syncthreads(); //select I_up (y=-1) if (y < 0 && a > 0) f_val2reduce[tid] = f; else f_val2reduce[tid] = INFINITY; int in = get_block_min(f_val2reduce, f_idx2reduce); float_type up_value_n = f_val2reduce[in]; kernel_type kInwsI = k_mat_rows[row_len * in + wsi];//K[i, wsi] __syncthreads(); //select I_low (y=+1) if (y > 0 && a > 0) f_val2reduce[tid] = -f; else f_val2reduce[tid] = INFINITY; int j1p = get_block_min(f_val2reduce, f_idx2reduce); float_type low_value_p = -f_val2reduce[j1p]; __syncthreads(); //select I_low (y=-1) if (y < 0 && a < C) f_val2reduce[tid] = -f; else f_val2reduce[tid] = INFINITY; int j1n = get_block_min(f_val2reduce, f_idx2reduce); float_type low_value_n = -f_val2reduce[j1n]; float_type local_diff = max(low_value_p - up_value_p, low_value_n - up_value_n); if (numOfIter == 0) { local_eps = max(eps, 0.1 * local_diff); if (tid == 0) { diff[0] = local_diff; } } if (numOfIter > max_iter || local_diff < local_eps) { alpha[wsi] = a; alpha_diff[tid] = -(a - aold) * y; diff[1] = numOfIter; break; } __syncthreads(); //select j2p using second order heuristic if (-up_value_p > -f && y > 0 && a > 0) { float_type aIJ = kd[ip] + kd[tid] - 2 * kIpwsI; float_type bIJ = -up_value_p + f; f_val2reduce[tid] = -bIJ * bIJ / aIJ; } else f_val2reduce[tid] = INFINITY; int j2p = get_block_min(f_val2reduce, f_idx2reduce); float_type f_val_j2p = f_val2reduce[j2p]; __syncthreads(); //select j2n using second order heuristic if (-up_value_n > -f && y < 0 && a < C) { float_type aIJ = kd[in] + kd[tid] - 2 * kInwsI; float_type bIJ = -up_value_n + f; f_val2reduce[tid] = -bIJ * bIJ / aIJ; } else f_val2reduce[tid] = INFINITY; int j2n = get_block_min(f_val2reduce, f_idx2reduce); int i, j2; float_type up_value; kernel_type kIwsI; if (f_val_j2p < f_val2reduce[j2n]) { i = ip; j2 = j2p; up_value = up_value_p; kIwsI = kIpwsI; } else { i = in; j2 = j2n; kIwsI = kInwsI; up_value = up_value_n; } //update alpha if (tid == i) *alpha_i_diff = y > 0 ? C - a : a; if (tid == j2) *alpha_j_diff = min(y > 0 ? a : C - a, (-up_value + f) / (kd[i] + kd[j2] - 2 * kIwsI)); __syncthreads(); float_type l = min(*alpha_i_diff, *alpha_j_diff); if (tid == i) a += l * y; if (tid == j2) a -= l * y; //update f kernel_type kJ2wsI = k_mat_rows[row_len * j2 + wsi];//K[J2, wsi] f -= l * (kJ2wsI - kIwsI); numOfIter++; } } void c_smo_solve(const SyncArray<int> &y, SyncArray<float_type> &f_val, SyncArray<float_type> &alpha, SyncArray<float_type> &alpha_diff, const SyncArray<int> &working_set, float_type Cp, float_type Cn, const SyncArray<kernel_type> &k_mat_rows, const SyncArray<kernel_type> &k_mat_diag, int row_len, float_type eps, SyncArray<float_type> &diff, int max_iter) { size_t ws_size = working_set.size(); size_t smem_size = 0; smem_size += ws_size * sizeof(int); //f_idx2reduce smem_size += ws_size * sizeof(float_type); //f_val2reduce smem_size += ws_size * sizeof(kernel_type); //kd smem_size += 2 * sizeof(float_type); //alpha diff c_smo_solve_kernel << < 1, ws_size, smem_size >> > (y.device_data(), f_val.device_data(), alpha.device_data(), alpha_diff.device_data(), working_set.device_data(), ws_size, Cp, Cn, k_mat_rows.device_data(), k_mat_diag.device_data(), row_len, eps, diff.device_data(), max_iter); } void nu_smo_solve(const SyncArray<int> &y, SyncArray<float_type> &f_val, SyncArray<float_type> &alpha, SyncArray<float_type> &alpha_diff, const SyncArray<int> &working_set, float_type C, const SyncArray<kernel_type> &k_mat_rows, const SyncArray<kernel_type> &k_mat_diag, int row_len, float_type eps, SyncArray<float_type> &diff, int max_iter) { size_t ws_size = working_set.size(); size_t smem_size = 0; smem_size += ws_size * sizeof(int); //f_idx2reduce smem_size += ws_size * sizeof(float_type); //f_val2reduce smem_size += ws_size * sizeof(kernel_type); //kd smem_size += 2 * sizeof(float_type); //alpha diff nu_smo_solve_kernel << < 1, ws_size, smem_size >> > (y.device_data(), f_val.device_data(), alpha.device_data(), alpha_diff.device_data(), working_set.device_data(), ws_size, C, k_mat_rows.device_data(), k_mat_diag.device_data(), row_len, eps, diff.device_data(), max_iter); } __global__ void update_f_kernel(float_type *f, int ws_size, const float_type *alpha_diff, const kernel_type *k_mat_rows, int n_instances) { //"n_instances" equals to the number of rows of the whole kernel matrix for both SVC and SVR. KERNEL_LOOP(idx, n_instances) {//one thread to update multiple fvalues. double sum_diff = 0; for (int i = 0; i < ws_size; ++i) { double d = alpha_diff[i]; if (d != 0) { sum_diff += d * k_mat_rows[i * n_instances + idx]; } } f[idx] -= sum_diff; } } void update_f(SyncArray<float_type> &f, const SyncArray<float_type> &alpha_diff, const SyncArray<kernel_type> &k_mat_rows, int n_instances) { SAFE_KERNEL_LAUNCH(update_f_kernel, f.device_data(), alpha_diff.size(), alpha_diff.device_data(), k_mat_rows.device_data(), n_instances); } void sort_f(SyncArray<float_type> &f_val2sort, SyncArray<int> &f_idx2sort) { thrust::sort_by_key(thrust::cuda::par, f_val2sort.device_data(), f_val2sort.device_data() + f_val2sort.size(), f_idx2sort.device_data(), thrust::less<float_type>()); } }
the_stack
#include <iostream> #include <algorithm> // CHECK: #include <hip/hip_runtime.h> #include <cuda.h> template<typename T> __global__ void axpy(T a, T *x, T *y) { y[threadIdx.x] = a * x[threadIdx.x]; } template<typename T1, typename T2> __global__ void axpy_2(T1 a, T2 *x, T2 *y) { y[threadIdx.x] = a * x[threadIdx.x]; } template<typename T> __global__ void axpy_empty() { } __global__ void empty() { } __global__ void nonempty(int x, int y, int z) { } int main(int argc, char* argv[]) { const int kDataLen = 4; float a = 2.0f; float host_x[kDataLen] = {1.0f, 2.0f, 3.0f, 4.0f}; float host_y[kDataLen]; // Copy input data to device. float* device_x; float* device_y; // CHECK: hipMalloc(&device_x, kDataLen * sizeof(float)); cudaMalloc(&device_x, kDataLen * sizeof(float)); // CHECK: hipMalloc(&device_y, kDataLen * sizeof(float)); cudaMalloc(&device_y, kDataLen * sizeof(float)); // CHECK: hipMemcpy(device_x, host_x, kDataLen * sizeof(float), hipMemcpyHostToDevice); cudaMemcpy(device_x, host_x, kDataLen * sizeof(float), cudaMemcpyHostToDevice); int x = 1, y = 2, z = 3; size_t N = 32; // CHECK: hipStream_t stream = NULL; cudaStream_t stream = NULL; // CHECK: hipStreamCreate(&stream); cudaStreamCreate(&stream); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy<float>), dim3(1), dim3(kDataLen), 0, 0, a, device_x, device_y); axpy<float><<<1, kDataLen>>>(a, device_x, device_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy<float>), dim3(1), dim3(kDataLen), 0, 0, a, device_x, device_y); axpy<float><<<dim3(1), kDataLen>>>(a, device_x, device_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy<float>), dim3(1), dim3(kDataLen), 0, 0, a, device_x, device_y); axpy<float><<<1, dim3(kDataLen)>>>(a, device_x, device_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy<float>), dim3(1), dim3(kDataLen), 0, 0, a, device_x, device_y); axpy<float><<<dim3(1), dim3(kDataLen)>>>(a, device_x, device_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy<float>), dim3(1), dim3(kDataLen), N, 0, a, device_x, device_y); axpy<float><<<1, kDataLen, N>>>(a, device_x, device_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy<float>), dim3(1), dim3(kDataLen), N, 0, a, device_x, device_y); axpy<float><<<dim3(1), kDataLen, N>>>(a, device_x, device_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy<float>), dim3(1), dim3(kDataLen), N, 0, a, device_x, device_y); axpy<float><<<1, dim3(kDataLen), N>>>(a, device_x, device_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy<float>), dim3(1), dim3(kDataLen), N, 0, a, device_x, device_y); axpy<float><<<dim3(1), dim3(kDataLen), N>>>(a, device_x, device_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy<float>), dim3(1), dim3(kDataLen), N, stream, a, device_x, device_y); axpy<float><<<1, kDataLen, N, stream>>>(a, device_x, device_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy<float>), dim3(1), dim3(kDataLen), N, stream, a, device_x, device_y); axpy<float><<<dim3(1), kDataLen, N, stream>>>(a, device_x, device_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy<float>), dim3(1), dim3(kDataLen), N, stream, a, device_x, device_y); axpy<float><<<1, dim3(kDataLen), N, stream>>>(a, device_x, device_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy<float>), dim3(1), dim3(kDataLen), N, stream, a, device_x, device_y); axpy<float><<<dim3(1), dim3(kDataLen), N, stream>>>(a, device_x, device_y); double h_x[kDataLen] = {1.0f, 2.0f, 3.0f, 4.0f}; double h_y[kDataLen]; // Copy input data to device. double* d_x; double* d_y; // CHECK: hipMalloc(&d_x, kDataLen * sizeof(double)); cudaMalloc(&d_x, kDataLen * sizeof(double)); // CHECK: hipMalloc(&d_y, kDataLen * sizeof(double)); cudaMalloc(&d_y, kDataLen * sizeof(double)); // CHECK: hipMemcpy(d_x, h_x, kDataLen * sizeof(double), hipMemcpyHostToDevice); cudaMemcpy(d_x, h_x, kDataLen * sizeof(double), cudaMemcpyHostToDevice); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_2<float,double>), dim3(1), dim3(kDataLen*2+10), N*N, stream, a, d_x, d_y); axpy_2<float,double><<<1, kDataLen*2+10, N*N, stream>>>(a, d_x, d_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_2<float,double>), dim3(1,1,1), dim3(kDataLen*2+10), N*N, stream, a, d_x, d_y); axpy_2<float,double><<<dim3(1,1,1), kDataLen*2+10, N*N, stream>>>(a, d_x, d_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_2<float,double>), dim3(1), dim3(kDataLen*2+10), N*N, stream, a, d_x, d_y); axpy_2<float,double><<<1, dim3(kDataLen*2+10), N*N, stream>>>(a, d_x, d_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_2<float,double>), dim3(1,1,1), dim3(kDataLen*2+10), N*N, stream, a, d_x, d_y); axpy_2<float,double><<<dim3(1,1,1), dim3(kDataLen*2+10), N*N, stream>>>(a, d_x, d_y); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_empty<float>), dim3(1), dim3(kDataLen), 0, 0); axpy_empty<float><<<1, kDataLen>>>(); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_empty<float>), dim3(1), dim3(kDataLen), 0, 0); axpy_empty<float><<<dim3(1), kDataLen>>>(); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_empty<float>), dim3(1), dim3(kDataLen), 0, 0); axpy_empty<float><<<1, dim3(kDataLen)>>>(); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_empty<float>), dim3(1), dim3(kDataLen), 0, 0); axpy_empty<float><<<dim3(1), dim3(kDataLen)>>>(); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_empty<float>), dim3(1), dim3(kDataLen), N, 0); axpy_empty<float><<<1, kDataLen, N>>>(); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_empty<float>), dim3(1), dim3(kDataLen), N, 0); axpy_empty<float><<<dim3(1), kDataLen, N>>>(); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_empty<float>), dim3(1), dim3(kDataLen), N, 0); axpy_empty<float><<<1, dim3(kDataLen), N>>>(); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_empty<float>), dim3(1), dim3(kDataLen), N, 0); axpy_empty<float><<<dim3(1), dim3(kDataLen), N>>>(); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_empty<float>), dim3(1), dim3(kDataLen), N, stream); axpy_empty<float><<<1, kDataLen, N, stream>>>(); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_empty<float>), dim3(1), dim3(kDataLen), N, stream); axpy_empty<float><<<dim3(1), kDataLen, N, stream>>>(); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_empty<float>), dim3(1), dim3(kDataLen), N, stream); axpy_empty<float><<<1, dim3(kDataLen), N, stream>>>(); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_empty<float>), dim3(1), dim3(kDataLen), N, stream); axpy_empty<float><<<dim3(1), dim3(kDataLen), N, stream>>>(); // CHECK: hipLaunchKernelGGL(empty, dim3(1), dim3(kDataLen), 0, 0); empty<<<1, kDataLen>>> ( ); // CHECK: hipLaunchKernelGGL(empty, dim3(1), dim3(kDataLen), 0, 0); empty<<<dim3(1), kDataLen>>> ( ); // CHECK: hipLaunchKernelGGL(empty, dim3(1), dim3(kDataLen), 0, 0); empty<<<1, dim3(kDataLen)>>> ( ); // CHECK: hipLaunchKernelGGL(empty, dim3(1), dim3(kDataLen), 0, 0); empty<<<dim3(1), dim3(kDataLen)>>> ( ); // CHECK: hipLaunchKernelGGL(empty, dim3(1), dim3(kDataLen), N, 0); empty<<<1, kDataLen, N>>> ( ); // CHECK: hipLaunchKernelGGL(empty, dim3(1), dim3(kDataLen), N, 0); empty<<<dim3(1), kDataLen, N>>> ( ); // CHECK: hipLaunchKernelGGL(empty, dim3(1), dim3(kDataLen), N, 0); empty<<<1, dim3(kDataLen), N>>> ( ); // CHECK: hipLaunchKernelGGL(empty, dim3(1), dim3(kDataLen), N, 0); empty<<<dim3(1), dim3(kDataLen), N>>> ( ); // CHECK: hipLaunchKernelGGL(empty, dim3(1), dim3(kDataLen), N, stream); empty<<<1, kDataLen, N, stream>>> ( ); // CHECK: hipLaunchKernelGGL(empty, dim3(1), dim3(kDataLen), N, stream); empty<<<dim3(1), kDataLen, N, stream>>> ( ); // CHECK: hipLaunchKernelGGL(empty, dim3(1), dim3(kDataLen), N, stream); empty<<<1, dim3(kDataLen), N, stream>>> ( ); // CHECK: hipLaunchKernelGGL(empty, dim3(1), dim3(kDataLen), N, stream); empty<<<dim3(1), dim3(kDataLen), N, stream>>> ( ); // CHECK: hipLaunchKernelGGL(nonempty, dim3(1), dim3(kDataLen), 0, 0, x, y, z); nonempty<<<1, kDataLen>>> (x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(1), dim3(kDataLen), 0, 0, x, y, z); nonempty<<<dim3(1), kDataLen>>> (x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(1), dim3(kDataLen), 0, 0, x, y, z); nonempty<<<1, dim3(kDataLen)>>> (x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(1), dim3(kDataLen), 0, 0, x, y, z); nonempty<<<dim3(1), dim3(kDataLen)>>> (x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(1), dim3(kDataLen), N, 0, x, y, z); nonempty<<<1, kDataLen, N>>> (x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(1), dim3(kDataLen), N, 0, x, y, z); nonempty<<<dim3(1), kDataLen, N>>> (x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(1), dim3(kDataLen), N, 0, x, y, z); nonempty<<<1, dim3(kDataLen), N>>> (x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(1), dim3(kDataLen), N, 0, x, y, z); nonempty<<<dim3(1), dim3(kDataLen), N>>> (x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(1), dim3(kDataLen), N, stream, x, y, z); nonempty<<<1, kDataLen, N, stream>>> (x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(1), dim3(kDataLen), N, stream, x, y, z); nonempty<<<dim3(1), kDataLen, N, stream>>> (x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(1), dim3(kDataLen), N, stream, x, y, z); nonempty<<<1, dim3(kDataLen), N, stream>>> (x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(1), dim3(kDataLen), N, stream, x, y, z); nonempty<<<dim3(1), dim3(kDataLen), N, stream>>> (x, y, z); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_2<float,double>), dim3(x,y,z), dim3(std::min(kDataLen*2+10,x)), std::min(x,y), stream, a, std::min(d_x,d_y), std::max(d_x,d_y)); axpy_2<float,double><<<dim3(x,y,z), std::min(kDataLen*2+10,x), std::min(x,y), stream>>>(a, std::min(d_x,d_y), std::max(d_x,d_y)); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_2<float,double>), dim3(x,y,z), dim3(std::min(kDataLen*2+10,x)), std::min(x,y), 0, a, std::min(d_x,d_y), std::max(d_x,d_y)); axpy_2<float,double><<<dim3(x,y,z), std::min(kDataLen*2+10,x), std::min(x,y)>>>(a, std::min(d_x,d_y), std::max(d_x,d_y)); // CHECK: hipLaunchKernelGGL(HIP_KERNEL_NAME(axpy_2<float,double>), dim3(x,y,z), dim3(std::min(kDataLen*2+10,x)), 0, 0, a, std::min(d_x,d_y), std::max(d_x,d_y)); axpy_2<float,double><<<dim3(x,y,z), std::min(kDataLen*2+10,x)>>>(a, std::min(d_x,d_y), std::max(d_x,d_y)); // CHECK: hipLaunchKernelGGL(nonempty, dim3(x,y,z), dim3(x,y,std::min(y,z)), 0, 0, x, y, z); nonempty<<<dim3(x,y,z), dim3(x,y,std::min(y,z))>>>(x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(x,y,z), dim3(x,y,std::min(std::max(x,y),z)), 0, 0, x, y, z); nonempty<<<dim3(x,y,z), dim3(x,y,std::min(std::max(x,y),z))>>>(x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(x,y,z), dim3(x,y,std::min(std::max(x,int(N)),z)), 0, 0, x, y, z); nonempty<<<dim3(x,y,z), dim3(x,y,std::min(std::max(x,int(N)),z))>>>(x, y, z); // CHECK: hipLaunchKernelGGL(nonempty, dim3(x,y,z), dim3(x,y,std::min(std::max(x,int(N+N -x/y + y*1)),z)), 0, 0, x, y, z); nonempty<<<dim3(x,y,z), dim3(x,y,std::min(std::max(x,int(N+N -x/y + y*1)),z))>>>(x, y, z); // Copy output data to host. // CHECK: hipDeviceSynchronize(); cudaDeviceSynchronize(); // CHECK: hipMemcpy(host_y, device_y, kDataLen * sizeof(float), hipMemcpyDeviceToHost); cudaMemcpy(host_y, device_y, kDataLen * sizeof(float), cudaMemcpyDeviceToHost); // Print the results. for (int i = 0; i < kDataLen; ++i) { std::cout << "y[" << i << "] = " << host_y[i] << "\n"; } // CHECK: hipDeviceReset(); cudaDeviceReset(); return 0; }
the_stack
* This sample demonstrates Inter Process Communication * using one process per GPU for computation. */ #include <stdio.h> #include <stdlib.h> #include <vector> #include <cuda.h> #define CUDA_DRIVER_API 1 #include "helper_cuda.h" #include "helper_cuda_drvapi.h" #include "helper_multiprocess.h" static const char shmName[] = "streamOrderedAllocationIPCshm"; static const char ipcName[] = "streamOrderedAllocationIPC_pipe"; // For direct NVLINK and PCI-E peers, at max 8 simultaneous peers are allowed // For NVSWITCH connected peers like DGX-2, simultaneous peers are not limited // in the same way. #define MAX_DEVICES (32) #define DATA_SIZE (64ULL << 20ULL) // 64MB #if defined(__linux__) #define cpu_atomic_add32(a, x) __sync_add_and_fetch(a, x) #elif defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) #define cpu_atomic_add32(a, x) InterlockedAdd((volatile LONG *)a, x) #else #error Unsupported system #endif typedef struct shmStruct_st { size_t nprocesses; int barrier; int sense; int devices[MAX_DEVICES]; cudaMemPoolPtrExportData exportPtrData[MAX_DEVICES]; } shmStruct; __global__ void simpleKernel(char *ptr, int sz, char val) { int idx = blockIdx.x * blockDim.x + threadIdx.x; for (; idx < sz; idx += (gridDim.x * blockDim.x)) { ptr[idx] = val; } } static void barrierWait(volatile int *barrier, volatile int *sense, unsigned int n) { int count; // Check-in count = cpu_atomic_add32(barrier, 1); if (count == n) // Last one in *sense = 1; while (!*sense) ; // Check-out count = cpu_atomic_add32(barrier, -1); if (count == 0) // Last one out *sense = 0; while (*sense) ; } static void childProcess(int id) { volatile shmStruct *shm = NULL; cudaStream_t stream; sharedMemoryInfo info; size_t procCount, i; int blocks = 0; int threads = 128; cudaDeviceProp prop; std::vector<void *> ptrs; std::vector<char> verification_buffer(DATA_SIZE); ipcHandle *ipcChildHandle = NULL; checkIpcErrors(ipcOpenSocket(ipcChildHandle)); if (sharedMemoryOpen(shmName, sizeof(shmStruct), &info) != 0) { printf("Failed to create shared memory slab\n"); exit(EXIT_FAILURE); } shm = (volatile shmStruct *)info.addr; procCount = shm->nprocesses; barrierWait(&shm->barrier, &shm->sense, (unsigned int)(procCount + 1)); // Receive all allocation handles shared by Parent. std::vector<ShareableHandle> shHandle(shm->nprocesses); checkIpcErrors(ipcRecvShareableHandles(ipcChildHandle, shHandle)); checkCudaErrors(cudaSetDevice(shm->devices[id])); checkCudaErrors(cudaGetDeviceProperties(&prop, shm->devices[id])); checkCudaErrors(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking)); checkCudaErrors(cudaOccupancyMaxActiveBlocksPerMultiprocessor( &blocks, simpleKernel, threads, 0)); blocks *= prop.multiProcessorCount; std::vector<cudaMemPool_t> pools(shm->nprocesses); cudaMemAllocationHandleType handleType = cudaMemHandleTypePosixFileDescriptor; // Import mem pools from all the devices created in the master // process using shareable handles received via socket // and import the pointer to the allocated buffer using // exportData filled in shared memory by the master process. for (i = 0; i < procCount; i++) { checkCudaErrors(cudaMemPoolImportFromShareableHandle( &pools[i], (void *)shHandle[i], handleType, 0)); cudaMemAccessFlags accessFlags; cudaMemLocation location; location.type = cudaMemLocationTypeDevice; location.id = shm->devices[id]; checkCudaErrors(cudaMemPoolGetAccess(&accessFlags, pools[i], &location)); if (accessFlags != cudaMemAccessFlagsProtReadWrite) { cudaMemAccessDesc desc; memset(&desc, 0, sizeof(cudaMemAccessDesc)); desc.location.type = cudaMemLocationTypeDevice; desc.location.id = shm->devices[id]; desc.flags = cudaMemAccessFlagsProtReadWrite; checkCudaErrors(cudaMemPoolSetAccess(pools[i], &desc, 1)); } // Import the allocation from each memory pool by iterating over exportData // until import is success. for (int j = 0; j < procCount; j++) { void *ptr = NULL; // Import the allocation using the opaque export data retrieved through // the shared memory". cudaError_t ret = cudaMemPoolImportPointer( &ptr, pools[i], (cudaMemPoolPtrExportData *)&shm->exportPtrData[j]); if (ret == cudaSuccess) { // Pointer import is successful hence add it to the ptrs bag. ptrs.push_back(ptr); break; } else { // Reset failure error received from cudaMemPoolImportPointer // for further try. cudaGetLastError(); } } // Since we have imported allocations shared by the parent with us, we can // close this ShareableHandle. checkIpcErrors(ipcCloseShareableHandle(shHandle[i])); } // Since we have imported allocations shared by the parent with us, we can // close the socket. checkIpcErrors(ipcCloseSocket(ipcChildHandle)); // At each iteration of the loop, each sibling process will push work on // their respective devices accessing the next peer mapped buffer allocated // by the master process (these can come from other sibling processes as // well). To coordinate each process' access, we force the stream to wait for // the work already accessing this buffer. for (i = 0; i < procCount; i++) { size_t bufferId = (i + id) % procCount; // Push a simple kernel on it simpleKernel<<<blocks, threads, 0, stream>>>((char *)ptrs[bufferId], DATA_SIZE, id); checkCudaErrors(cudaGetLastError()); checkCudaErrors(cudaStreamSynchronize(stream)); // Wait for all my sibling processes to push this stage of their work // before proceeding to the next. This prevents siblings from racing // ahead and clobbering the recorded event or waiting on the wrong // recorded event. barrierWait(&shm->barrier, &shm->sense, (unsigned int)procCount); if (id == 0) { printf("Step %lld done\n", (unsigned long long)i); } } // Now wait for my buffer to be ready so I can copy it locally and verify it checkCudaErrors(cudaMemcpyAsync(&verification_buffer[0], ptrs[id], DATA_SIZE, cudaMemcpyDeviceToHost, stream)); // And wait for all the queued up work to complete checkCudaErrors(cudaStreamSynchronize(stream)); printf("Process %d: verifying...\n", id); // The contents should have the id of the sibling just after me char compareId = (char)((id + 1) % procCount); for (unsigned long long j = 0; j < DATA_SIZE; j++) { if (verification_buffer[j] != compareId) { printf("Process %d: Verification mismatch at %lld: %d != %d\n", id, j, (int)verification_buffer[j], (int)compareId); } } // Clean up! for (i = 0; i < procCount; i++) { // Free the memory before the exporter process frees it checkCudaErrors(cudaFreeAsync(ptrs[i], stream)); } // And wait for all the queued up work to complete checkCudaErrors(cudaStreamSynchronize(stream)); checkCudaErrors(cudaStreamDestroy(stream)); printf("Process %d complete!\n", id); } static void parentProcess(char *app) { sharedMemoryInfo info; int devCount, i; volatile shmStruct *shm = NULL; std::vector<void *> ptrs; std::vector<Process> processes; checkCudaErrors(cudaGetDeviceCount(&devCount)); std::vector<CUdevice> devices(devCount); for (i = 0; i < devCount; i++) { cuDeviceGet(&devices[i], i); } if (sharedMemoryCreate(shmName, sizeof(*shm), &info) != 0) { printf("Failed to create shared memory slab\n"); exit(EXIT_FAILURE); } shm = (volatile shmStruct *)info.addr; memset((void *)shm, 0, sizeof(*shm)); // Pick all the devices that can access each other's memory for this test // Keep in mind that CUDA has minimal support for fork() without a // corresponding exec() in the child process, but in this case our // spawnProcess will always exec, so no need to worry. for (i = 0; i < devCount; i++) { bool allPeers = true; cudaDeviceProp prop; checkCudaErrors(cudaGetDeviceProperties(&prop, i)); int isMemPoolSupported = 0; checkCudaErrors(cudaDeviceGetAttribute(&isMemPoolSupported, cudaDevAttrMemoryPoolsSupported, i)); // CUDA IPC is only supported on devices with unified addressing if (!isMemPoolSupported) { printf("Device %d does not support cuda memory pools, skipping...\n", i); continue; } int deviceSupportsIpcHandle = 0; #if defined(__linux__) checkCudaErrors(cuDeviceGetAttribute( &deviceSupportsIpcHandle, CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR_SUPPORTED, devices[i])); #else cuDeviceGetAttribute(&deviceSupportsIpcHandle, CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_WIN32_HANDLE_SUPPORTED, devices[i]); #endif if (!deviceSupportsIpcHandle) { printf("Device %d does not support CUDA IPC Handle, skipping...\n", i); continue; } // This sample requires two processes accessing each device, so we need // to ensure exclusive or prohibited mode is not set if (prop.computeMode != cudaComputeModeDefault) { printf("Device %d is in an unsupported compute mode for this sample\n", i); continue; } #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) // CUDA IPC on Windows is only supported on TCC if (!prop.tccDriver) { printf("Device %d is not in TCC mode\n", i); continue; } #endif for (int j = 0; j < shm->nprocesses; j++) { int canAccessPeerIJ, canAccessPeerJI; checkCudaErrors( cudaDeviceCanAccessPeer(&canAccessPeerJI, shm->devices[j], i)); checkCudaErrors( cudaDeviceCanAccessPeer(&canAccessPeerIJ, i, shm->devices[j])); if (!canAccessPeerIJ || !canAccessPeerJI) { allPeers = false; break; } } if (allPeers) { // Enable peers here. This isn't necessary for IPC, but it will // setup the peers for the device. For systems that only allow 8 // peers per GPU at a time, this acts to remove devices from CanAccessPeer for (int j = 0; j < shm->nprocesses; j++) { checkCudaErrors(cudaSetDevice(i)); checkCudaErrors(cudaDeviceEnablePeerAccess(shm->devices[j], 0)); checkCudaErrors(cudaSetDevice(shm->devices[j])); checkCudaErrors(cudaDeviceEnablePeerAccess(i, 0)); } shm->devices[shm->nprocesses++] = i; if (shm->nprocesses >= MAX_DEVICES) break; } else { printf( "Device %d is not peer capable with some other selected peers, " "skipping\n", i); } } if (shm->nprocesses == 0) { printf("No CUDA devices support IPC\n"); exit(EXIT_WAIVED); } std::vector<ShareableHandle> shareableHandles(shm->nprocesses); std::vector<cudaStream_t> streams(shm->nprocesses); std::vector<cudaMemPool_t> pools(shm->nprocesses); // Now allocate memory for each process and fill the shared // memory buffer with the export data and get memPool handles to communicate for (i = 0; i < shm->nprocesses; i++) { void *ptr = NULL; checkCudaErrors(cudaSetDevice(shm->devices[i])); checkCudaErrors( cudaStreamCreateWithFlags(&streams[i], cudaStreamNonBlocking)); // Allocate an explicit pool with IPC capabilities cudaMemPoolProps poolProps; memset(&poolProps, 0, sizeof(cudaMemPoolProps)); poolProps.allocType = cudaMemAllocationTypePinned; poolProps.handleTypes = cudaMemHandleTypePosixFileDescriptor; poolProps.location.type = cudaMemLocationTypeDevice; poolProps.location.id = shm->devices[i]; checkCudaErrors(cudaMemPoolCreate(&pools[i], &poolProps)); // Query the shareable handle for the pool cudaMemAllocationHandleType handleType = cudaMemHandleTypePosixFileDescriptor; // Allocate memory in a stream from the pool just created checkCudaErrors(cudaMallocAsync(&ptr, DATA_SIZE, pools[i], streams[i])); checkCudaErrors(cudaMemPoolExportToShareableHandle( &shareableHandles[i], pools[i], handleType, 0)); // Get the opaque ‘bag-of-bits’ representing the allocation memset((void *)&shm->exportPtrData[i], 0, sizeof(cudaMemPoolPtrExportData)); checkCudaErrors(cudaMemPoolExportPointer( (cudaMemPoolPtrExportData *)&shm->exportPtrData[i], ptr)); ptrs.push_back(ptr); } // Launch the child processes! for (i = 0; i < shm->nprocesses; i++) { char devIdx[10]; char *const args[] = {app, devIdx, NULL}; Process process; SPRINTF(devIdx, "%d", i); if (spawnProcess(&process, app, args)) { printf("Failed to create process\n"); exit(EXIT_FAILURE); } processes.push_back(process); } barrierWait(&shm->barrier, &shm->sense, (unsigned int)(shm->nprocesses + 1)); ipcHandle *ipcParentHandle = NULL; checkIpcErrors(ipcCreateSocket(ipcParentHandle, ipcName, processes)); checkIpcErrors( ipcSendShareableHandles(ipcParentHandle, shareableHandles, processes)); // Close the shareable handles as they are not needed anymore. for (int i = 0; i < shm->nprocesses; i++) { checkIpcErrors(ipcCloseShareableHandle(shareableHandles[i])); } checkIpcErrors(ipcCloseSocket(ipcParentHandle)); // And wait for them to finish for (i = 0; i < processes.size(); i++) { if (waitProcess(&processes[i]) != EXIT_SUCCESS) { printf("Process %d failed!\n", i); exit(EXIT_FAILURE); } } // Clean up! for (i = 0; i < shm->nprocesses; i++) { checkCudaErrors(cudaSetDevice(shm->devices[i])); checkCudaErrors(cudaFreeAsync(ptrs[i], streams[i])); checkCudaErrors(cudaStreamSynchronize(streams[i])); checkCudaErrors(cudaMemPoolDestroy(pools[i])); } sharedMemoryClose(&info); } // Host code int main(int argc, char **argv) { #if defined(__arm__) || defined(__aarch64__) || defined(WIN32) || \ defined(_WIN32) || defined(WIN64) || defined(_WIN64) printf("Not supported on ARM\n"); return EXIT_WAIVED; #else if (argc == 1) { parentProcess(argv[0]); } else { childProcess(atoi(argv[1])); } return EXIT_SUCCESS; #endif }
the_stack
#include <cub/cub.cuh> #include <faiss/gpu/utils/DeviceDefs.cuh> #include <faiss/gpu/utils/MergeNetworkUtils.cuh> #include <faiss/gpu/utils/PtxUtils.cuh> #include <faiss/gpu/utils/StaticUtils.h> #include <faiss/gpu/utils/WarpShuffles.cuh> namespace faiss { namespace gpu { template <typename _Key, typename _Value> struct KeyValuePair { typedef _Key Key; ///< Key data type typedef _Value Value; ///< Value data type Key key; ///< Item key Value value; ///< Item value /// Constructor __host__ __device__ __forceinline__ KeyValuePair() {} /// Copy Constructors __host__ __device__ __forceinline__ KeyValuePair(cub::KeyValuePair<_Key, _Value>& kvp) : key(kvp.key), value(kvp.value) { } __host__ __device__ __forceinline__ KeyValuePair(faiss::gpu::KeyValuePair<_Key, _Value>& kvp) : key(kvp.key), value(kvp.value) { } /// Constructor __host__ __device__ __forceinline__ KeyValuePair(Key const& key, Value const& value) : key(key), value(value) { } /// Inequality operator __host__ __device__ __forceinline__ bool operator!=(const KeyValuePair& b) { return (value != b.value) || (key != b.key); } }; // // This file contains functions to: // // -perform bitonic merges on pairs of sorted lists, held in // registers. Each list contains N * kWarpSize (multiple of 32) // elements for some N. // The bitonic merge is implemented for arbitrary sizes; // sorted list A of size N1 * kWarpSize registers // sorted list B of size N2 * kWarpSize registers => // sorted list C if size (N1 + N2) * kWarpSize registers. N1 and N2 // are >= 1 and don't have to be powers of 2. // // -perform bitonic sorts on a set of N * kWarpSize key/value pairs // held in registers, by using the above bitonic merge as a // primitive. // N can be an arbitrary N >= 1; i.e., the bitonic sort here supports // odd sizes and doesn't require the input to be a power of 2. // // The sort or merge network is completely statically instantiated via // template specialization / expansion and constexpr, and it uses warp // shuffles to exchange values between warp lanes. // // A note about comparsions: // // For a sorting network of keys only, we only need one // comparison (a < b). However, what we really need to know is // if one lane chooses to exchange a value, then the // corresponding lane should also do the exchange. // Thus, if one just uses the negation !(x < y) in the higher // lane, this will also include the case where (x == y). Thus, one // lane in fact performs an exchange and the other doesn't, but // because the only value being exchanged is equivalent, nothing has // changed. // So, you can get away with just one comparison and its negation. // // If we're sorting keys and values, where equivalent keys can // exist, then this is a problem, since we want to treat (x, v1) // as not equivalent to (x, v2). // // To remedy this, you can either compare with a lexicographic // ordering (a.k < b.k || (a.k == b.k && a.v < b.v)), which since // we're predicating all of the choices results in 3 comparisons // being executed, or we can invert the selection so that there is no // middle choice of equality; the other lane will likewise // check that (b.k > a.k) (the higher lane has the values // swapped). Then, the first lane swaps if and only if the // second lane swaps; if both lanes have equivalent keys, no // swap will be performed. This results in only two comparisons // being executed. // // If you don't consider values as well, then this does not produce a // consistent ordering among (k, v) pairs with equivalent keys but // different values; for us, we don't really care about ordering or // stability here. // // I have tried both re-arranging the order in the higher lane to get // away with one comparison or adding the value to the check; both // result in greater register consumption or lower speed than just // perfoming both < and > comparisons with the variables, so I just // stick with this. // This function merges kWarpSize / 2L lists in parallel using warp // shuffles. // It works on at most size-16 lists, as we need 32 threads for this // shuffle merge. // // If IsBitonic is false, the first stage is reversed, so we don't // need to sort directionally. It's still technically a bitonic sort. template <typename K, typename V, int L, bool Dir, typename Comp, bool IsBitonic> inline __device__ void warpBitonicMergeLE16KVP(K& k, KeyValuePair<K, V>& v) { static_assert(utils::isPowerOf2(L), "L must be a power-of-2"); static_assert(L <= kWarpSize / 2, "merge list size must be <= 16"); int laneId = getLaneId(); if (!IsBitonic) { // Reverse the first comparison stage. // For example, merging a list of size 8 has the exchanges: // 0 <-> 15, 1 <-> 14, ... K otherK = shfl_xor(k, 2 * L - 1); K otherVk = shfl_xor(v.key, 2 * L - 1); V otherVv = shfl_xor(v.value, 2 * L - 1); KeyValuePair<K, V> otherV = KeyValuePair(otherVk, otherVv); // Whether we are the lesser thread in the exchange bool small = !(laneId & L); if (Dir) { // See the comment above how performing both of these // comparisons in the warp seems to win out over the // alternatives in practice bool s = small ? Comp::gt(k, otherK) : Comp::lt(k, otherK); assign(s, k, otherK); assign(s, v.key, otherV.key); assign(s, v.value, otherV.value); } else { bool s = small ? Comp::lt(k, otherK) : Comp::gt(k, otherK); assign(s, k, otherK); assign(s, v.value, otherV.value); assign(s, v.key, otherV.key); } } #pragma unroll for (int stride = IsBitonic ? L : L / 2; stride > 0; stride /= 2) { K otherK = shfl_xor(k, stride); K otherVk = shfl_xor(v.key, stride); V otherVv = shfl_xor(v.value, stride); KeyValuePair<K, V> otherV = KeyValuePair(otherVk, otherVv); // Whether we are the lesser thread in the exchange bool small = !(laneId & stride); if (Dir) { bool s = small ? Comp::gt(k, otherK) : Comp::lt(k, otherK); assign(s, k, otherK); assign(s, v.key, otherV.key); assign(s, v.value, otherV.value); } else { bool s = small ? Comp::lt(k, otherK) : Comp::gt(k, otherK); assign(s, k, otherK); assign(s, v.key, otherV.key); assign(s, v.value, otherV.value); } } } // Template for performing a bitonic merge of an arbitrary set of // registers template <typename K, typename V, int N, bool Dir, typename Comp, bool Low, bool Pow2> struct BitonicMergeStepKVP { }; // // Power-of-2 merge specialization // // All merges eventually call this template <typename K, typename V, bool Dir, typename Comp, bool Low> struct BitonicMergeStepKVP<K, V, 1, Dir, Comp, Low, true> { static inline __device__ void merge(K k[1], KeyValuePair<K, V> v[1]) { // Use warp shuffles warpBitonicMergeLE16KVP<K, V, 16, Dir, Comp, true>(k[0], v[0]); } }; template <typename K, typename V, int N, bool Dir, typename Comp, bool Low> struct BitonicMergeStepKVP<K, V, N, Dir, Comp, Low, true> { static inline __device__ void merge(K k[N], KeyValuePair<K, V> v[N]) { static_assert(utils::isPowerOf2(N), "must be power of 2"); static_assert(N > 1, "must be N > 1"); #pragma unroll for (int i = 0; i < N / 2; ++i) { K& ka = k[i]; KeyValuePair<K, V>& va = v[i]; K& kb = k[i + N / 2]; KeyValuePair<K, V>& vb = v[i + N / 2]; bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); swap(s, ka, kb); swap(s, va.key, vb.key); swap(s, va.value, vb.value); } { K newK[N / 2]; KeyValuePair<K, V> newV[N / 2]; #pragma unroll for (int i = 0; i < N / 2; ++i) { newK[i] = k[i]; newV[i].key = v[i].key; newV[i].value = v[i].value; } BitonicMergeStepKVP<K, V, N / 2, Dir, Comp, true, true>::merge(newK, newV); #pragma unroll for (int i = 0; i < N / 2; ++i) { k[i] = newK[i]; v[i].key = newV[i].key; v[i].value = newV[i].value; } } { K newK[N / 2]; KeyValuePair<K, V> newV[N / 2]; #pragma unroll for (int i = 0; i < N / 2; ++i) { newK[i] = k[i + N / 2]; newV[i].key = v[i + N / 2].key; newV[i].value = v[i + N / 2].value; } BitonicMergeStepKVP<K, V, N / 2, Dir, Comp, false, true>::merge(newK, newV); #pragma unroll for (int i = 0; i < N / 2; ++i) { k[i + N / 2] = newK[i]; v[i + N / 2].key = newV[i].key; v[i + N / 2].value = newV[i].value; } } } }; // // Non-power-of-2 merge specialization // // Low recursion template <typename K, typename V, int N, bool Dir, typename Comp> struct BitonicMergeStepKVP<K, V, N, Dir, Comp, true, false> { static inline __device__ void merge(K k[N], KeyValuePair<K, V> v[N]) { static_assert(!utils::isPowerOf2(N), "must be non-power-of-2"); static_assert(N >= 3, "must be N >= 3"); constexpr int kNextHighestPowerOf2 = utils::nextHighestPowerOf2(N); #pragma unroll for (int i = 0; i < N - kNextHighestPowerOf2 / 2; ++i) { K& ka = k[i]; KeyValuePair<K, V>& va = v[i]; K& kb = k[i + kNextHighestPowerOf2 / 2]; KeyValuePair<K, V>& vb = v[i + kNextHighestPowerOf2 / 2]; bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); swap(s, ka, kb); swap(s, va.key, vb.key); swap(s, va.value, vb.value); } constexpr int kLowSize = N - kNextHighestPowerOf2 / 2; constexpr int kHighSize = kNextHighestPowerOf2 / 2; { K newK[kLowSize]; KeyValuePair<K, V> newV[kLowSize]; #pragma unroll for (int i = 0; i < kLowSize; ++i) { newK[i] = k[i]; newV[i].key = v[i].key; newV[i].value = v[i].value; } constexpr bool kLowIsPowerOf2 = utils::isPowerOf2(N - kNextHighestPowerOf2 / 2); // FIXME: compiler doesn't like this expression? compiler bug? // constexpr bool kLowIsPowerOf2 = utils::isPowerOf2(kLowSize); BitonicMergeStepKVP<K, V, kLowSize, Dir, Comp, true, // low kLowIsPowerOf2>::merge(newK, newV); #pragma unroll for (int i = 0; i < kLowSize; ++i) { k[i] = newK[i]; v[i].key = newV[i].key; v[i].value = newV[i].value; } } { K newK[kHighSize]; KeyValuePair<K, V> newV[kHighSize]; #pragma unroll for (int i = 0; i < kHighSize; ++i) { newK[i] = k[i + kLowSize]; newV[i].key = v[i + kLowSize].key; newV[i].value = v[i + kLowSize].value; } constexpr bool kHighIsPowerOf2 = utils::isPowerOf2(kNextHighestPowerOf2 / 2); // FIXME: compiler doesn't like this expression? compiler bug? // constexpr bool kHighIsPowerOf2 = utils::isPowerOf2(kHighSize); BitonicMergeStepKVP<K, V, kHighSize, Dir, Comp, false, // high kHighIsPowerOf2>::merge(newK, newV); #pragma unroll for (int i = 0; i < kHighSize; ++i) { k[i + kLowSize] = newK[i]; v[i + kLowSize].key = newV[i].key; v[i + kLowSize].value = newV[i].value; } } } }; // High recursion template <typename K, typename V, int N, bool Dir, typename Comp> struct BitonicMergeStepKVP<K, V, N, Dir, Comp, false, false> { static inline __device__ void merge(K k[N], KeyValuePair<K, V> v[N]) { static_assert(!utils::isPowerOf2(N), "must be non-power-of-2"); static_assert(N >= 3, "must be N >= 3"); constexpr int kNextHighestPowerOf2 = utils::nextHighestPowerOf2(N); #pragma unroll for (int i = 0; i < N - kNextHighestPowerOf2 / 2; ++i) { K& ka = k[i]; KeyValuePair<K, V>& va = v[i]; K& kb = k[i + kNextHighestPowerOf2 / 2]; KeyValuePair<K, V>& vb = v[i + kNextHighestPowerOf2 / 2]; bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); swap(s, ka, kb); swap(s, va.key, vb.key); swap(s, va.value, vb.value); } constexpr int kLowSize = kNextHighestPowerOf2 / 2; constexpr int kHighSize = N - kNextHighestPowerOf2 / 2; { K newK[kLowSize]; KeyValuePair<K, V> newV[kLowSize]; #pragma unroll for (int i = 0; i < kLowSize; ++i) { newK[i] = k[i]; newV[i].key = v[i].key; newV[i].value = v[i].value; } constexpr bool kLowIsPowerOf2 = utils::isPowerOf2(kNextHighestPowerOf2 / 2); // FIXME: compiler doesn't like this expression? compiler bug? // constexpr bool kLowIsPowerOf2 = utils::isPowerOf2(kLowSize); BitonicMergeStepKVP<K, V, kLowSize, Dir, Comp, true, // low kLowIsPowerOf2>::merge(newK, newV); #pragma unroll for (int i = 0; i < kLowSize; ++i) { k[i] = newK[i]; v[i].key = newV[i].key; v[i].value = newV[i].value; } } { K newK[kHighSize]; KeyValuePair<K, V> newV[kHighSize]; #pragma unroll for (int i = 0; i < kHighSize; ++i) { newK[i] = k[i + kLowSize]; newV[i].key = v[i + kLowSize].key; newV[i].value = v[i + kLowSize].value; } constexpr bool kHighIsPowerOf2 = utils::isPowerOf2(N - kNextHighestPowerOf2 / 2); // FIXME: compiler doesn't like this expression? compiler bug? // constexpr bool kHighIsPowerOf2 = utils::isPowerOf2(kHighSize); BitonicMergeStepKVP<K, V, kHighSize, Dir, Comp, false, // high kHighIsPowerOf2>::merge(newK, newV); #pragma unroll for (int i = 0; i < kHighSize; ++i) { k[i + kLowSize] = newK[i]; v[i + kLowSize].key = newV[i].key; v[i + kLowSize].value = newV[i].value; } } } }; /// Merges two sets of registers across the warp of any size; /// i.e., merges a sorted k/v list of size kWarpSize * N1 with a /// sorted k/v list of size kWarpSize * N2, where N1 and N2 are any /// value >= 1 template <typename K, typename V, int N1, int N2, bool Dir, typename Comp, bool FullMerge = true> inline __device__ void warpMergeAnyRegistersKVP(K k1[N1], KeyValuePair<K, V> v1[N1], K k2[N2], KeyValuePair<K, V> v2[N2]) { constexpr int kSmallestN = N1 < N2 ? N1 : N2; #pragma unroll for (int i = 0; i < kSmallestN; ++i) { K& ka = k1[N1 - 1 - i]; KeyValuePair<K, V>& va = v1[N1 - 1 - i]; K& kb = k2[i]; KeyValuePair<K, V>& vb = v2[i]; K otherKa; KeyValuePair<K, V> otherVa; if (FullMerge) { // We need the other values otherKa = shfl_xor(ka, kWarpSize - 1); K otherVak = shfl_xor(va.key, kWarpSize - 1); V otherVav = shfl_xor(va.value, kWarpSize - 1); otherVa = KeyValuePair(otherVak, otherVav); } K otherKb = shfl_xor(kb, kWarpSize - 1); K otherVbk = shfl_xor(vb.key, kWarpSize - 1); V otherVbv = shfl_xor(vb.value, kWarpSize - 1); // ka is always first in the list, so we needn't use our lane // in this comparison bool swapa = Dir ? Comp::gt(ka, otherKb) : Comp::lt(ka, otherKb); assign(swapa, ka, otherKb); assign(swapa, va.key, otherVbk); assign(swapa, va.value, otherVbv); // kb is always second in the list, so we needn't use our lane // in this comparison if (FullMerge) { bool swapb = Dir ? Comp::lt(kb, otherKa) : Comp::gt(kb, otherKa); assign(swapb, kb, otherKa); assign(swapb, vb.key, otherVa.key); assign(swapb, vb.value, otherVa.value); } else { // We don't care about updating elements in the second list } } BitonicMergeStepKVP<K, V, N1, Dir, Comp, true, utils::isPowerOf2(N1)>::merge(k1, v1); if (FullMerge) { // Only if we care about N2 do we need to bother merging it fully BitonicMergeStepKVP<K, V, N2, Dir, Comp, false, utils::isPowerOf2(N2)>::merge(k2, v2); } } // Recursive template that uses the above bitonic merge to perform a // bitonic sort template <typename K, typename V, int N, bool Dir, typename Comp> struct BitonicSortStepKVP { static inline __device__ void sort(K k[N], KeyValuePair<K, V> v[N]) { static_assert(N > 1, "did not hit specialized case"); // Sort recursively constexpr int kSizeA = N / 2; constexpr int kSizeB = N - kSizeA; K aK[kSizeA]; KeyValuePair<K, V> aV[kSizeA]; #pragma unroll for (int i = 0; i < kSizeA; ++i) { aK[i] = k[i]; aV[i].key = v[i].key; aV[i].value = v[i].value; } BitonicSortStepKVP<K, V, kSizeA, Dir, Comp>::sort(aK, aV); K bK[kSizeB]; KeyValuePair<K, V> bV[kSizeB]; #pragma unroll for (int i = 0; i < kSizeB; ++i) { bK[i] = k[i + kSizeA]; bV[i].key = v[i + kSizeA].key; bV[i].value = v[i + kSizeA].value; } BitonicSortStepKVP<K, V, kSizeB, Dir, Comp>::sort(bK, bV); // Merge halves warpMergeAnyRegistersKVP<K, V, kSizeA, kSizeB, Dir, Comp>(aK, aV, bK, bV); #pragma unroll for (int i = 0; i < kSizeA; ++i) { k[i] = aK[i]; v[i].key = aV[i].key; v[i].value = aV[i].value; } #pragma unroll for (int i = 0; i < kSizeB; ++i) { k[i + kSizeA] = bK[i]; v[i + kSizeA].key = bV[i].key; v[i + kSizeA].value = bV[i].value; } } }; // Single warp (N == 1) sorting specialization template <typename K, typename V, bool Dir, typename Comp> struct BitonicSortStepKVP<K, V, 1, Dir, Comp> { static inline __device__ void sort(K k[1], KeyValuePair<K, V> v[1]) { // Update this code if this changes // should go from 1 -> kWarpSize in multiples of 2 static_assert(kWarpSize == 32, "unexpected warp size"); warpBitonicMergeLE16KVP<K, V, 1, Dir, Comp, false>(k[0], v[0]); warpBitonicMergeLE16KVP<K, V, 2, Dir, Comp, false>(k[0], v[0]); warpBitonicMergeLE16KVP<K, V, 4, Dir, Comp, false>(k[0], v[0]); warpBitonicMergeLE16KVP<K, V, 8, Dir, Comp, false>(k[0], v[0]); warpBitonicMergeLE16KVP<K, V, 16, Dir, Comp, false>(k[0], v[0]); } }; /// Sort a list of kWarpSize * N elements in registers, where N is an /// arbitrary >= 1 template <typename K, typename V, int N, bool Dir, typename Comp> inline __device__ void warpSortAnyRegistersKVP(K k[N], KeyValuePair<K, V> v[N]) { BitonicSortStepKVP<K, V, N, Dir, Comp>::sort(k, v); } // `Dir` true, produce largest values. // `Dir` false, produce smallest values. template <typename K, typename V, bool Dir, typename Comp, int NumWarpQ, int NumThreadQ, int ThreadsPerBlock> struct KeyValueWarpSelect { static constexpr int kNumWarpQRegisters = NumWarpQ / faiss::gpu::kWarpSize; __device__ inline KeyValueWarpSelect(K initKVal, faiss::gpu::KeyValuePair<K, V> initVVal, int k) : initK(initKVal), initV(initVVal), numVals(0), warpKTop(initKVal), warpKTopRDist(initKVal), kLane((k - 1) % faiss::gpu::kWarpSize) { static_assert(faiss::gpu::utils::isPowerOf2(ThreadsPerBlock), "threads must be a power-of-2"); static_assert(faiss::gpu::utils::isPowerOf2(NumWarpQ), "warp queue must be power-of-2"); // Fill the per-thread queue keys with the default value #pragma unroll for (int i = 0; i < NumThreadQ; ++i) { threadK[i] = initK; threadV[i].key = initV.key; threadV[i].value = initV.value; } // Fill the warp queue with the default value #pragma unroll for (int i = 0; i < kNumWarpQRegisters; ++i) { warpK[i] = initK; warpV[i].key = initV.key; warpV[i].value = initV.value; } } __device__ inline void addThreadQ(K k, faiss::gpu::KeyValuePair<K, V>& v) { if (Dir ? Comp::gt(k, warpKTop) : Comp::lt(k, warpKTop)) { // Rotate right #pragma unroll for (int i = NumThreadQ - 1; i > 0; --i) { threadK[i] = threadK[i - 1]; threadV[i].key = threadV[i - 1].key; threadV[i].value = threadV[i - 1].value; } threadK[0] = k; threadV[0].key = v.key; threadV[0].value = v.value; ++numVals; } } /// This function handles sorting and merging together the /// per-thread queues with the warp-wide queue, creating a sorted /// list across both // TODO __device__ inline void mergeWarpQ() { // Sort all of the per-thread queues faiss::gpu::warpSortAnyRegistersKVP<K, V, NumThreadQ, !Dir, Comp>(threadK, threadV); // The warp queue is already sorted, and now that we've sorted the // per-thread queue, merge both sorted lists together, producing // one sorted list faiss::gpu::warpMergeAnyRegistersKVP<K, V, kNumWarpQRegisters, NumThreadQ, !Dir, Comp, false>( warpK, warpV, threadK, threadV); } /// WARNING: all threads in a warp must participate in this. /// Otherwise, you must call the constituent parts separately. __device__ inline void add(K k, faiss::gpu::KeyValuePair<K, V>& v) { addThreadQ(k, v); checkThreadQ(); } __device__ inline void reduce() { // Have all warps dump and merge their queues; this will produce // the final per-warp results mergeWarpQ(); } __device__ inline void checkThreadQ() { bool needSort = (numVals == NumThreadQ); #if CUDA_VERSION >= 9000 needSort = __any_sync(0xffffffff, needSort); #else needSort = __any(needSort); #endif if (!needSort) { // no lanes have triggered a sort return; } mergeWarpQ(); // Any top-k elements have been merged into the warp queue; we're // free to reset the thread queues numVals = 0; #pragma unroll for (int i = 0; i < NumThreadQ; ++i) { threadK[i] = initK; threadV[i].key = initV.key; threadV[i].value = initV.value; } // We have to beat at least this element warpKTopRDist = shfl(warpV[kNumWarpQRegisters - 1].key, kLane); warpKTop = shfl(warpK[kNumWarpQRegisters - 1], kLane); } /// Dump final k selected values for this warp out __device__ inline void writeOut(K* outK, V* outV, int k) { int laneId = faiss::gpu::getLaneId(); #pragma unroll for (int i = 0; i < kNumWarpQRegisters; ++i) { int idx = i * faiss::gpu::kWarpSize + laneId; if (idx < k) { outK[idx] = warpK[i]; outV[idx] = warpV[i].value; } } } // Default element key const K initK; // Default element value const faiss::gpu::KeyValuePair<K, V> initV; // Number of valid elements in our thread queue int numVals; // The k-th highest (Dir) or lowest (!Dir) element K warpKTop; // TopK's distance to closest landmark K warpKTopRDist; // Thread queue values K threadK[NumThreadQ]; faiss::gpu::KeyValuePair<K, V> threadV[NumThreadQ]; // warpK[0] is highest (Dir) or lowest (!Dir) K warpK[kNumWarpQRegisters]; faiss::gpu::KeyValuePair<K, V> warpV[kNumWarpQRegisters]; // This is what lane we should load an approximation (>=k) to the // kth element from the last register in the warp queue (i.e., // warpK[kNumWarpQRegisters - 1]). int kLane; }; } // namespace gpu } // namespace faiss
the_stack
// Copyright (c) 2018 Changan Wang // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if GOOGLE_CUDA == 1 #define EIGEN_USE_GPU #include "ps_roi_align_op.h" #include "tensorflow/core/util/cuda_kernel_helper.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor_shape.h" using namespace tensorflow; #include <cstdint> #include <cmath> #include <cfloat> // Define the CUDA kernel. template <typename T> __global__ void PSROIAlignGradCudaKernel(CudaLaunchConfig config, const T * inputs, const T * rois, const T * pooled_features_grad, const int32_t * pooled_index, T * grad_output, const int32_t grid_dim_width, const int32_t grid_dim_height, const int batch_size, const int num_channals, const int map_height, const int map_width, const int num_rois, const bool using_max_pool) { const int32_t grid_size = grid_dim_width * grid_dim_height; const int32_t bank_size = num_channals / grid_size; CUDA_1D_KERNEL_LOOP(worker_index, config.virtual_thread_count) { // image_index * roi_index * channal_pos_remainder * row_index * col_index const int32_t position_index = (worker_index % num_channals) / bank_size; const int32_t row_index = position_index / grid_dim_width; const int32_t col_index = position_index % grid_dim_width; // position of the channal of pooled feature // position of the channal in the bank of feature map const int32_t channal_pos_remainder = worker_index % bank_size; const int32_t pool_index = worker_index / num_channals; const int32_t image_index = pool_index / num_rois; const int32_t roi_index = pool_index % num_rois; const T * roi_to_pool = rois + (image_index * num_rois + roi_index) * 4; if(ldg(roi_to_pool + 2) < std::numeric_limits<T>::min() || ldg(roi_to_pool + 3) < std::numeric_limits<T>::min()) continue; // T roi_ymin = static_cast<T>(0); // T roi_xmin = static_cast<T>(0); // T roi_ymax = static_cast<T>(0); // T roi_xmax = static_cast<T>(0); // fix ROI // std::tie(roi_ymin, roi_xmin, roi_ymax, roi_xmax) = [roi_to_pool, map_height, map_width](){ T _roi_y_center = static_cast<T>(ldg(roi_to_pool) * map_height); T _roi_x_center = static_cast<T>(ldg(roi_to_pool + 1) * map_width); T _roi_h = tf_max(ldg(roi_to_pool + 2) * map_height, static_cast<T>(1)); T _roi_w = tf_max(ldg(roi_to_pool + 3) * map_width, static_cast<T>(1)); T roi_ymin = tf_max(_roi_y_center - static_cast<T>(_roi_h / 2.), static_cast<T>(0)); T roi_xmin = tf_max(_roi_x_center - static_cast<T>(_roi_w / 2.), static_cast<T>(0)); T roi_ymax = tf_min(_roi_y_center + static_cast<T>(_roi_h / 2.), static_cast<T>(map_height) - std::numeric_limits<T>::min()); T roi_xmax = tf_min(_roi_x_center + static_cast<T>(_roi_w / 2.), static_cast<T>(map_width) - std::numeric_limits<T>::min()); // return std::make_tuple(roi_ymin, roi_xmin, roi_ymax, roi_xmax); // }(); T roi_h = roi_ymax - roi_ymin; T roi_w = roi_xmax - roi_xmin; float pool_bin_width = static_cast<float>(roi_w) / grid_dim_width; float pool_bin_height = static_cast<float>(roi_h) / grid_dim_height; int32_t num_elem_width = static_cast<int32_t>(pool_bin_width) + 1; int32_t num_elem_height = static_cast<int32_t>(pool_bin_height) + 1; // std::cout << "pool_bin_width: " << pool_bin_width << " pool_bin_height: " << pool_bin_height << " num_elem_width: " << num_elem_width << " num_elem_height: " << num_elem_height << std::endl; // std::cout << "worker_index: " << worker_index << " roi_index: " << roi_index // << " roi_ymin: " << roi_ymin << " roi_xmin: " << roi_xmin << " roi_ymax: " << roi_ymax << " roi_xmax: " << roi_xmax << " image_index: " << image_index << " position_index: " << (position_index % grid_size) << " channal_pos_remainder: " << channal_pos_remainder << std::endl; float step_width_each_bin = pool_bin_width / num_elem_width; float step_height_each_bin = pool_bin_height / num_elem_height; T * grad_output_start = reinterpret_cast<T*>(grad_output + (image_index * num_channals + position_index * bank_size + channal_pos_remainder) * map_height * map_width); const T * pooled_features_start = pooled_features_grad + worker_index; const int32_t * pooled_index_start = pooled_index + worker_index; // T * pooled_features_start = pooled_features_grad + image_index * (num_rois * num_channals) + roi_index * num_channals + (position_index % grid_size) * bank_size + channal_pos_remainder; // int32_t * pooled_index_start = pooled_index + image_index * (num_rois * num_channals) + roi_index * num_channals + (position_index % grid_size) * bank_size + channal_pos_remainder; float pool_width_start = roi_xmin + pool_bin_width * col_index; float pool_height_start = roi_ymin + pool_bin_height * row_index; if(using_max_pool){ const int32_t h_ind = ldg(pooled_index_start) / num_elem_width; const int32_t w_ind = ldg(pooled_index_start) % num_elem_width; float col_to_pool = pool_width_start + step_width_each_bin * w_ind + step_width_each_bin / 2.; float row_to_pool = pool_height_start + step_height_each_bin * h_ind + step_height_each_bin / 2.; //std::cout << "col_to_pool: " << col_to_pool << " row_to_pool: " << row_to_pool << std::endl; int32_t int_col_to_pool = static_cast<int32_t>(col_to_pool); int32_t int_row_to_pool = static_cast<int32_t>(row_to_pool); float float_col_to_pool = col_to_pool - int_col_to_pool; float float_row_to_pool = row_to_pool - int_row_to_pool; const T grad_in = ldg(pooled_features_start); atomicAdd(grad_output_start + int_row_to_pool * map_width + int_col_to_pool, static_cast<T>((1. - float_col_to_pool) * (1. - float_row_to_pool) * grad_in)); atomicAdd(grad_output_start + tf_min(int_row_to_pool + 1, map_height - 1) * map_width + int_col_to_pool, static_cast<T>((1. - float_col_to_pool) * float_row_to_pool * grad_in)); atomicAdd(grad_output_start + int_row_to_pool * map_width + tf_min(int_col_to_pool + 1, map_width - 1), static_cast<T>(float_col_to_pool * (1. - float_row_to_pool) * grad_in)); atomicAdd(grad_output_start + tf_min(int_row_to_pool + 1, map_height - 1) * map_width + tf_min(int_col_to_pool + 1, map_width - 1), static_cast<T>(float_col_to_pool * float_row_to_pool * grad_in)); }else{ const T grad_in = ldg(pooled_features_start) / static_cast<T>(num_elem_width * num_elem_height); for (int32_t h_ind = 0; h_ind < num_elem_height; ++h_ind) { for (int32_t w_ind = 0; w_ind < num_elem_width; ++w_ind) { float col_to_pool = pool_width_start + step_width_each_bin * w_ind + step_width_each_bin / 2.; float row_to_pool = pool_height_start + step_height_each_bin * h_ind + step_height_each_bin / 2.; int32_t int_col_to_pool = static_cast<int32_t>(col_to_pool); int32_t int_row_to_pool = static_cast<int32_t>(row_to_pool); float float_col_to_pool = col_to_pool - int_col_to_pool; float float_row_to_pool = row_to_pool - int_row_to_pool; atomicAdd(grad_output_start + int_row_to_pool * map_width + int_col_to_pool, static_cast<T>((1. - float_col_to_pool) * (1. - float_row_to_pool) * grad_in)); atomicAdd(grad_output_start + tf_min(int_row_to_pool + 1, map_height - 1) * map_width + int_col_to_pool, static_cast<T>((1. - float_col_to_pool) * float_row_to_pool * grad_in)); atomicAdd(grad_output_start + int_row_to_pool * map_width + tf_min(int_col_to_pool + 1, map_width - 1), static_cast<T>(float_col_to_pool * (1. - float_row_to_pool) * grad_in)); atomicAdd(grad_output_start + tf_min(int_row_to_pool + 1, map_height - 1) * map_width + tf_min(int_col_to_pool + 1, map_width - 1), static_cast<T>(float_col_to_pool * float_row_to_pool * grad_in)); } } } } } template <typename T> void PSROIAlignGradFunctor<GPUDevice, T>::operator()(OpKernelContext* context, const GPUDevice& d, typename TTypes<T>::ConstFlat inputs, typename TTypes<T>::ConstFlat rois, const int32_t grid_dim_width, const int32_t grid_dim_height, typename TTypes<T>::ConstFlat pooled_features_grad, typename TTypes<int32_t>::ConstFlat pooled_index, typename TTypes<T>::Flat grad_output, KDimSize dim_info) { int batch_size = 0; int num_channals = 0; int map_height = 0; int map_width = 0; int num_rois = 0; bool using_max_pool = false; std::tie(batch_size, num_channals, map_height, map_width, num_rois, using_max_pool) = dim_info; CudaLaunchConfig config = GetCudaLaunchConfig(batch_size * num_rois * num_channals, d); //grad_output = grad_output.setZero(); SetZero <<<config.block_count, config.thread_per_block, 0, d.stream()>>> (batch_size * map_height * map_width * num_channals, grad_output.data()); PSROIAlignGradCudaKernel <<<config.block_count, config.thread_per_block, 0, d.stream()>>> (config, inputs.data(), rois.data(), pooled_features_grad.data(), pooled_index.data(), grad_output.data(), grid_dim_width, grid_dim_height, batch_size, num_channals, map_height, map_width, num_rois, using_max_pool); cudaError_t err = cudaGetLastError(); if(cudaSuccess != err) { fprintf( stderr, "cudaCheckError() failed : %s\n", cudaGetErrorString( err ) ); exit( -1 ); } } template struct PSROIAlignGradFunctor<GPUDevice, float>; // #define DEFINE_GPU_SPECS(T) \ // template struct PSROIAlignFunctorGPU<T>; // TF_CALL_GPU_NUMBER_TYPES(DEFINE_GPU_SPECS); #endif // GOOGLE_CUDA
the_stack
* Scan-scatter kernel. The third kernel in a radix-sorting digit-place pass. ******************************************************************************/ #pragma once #include "radixsort_kernel_common.cu" namespace b40c { /** * Register-saving variable qualifier. Can be used when declaring * variables that would otherwise have the same value for all threads in the CTA. */ #if __CUDA_ARCH__ >= 200 #define _B40C_SCANSCATTER_REG_MISER_ __shared__ #else #define _B40C_SCANSCATTER_REG_MISER_ #endif /****************************************************************************** * Appropriate key-substitutes for use by threads that would otherwise index * past the end of valid global data ******************************************************************************/ template <typename T> __device__ __forceinline__ void DefaultExtraValue(T &val) { } // Accomodate bizarre introduction of "signed" for char loads __device__ __forceinline__ void DefaultExtraValue(char &val) { } template <> __device__ __forceinline__ void DefaultExtraValue<unsigned char>(unsigned char &val) { val = (unsigned char) -1; } template <> __device__ __forceinline__ void DefaultExtraValue<unsigned short>(unsigned short &val) { val = (unsigned short) -1; } template <> __device__ __forceinline__ void DefaultExtraValue<unsigned int>(unsigned int &val) { val = (unsigned int) -1; } template <> __device__ __forceinline__ void DefaultExtraValue<unsigned long>(unsigned long &val) { val = (unsigned long) -1; } template <> __device__ __forceinline__ void DefaultExtraValue<unsigned long long>(unsigned long long &val) { val = (unsigned long long) -1; } /****************************************************************************** * Tile-processing Routines ******************************************************************************/ template <typename K, int RADIX_BITS, int BIT> __device__ __forceinline__ int DecodeDigit(K key) { int retval; ExtractKeyBits<K, BIT, RADIX_BITS>::Extract(retval, key); return retval; } template <typename K, int RADIX_BITS, int BIT, int PADDED_PARTIALS_PER_LANE> __device__ __forceinline__ void DecodeDigit( K key, int &digit, int &flag_offset, // in bytes const int LOAD_OFFSET) { const int PADDED_BYTES_PER_LANE = PADDED_PARTIALS_PER_LANE * 4; const int LOAD_OFFSET_BYTES = LOAD_OFFSET * 4; const K QUAD_MASK = (RADIX_BITS < 2) ? 0x1 : 0x3; digit = DecodeDigit<K, RADIX_BITS, BIT>(key); int lane = digit >> 2; int quad_byte = digit & QUAD_MASK; flag_offset = LOAD_OFFSET_BYTES + FastMul(lane, PADDED_BYTES_PER_LANE) + quad_byte; } template <typename K, int RADIX_BITS, int BIT, int LOADS_PER_CYCLE, int SCAN_LANES_PER_LOAD, int PADDED_PARTIALS_PER_LANE> __device__ __forceinline__ void DecodeDigits( typename VecType<K, 2>::Type keypairs[LOADS_PER_CYCLE], int2 digits[LOADS_PER_CYCLE], int2 flag_offsets[LOADS_PER_CYCLE]) // in bytes { if (LOADS_PER_CYCLE > 0) { const int LOAD = 0; const int LOAD_OFFSET = LOAD * SCAN_LANES_PER_LOAD * PADDED_PARTIALS_PER_LANE; DecodeDigit<K, RADIX_BITS, BIT, PADDED_PARTIALS_PER_LANE>( keypairs[LOAD].x, digits[LOAD].x, flag_offsets[LOAD].x, LOAD_OFFSET); DecodeDigit<K, RADIX_BITS, BIT, PADDED_PARTIALS_PER_LANE>( keypairs[LOAD].y, digits[LOAD].y, flag_offsets[LOAD].y, LOAD_OFFSET); } if (LOADS_PER_CYCLE > 1) { const int LOAD = 1; const int LOAD_OFFSET = LOAD * SCAN_LANES_PER_LOAD * PADDED_PARTIALS_PER_LANE; DecodeDigit<K, RADIX_BITS, BIT, PADDED_PARTIALS_PER_LANE>( keypairs[LOAD].x, digits[LOAD].x, flag_offsets[LOAD].x, LOAD_OFFSET); DecodeDigit<K, RADIX_BITS, BIT, PADDED_PARTIALS_PER_LANE>( keypairs[LOAD].y, digits[LOAD].y, flag_offsets[LOAD].y, LOAD_OFFSET); } } template <typename T, CacheModifier CACHE_MODIFIER, typename PreprocessFunctor> __device__ __forceinline__ void GuardedLoad( T *in, typename VecType<T, 2>::Type &pair, int offset, const int &extra_elements, PreprocessFunctor preprocess = PreprocessFunctor()) { if (offset - extra_elements < 0) { GlobalLoad<T, CACHE_MODIFIER>::Ld(pair.x, in, offset); preprocess(pair.x); } else { DefaultExtraValue(pair.x); } if (offset + 1 - extra_elements < 0) { GlobalLoad<T, CACHE_MODIFIER>::Ld(pair.y, in, offset + 1); preprocess(pair.y); } else { DefaultExtraValue(pair.y); } } template <typename T, CacheModifier CACHE_MODIFIER, bool UNGUARDED_IO, int LOADS_PER_CYCLE, typename PreprocessFunctor> struct ReadCycle { __device__ __forceinline__ static void Read( typename VecType<T, 2>::Type *d_in, typename VecType<T, 2>::Type pairs[LOADS_PER_CYCLE], const int BASE2, const int &extra_elements, PreprocessFunctor preprocess = PreprocessFunctor()) { if (UNGUARDED_IO) { // N.B. -- I wish we could do some pragma unrolling here too, but we can't with asm statements inside if (LOADS_PER_CYCLE > 0) GlobalLoad<typename VecType<T, 2>::Type, CACHE_MODIFIER>::Ld( pairs[0], d_in, threadIdx.x + BASE2 + (B40C_RADIXSORT_THREADS * 0)); if (LOADS_PER_CYCLE > 1) GlobalLoad<typename VecType<T, 2>::Type, CACHE_MODIFIER>::Ld( pairs[1], d_in, threadIdx.x + BASE2 + (B40C_RADIXSORT_THREADS * 1)); #pragma unroll for (int LOAD = 0; LOAD < (int) LOADS_PER_CYCLE; LOAD++) { preprocess(pairs[LOAD].x); preprocess(pairs[LOAD].y); } } else { // N.B. -- I wish we could do some pragma unrolling here too, but we can't with asm statements inside if (LOADS_PER_CYCLE > 0) GuardedLoad<T, CACHE_MODIFIER, PreprocessFunctor>( (T*) d_in, pairs[0], (threadIdx.x << 1) + (BASE2 << 1) + (B40C_RADIXSORT_THREADS * 2 * 0), extra_elements); if (LOADS_PER_CYCLE > 1) GuardedLoad<T, CACHE_MODIFIER, PreprocessFunctor>( (T*) d_in, pairs[1], (threadIdx.x << 1) + (BASE2 << 1) + (B40C_RADIXSORT_THREADS * 2 * 1), extra_elements); } } }; template <CacheModifier CACHE_MODIFIER, bool UNGUARDED_IO, int LOADS_PER_CYCLE, typename PreprocessFunctor> struct ReadCycle<KeysOnlyType, CACHE_MODIFIER, UNGUARDED_IO, LOADS_PER_CYCLE, PreprocessFunctor> { __device__ __forceinline__ static void Read( typename VecType<KeysOnlyType, 2>::Type *d_in, typename VecType<KeysOnlyType, 2>::Type pairs[LOADS_PER_CYCLE], const int BASE2, const int &extra_elements, PreprocessFunctor preprocess = PreprocessFunctor()) { // Do nothing for KeysOnlyType } }; template <int LOADS_PER_CYCLE> __device__ __forceinline__ void PlacePartials( unsigned char * base_partial, int2 digits[LOADS_PER_CYCLE], int2 flag_offsets[LOADS_PER_CYCLE]) { #pragma unroll for (int LOAD = 0; LOAD < (int) LOADS_PER_CYCLE; LOAD++) { base_partial[flag_offsets[LOAD].x] = 1; base_partial[flag_offsets[LOAD].y] = 1 + (digits[LOAD].x == digits[LOAD].y); } } template <int LOADS_PER_CYCLE> __device__ __forceinline__ void ExtractRanks( unsigned char * base_partial, int2 digits[LOADS_PER_CYCLE], int2 flag_offsets[LOADS_PER_CYCLE], int2 ranks[LOADS_PER_CYCLE]) { #pragma unroll for (int LOAD = 0; LOAD < (int) LOADS_PER_CYCLE; LOAD++) { ranks[LOAD].x = base_partial[flag_offsets[LOAD].x]; ranks[LOAD].y = base_partial[flag_offsets[LOAD].y] + (digits[LOAD].x == digits[LOAD].y); } } template <int RADIX_DIGITS, int LOADS_PER_CYCLE> __device__ __forceinline__ void UpdateRanks( int2 digits[LOADS_PER_CYCLE], int2 ranks[LOADS_PER_CYCLE], int digit_counts[LOADS_PER_CYCLE][RADIX_DIGITS]) { #pragma unroll for (int LOAD = 0; LOAD < LOADS_PER_CYCLE; LOAD++) { ranks[LOAD].x += digit_counts[LOAD][digits[LOAD].x]; ranks[LOAD].y += digit_counts[LOAD][digits[LOAD].y]; } } template <int RADIX_DIGITS, int CYCLES_PER_TILE, int LOADS_PER_CYCLE> __device__ __forceinline__ void UpdateRanks( int2 digits[CYCLES_PER_TILE][LOADS_PER_CYCLE], int2 ranks[CYCLES_PER_TILE][LOADS_PER_CYCLE], int digit_counts[CYCLES_PER_TILE][LOADS_PER_CYCLE][RADIX_DIGITS]) { #pragma unroll for (int CYCLE = 0; CYCLE < CYCLES_PER_TILE; CYCLE++) { UpdateRanks<RADIX_DIGITS, LOADS_PER_CYCLE>(digits[CYCLE], ranks[CYCLE], digit_counts[CYCLE]); } } template <int SCAN_LANES_PER_CYCLE, int LOG_RAKING_THREADS_PER_LANE, int RAKING_THREADS_PER_LANE, int PARTIALS_PER_SEG> __device__ __forceinline__ void PrefixScanOverLanes( int raking_segment[], int warpscan[SCAN_LANES_PER_CYCLE][3][RAKING_THREADS_PER_LANE], int copy_section) { // Upsweep rake int partial_reduction = SerialReduce<PARTIALS_PER_SEG>(raking_segment); // Warpscan reduction in digit warpscan_lane int warpscan_lane = threadIdx.x >> LOG_RAKING_THREADS_PER_LANE; int group_prefix = WarpScan<RAKING_THREADS_PER_LANE, true>( warpscan[warpscan_lane], partial_reduction, copy_section); // Downsweep rake SerialScan<PARTIALS_PER_SEG>(raking_segment, group_prefix); } template <int SCAN_LANES_PER_CYCLE, int RAKING_THREADS_PER_LANE, int LOADS_PER_CYCLE, int SCAN_LANES_PER_LOAD> __device__ __forceinline__ void RecoverDigitCounts( int warpscan[SCAN_LANES_PER_CYCLE][3][RAKING_THREADS_PER_LANE], int counts[LOADS_PER_CYCLE], int copy_section) { int my_lane = threadIdx.x >> 2; int my_quad_byte = threadIdx.x & 3; #pragma unroll for (int LOAD = 0; LOAD < (int) LOADS_PER_CYCLE; LOAD++) { unsigned char *warpscan_count = (unsigned char *) &warpscan[my_lane + (SCAN_LANES_PER_LOAD * LOAD)][1 + copy_section][RAKING_THREADS_PER_LANE - 1]; counts[LOAD] = warpscan_count[my_quad_byte]; } } template<int RADIX_DIGITS> __device__ __forceinline__ void CorrectLoadOverflow( int2 load_digits, int &load_count) { if (WarpVoteAll(RADIX_DIGITS, load_count <= 1)) { // All keys have same digit load_count = (threadIdx.x == load_digits.x) ? 256 : 0; } } template <int RADIX_DIGITS, int LOADS_PER_CYCLE> __device__ __forceinline__ void CorrectCycleOverflow( int2 cycle_digits[LOADS_PER_CYCLE], int cycle_counts[LOADS_PER_CYCLE]) { // N.B. -- I wish we could do some pragma unrolling here too, but the compiler won't comply, // telling me "Advisory: Loop was not unrolled, unexpected call OPs" if (LOADS_PER_CYCLE > 0) CorrectLoadOverflow<RADIX_DIGITS>(cycle_digits[0], cycle_counts[0]); if (LOADS_PER_CYCLE > 1) CorrectLoadOverflow<RADIX_DIGITS>(cycle_digits[1], cycle_counts[1]); } template <int RADIX_DIGITS, int CYCLES_PER_TILE, int LOADS_PER_CYCLE> __device__ __forceinline__ void CorrectTileOverflow( int2 tile_digits[CYCLES_PER_TILE][LOADS_PER_CYCLE], int tile_counts[CYCLES_PER_TILE][LOADS_PER_CYCLE]) { // N.B. -- I wish we could do some pragma unrolling here too, but the compiler won't comply, // telling me "Advisory: Loop was not unrolled, unexpected call OPs" if (CYCLES_PER_TILE > 0) CorrectCycleOverflow<RADIX_DIGITS, LOADS_PER_CYCLE>(tile_digits[0], tile_counts[0]); if (CYCLES_PER_TILE > 1) CorrectCycleOverflow<RADIX_DIGITS, LOADS_PER_CYCLE>(tile_digits[1], tile_counts[1]); } template <int RADIX_DIGITS> __device__ __forceinline__ void CorrectLastLaneOverflow(int &count, const int &extra_elements) { if (WarpVoteAll(RADIX_DIGITS, count == 0) && (threadIdx.x == RADIX_DIGITS - 1)) { // We're 'f' and we overflowed b/c of invalid 'f' placemarkers; the number of valid items in this load is the count of valid f's count = extra_elements & 255; } } template <int RADIX_DIGITS, int CYCLES_PER_TILE, int LOADS_PER_CYCLE, int LOADS_PER_TILE, bool UNGUARDED_IO> __device__ __forceinline__ void CorrectForOverflows( int2 digits[CYCLES_PER_TILE][LOADS_PER_CYCLE], int counts[CYCLES_PER_TILE][LOADS_PER_CYCLE], const int &extra_elements) { if (!UNGUARDED_IO) { // Correct any overflow in the partially-filled last lane int *linear_counts = (int *) counts; CorrectLastLaneOverflow<RADIX_DIGITS>(linear_counts[LOADS_PER_TILE - 1], extra_elements); } CorrectTileOverflow<RADIX_DIGITS, CYCLES_PER_TILE, LOADS_PER_CYCLE>(digits, counts); } template < typename K, int BIT, int RADIX_BITS, int RADIX_DIGITS, int SCAN_LANES_PER_LOAD, int LOADS_PER_CYCLE, int RAKING_THREADS, int SCAN_LANES_PER_CYCLE, int LOG_RAKING_THREADS_PER_LANE, int RAKING_THREADS_PER_LANE, int PARTIALS_PER_SEG, int PADDED_PARTIALS_PER_LANE, int CYCLES_PER_TILE> __device__ __forceinline__ void ScanCycle( int *base_partial, int *raking_partial, int warpscan[SCAN_LANES_PER_CYCLE][3][RAKING_THREADS_PER_LANE], typename VecType<K, 2>::Type keypairs[LOADS_PER_CYCLE], int2 digits[LOADS_PER_CYCLE], int2 flag_offsets[LOADS_PER_CYCLE], int2 ranks[LOADS_PER_CYCLE], int copy_section) { // Reset smem #pragma unroll for (int SCAN_LANE = 0; SCAN_LANE < (int) SCAN_LANES_PER_CYCLE; SCAN_LANE++) { base_partial[SCAN_LANE * PADDED_PARTIALS_PER_LANE] = 0; } // Decode digits for first cycle DecodeDigits<K, RADIX_BITS, BIT, LOADS_PER_CYCLE, SCAN_LANES_PER_LOAD, PADDED_PARTIALS_PER_LANE>( keypairs, digits, flag_offsets); // Encode counts into smem for first cycle PlacePartials<LOADS_PER_CYCLE>( (unsigned char *) base_partial, digits, flag_offsets); __syncthreads(); // Intra-group prefix scans for first cycle if (threadIdx.x < RAKING_THREADS) { PrefixScanOverLanes<SCAN_LANES_PER_CYCLE, LOG_RAKING_THREADS_PER_LANE, RAKING_THREADS_PER_LANE, PARTIALS_PER_SEG>( // first cycle is offset right by one raking_partial, warpscan, copy_section); } __syncthreads(); // Extract ranks ExtractRanks<LOADS_PER_CYCLE>( (unsigned char *) base_partial, digits, flag_offsets, ranks); } /****************************************************************************** * SM1.3 Local Exchange Routines * * Routines for exchanging keys (and values) in shared memory (i.e., local * scattering) in order to to facilitate coalesced global scattering ******************************************************************************/ template <typename T, bool UNGUARDED_IO, int CYCLES_PER_TILE, int LOADS_PER_CYCLE, typename PostprocessFunctor> __device__ __forceinline__ void ScatterLoads( T *d_out, typename VecType<T, 2>::Type pairs[LOADS_PER_CYCLE], int2 offsets[LOADS_PER_CYCLE], const int BASE4, const int &extra_elements, PostprocessFunctor postprocess = PostprocessFunctor()) { #pragma unroll for (int LOAD = 0; LOAD < (int) LOADS_PER_CYCLE; LOAD++) { postprocess(pairs[LOAD].x); postprocess(pairs[LOAD].y); if (UNGUARDED_IO || (threadIdx.x + BASE4 + (B40C_RADIXSORT_THREADS * (LOAD * 2 + 0)) < extra_elements)) d_out[offsets[LOAD].x] = pairs[LOAD].x; if (UNGUARDED_IO || (threadIdx.x + BASE4 + (B40C_RADIXSORT_THREADS * (LOAD * 2 + 1)) < extra_elements)) d_out[offsets[LOAD].y] = pairs[LOAD].y; } } template <typename T, int CYCLES_PER_TILE, int LOADS_PER_CYCLE> __device__ __forceinline__ void PushPairs( T *swap, typename VecType<T, 2>::Type pairs[CYCLES_PER_TILE][LOADS_PER_CYCLE], int2 ranks[CYCLES_PER_TILE][LOADS_PER_CYCLE]) { #pragma unroll for (int CYCLE = 0; CYCLE < (int) CYCLES_PER_TILE; CYCLE++) { #pragma unroll for (int LOAD = 0; LOAD < (int) LOADS_PER_CYCLE; LOAD++) { swap[ranks[CYCLE][LOAD].x] = pairs[CYCLE][LOAD].x; swap[ranks[CYCLE][LOAD].y] = pairs[CYCLE][LOAD].y; } } } template <typename T, int CYCLES_PER_TILE, int LOADS_PER_CYCLE> __device__ __forceinline__ void ExchangePairs( T *swap, typename VecType<T, 2>::Type pairs[CYCLES_PER_TILE][LOADS_PER_CYCLE], int2 ranks[CYCLES_PER_TILE][LOADS_PER_CYCLE]) { // Push in Pairs PushPairs<T, CYCLES_PER_TILE, LOADS_PER_CYCLE>(swap, pairs, ranks); __syncthreads(); // Extract pairs #pragma unroll for (int CYCLE = 0; CYCLE < (int) CYCLES_PER_TILE; CYCLE++) { #pragma unroll for (int LOAD = 0; LOAD < (int) LOADS_PER_CYCLE; LOAD++) { const int BLOCK = ((CYCLE * LOADS_PER_CYCLE) + LOAD) * 2; pairs[CYCLE][LOAD].x = swap[threadIdx.x + (B40C_RADIXSORT_THREADS * (BLOCK + 0))]; pairs[CYCLE][LOAD].y = swap[threadIdx.x + (B40C_RADIXSORT_THREADS * (BLOCK + 1))]; } } } template < typename K, typename V, CacheModifier CACHE_MODIFIER, int RADIX_BITS, int RADIX_DIGITS, int BIT, int CYCLES_PER_TILE, int LOADS_PER_CYCLE, bool UNGUARDED_IO, typename PostprocessFunctor> __device__ __forceinline__ void SwapAndScatterSm13( typename VecType<K, 2>::Type keypairs[CYCLES_PER_TILE][LOADS_PER_CYCLE], int2 ranks[CYCLES_PER_TILE][LOADS_PER_CYCLE], int *exchange, typename VecType<V, 2>::Type *d_in_values, K *d_out_keys, V *d_out_values, int digit_carry[RADIX_DIGITS], const int &extra_elements) { int2 offsets[CYCLES_PER_TILE][LOADS_PER_CYCLE]; // Swap keys according to ranks ExchangePairs<K, CYCLES_PER_TILE, LOADS_PER_CYCLE>((K*) exchange, keypairs, ranks); // Calculate scatter offsets (re-decode digits from keys: it's less work than making a second exchange of digits) if (CYCLES_PER_TILE > 0) { const int CYCLE = 0; if (LOADS_PER_CYCLE > 0) { const int LOAD = 0; const int BLOCK = ((CYCLE * LOADS_PER_CYCLE) + LOAD) * 2; offsets[CYCLE][LOAD].x = threadIdx.x + (B40C_RADIXSORT_THREADS * (BLOCK + 0)) + digit_carry[DecodeDigit<K, RADIX_BITS, BIT>(keypairs[CYCLE][LOAD].x)]; offsets[CYCLE][LOAD].y = threadIdx.x + (B40C_RADIXSORT_THREADS * (BLOCK + 1)) + digit_carry[DecodeDigit<K, RADIX_BITS, BIT>(keypairs[CYCLE][LOAD].y)]; } if (LOADS_PER_CYCLE > 1) { const int LOAD = 1; const int BLOCK = ((CYCLE * LOADS_PER_CYCLE) + LOAD) * 2; offsets[CYCLE][LOAD].x = threadIdx.x + (B40C_RADIXSORT_THREADS * (BLOCK + 0)) + digit_carry[DecodeDigit<K, RADIX_BITS, BIT>(keypairs[CYCLE][LOAD].x)]; offsets[CYCLE][LOAD].y = threadIdx.x + (B40C_RADIXSORT_THREADS * (BLOCK + 1)) + digit_carry[DecodeDigit<K, RADIX_BITS, BIT>(keypairs[CYCLE][LOAD].y)]; } } if (CYCLES_PER_TILE > 1) { const int CYCLE = 1; if (LOADS_PER_CYCLE > 0) { const int LOAD = 0; const int BLOCK = ((CYCLE * LOADS_PER_CYCLE) + LOAD) * 2; offsets[CYCLE][LOAD].x = threadIdx.x + (B40C_RADIXSORT_THREADS * (BLOCK + 0)) + digit_carry[DecodeDigit<K, RADIX_BITS, BIT>(keypairs[CYCLE][LOAD].x)]; offsets[CYCLE][LOAD].y = threadIdx.x + (B40C_RADIXSORT_THREADS * (BLOCK + 1)) + digit_carry[DecodeDigit<K, RADIX_BITS, BIT>(keypairs[CYCLE][LOAD].y)]; } if (LOADS_PER_CYCLE > 1) { const int LOAD = 1; const int BLOCK = ((CYCLE * LOADS_PER_CYCLE) + LOAD) * 2; offsets[CYCLE][LOAD].x = threadIdx.x + (B40C_RADIXSORT_THREADS * (BLOCK + 0)) + digit_carry[DecodeDigit<K, RADIX_BITS, BIT>(keypairs[CYCLE][LOAD].x)]; offsets[CYCLE][LOAD].y = threadIdx.x + (B40C_RADIXSORT_THREADS * (BLOCK + 1)) + digit_carry[DecodeDigit<K, RADIX_BITS, BIT>(keypairs[CYCLE][LOAD].y)]; } } // Scatter keys #pragma unroll for (int CYCLE = 0; CYCLE < (int) CYCLES_PER_TILE; CYCLE++) { const int BLOCK = CYCLE * LOADS_PER_CYCLE * 2; ScatterLoads<K, UNGUARDED_IO, CYCLES_PER_TILE, LOADS_PER_CYCLE, PostprocessFunctor>(d_out_keys, keypairs[CYCLE], offsets[CYCLE], B40C_RADIXSORT_THREADS * BLOCK, extra_elements); } if (!IsKeysOnly<V>()) { __syncthreads(); // Read input data typename VecType<V, 2>::Type datapairs[CYCLES_PER_TILE][LOADS_PER_CYCLE]; // N.B. -- I wish we could do some pragma unrolling here too, but the compiler won't comply, // telling me "Advisory: Loop was not unrolled, unexpected control flow" if (CYCLES_PER_TILE > 0) ReadCycle<V, CACHE_MODIFIER, UNGUARDED_IO, LOADS_PER_CYCLE, NopFunctor<V> >::Read(d_in_values, datapairs[0], B40C_RADIXSORT_THREADS * LOADS_PER_CYCLE * 0, extra_elements); if (CYCLES_PER_TILE > 1) ReadCycle<V, CACHE_MODIFIER, UNGUARDED_IO, LOADS_PER_CYCLE, NopFunctor<V> >::Read(d_in_values, datapairs[1], B40C_RADIXSORT_THREADS * LOADS_PER_CYCLE * 1, extra_elements); // Swap data according to ranks ExchangePairs<V, CYCLES_PER_TILE, LOADS_PER_CYCLE>((V*) exchange, datapairs, ranks); // Scatter data #pragma unroll for (int CYCLE = 0; CYCLE < (int) CYCLES_PER_TILE; CYCLE++) { const int BLOCK = CYCLE * LOADS_PER_CYCLE * 2; ScatterLoads<V, UNGUARDED_IO, CYCLES_PER_TILE, LOADS_PER_CYCLE, NopFunctor<V> >(d_out_values, datapairs[CYCLE], offsets[CYCLE], B40C_RADIXSORT_THREADS * BLOCK, extra_elements); } } } /****************************************************************************** * SM1.0 Local Exchange Routines * * Routines for exchanging keys (and values) in shared memory (i.e., local * scattering) in order to to facilitate coalesced global scattering ******************************************************************************/ template < typename T, int RADIX_DIGITS, bool UNGUARDED_IO, typename PostprocessFunctor> __device__ __forceinline__ void ScatterCycle( T *swapmem, T *d_out, int digit_scan[2][RADIX_DIGITS], int digit_carry[RADIX_DIGITS], const int &extra_elements, int base_digit, PostprocessFunctor postprocess = PostprocessFunctor()) { const int LOG_STORE_TXN_THREADS = B40C_LOG_MEM_BANKS(__CUDA_ARCH__); const int STORE_TXN_THREADS = 1 << LOG_STORE_TXN_THREADS; int store_txn_idx = threadIdx.x & (STORE_TXN_THREADS - 1); int store_txn_digit = threadIdx.x >> LOG_STORE_TXN_THREADS; int my_digit = base_digit + store_txn_digit; if (my_digit < RADIX_DIGITS) { int my_exclusive_scan = digit_scan[1][my_digit - 1]; int my_inclusive_scan = digit_scan[1][my_digit]; int my_digit_count = my_inclusive_scan - my_exclusive_scan; int my_carry = digit_carry[my_digit] + my_exclusive_scan; int my_aligned_offset = store_txn_idx - (my_carry & (STORE_TXN_THREADS - 1)); while (my_aligned_offset < my_digit_count) { if ((my_aligned_offset >= 0) && (UNGUARDED_IO || (my_exclusive_scan + my_aligned_offset < extra_elements))) { T datum = swapmem[my_exclusive_scan + my_aligned_offset]; postprocess(datum); d_out[my_carry + my_aligned_offset] = datum; } my_aligned_offset += STORE_TXN_THREADS; } } } template < typename T, int RADIX_DIGITS, int CYCLES_PER_TILE, int LOADS_PER_CYCLE, bool UNGUARDED_IO, typename PostprocessFunctor> __device__ __forceinline__ void SwapAndScatterPairs( typename VecType<T, 2>::Type pairs[CYCLES_PER_TILE][LOADS_PER_CYCLE], int2 ranks[CYCLES_PER_TILE][LOADS_PER_CYCLE], T *exchange, T *d_out, int digit_carry[RADIX_DIGITS], int digit_scan[2][RADIX_DIGITS], const int &extra_elements) { const int SCATTER_CYCLE_DIGITS = B40C_RADIXSORT_WARPS * (B40C_WARP_THREADS / B40C_MEM_BANKS(__CUDA_ARCH__)); const int SCATTER_CYCLES = RADIX_DIGITS / SCATTER_CYCLE_DIGITS; // Push in pairs PushPairs<T, CYCLES_PER_TILE, LOADS_PER_CYCLE>(exchange, pairs, ranks); __syncthreads(); // N.B. -- I wish we could do some pragma unrolling here too, but the compiler won't comply, // telling me "Advisory: Loop was not unrolled, not an innermost loop" if (SCATTER_CYCLES > 0) ScatterCycle<T, RADIX_DIGITS, UNGUARDED_IO, PostprocessFunctor>(exchange, d_out, digit_scan, digit_carry, extra_elements, SCATTER_CYCLE_DIGITS * 0); if (SCATTER_CYCLES > 1) ScatterCycle<T, RADIX_DIGITS, UNGUARDED_IO, PostprocessFunctor>(exchange, d_out, digit_scan, digit_carry, extra_elements, SCATTER_CYCLE_DIGITS * 1); if (SCATTER_CYCLES > 2) ScatterCycle<T, RADIX_DIGITS, UNGUARDED_IO, PostprocessFunctor>(exchange, d_out, digit_scan, digit_carry, extra_elements, SCATTER_CYCLE_DIGITS * 2); if (SCATTER_CYCLES > 3) ScatterCycle<T, RADIX_DIGITS, UNGUARDED_IO, PostprocessFunctor>(exchange, d_out, digit_scan, digit_carry, extra_elements, SCATTER_CYCLE_DIGITS * 3); if (SCATTER_CYCLES > 4) ScatterCycle<T, RADIX_DIGITS, UNGUARDED_IO, PostprocessFunctor>(exchange, d_out, digit_scan, digit_carry, extra_elements, SCATTER_CYCLE_DIGITS * 4); if (SCATTER_CYCLES > 5) ScatterCycle<T, RADIX_DIGITS, UNGUARDED_IO, PostprocessFunctor>(exchange, d_out, digit_scan, digit_carry, extra_elements, SCATTER_CYCLE_DIGITS * 5); if (SCATTER_CYCLES > 6) ScatterCycle<T, RADIX_DIGITS, UNGUARDED_IO, PostprocessFunctor>(exchange, d_out, digit_scan, digit_carry, extra_elements, SCATTER_CYCLE_DIGITS * 6); if (SCATTER_CYCLES > 7) ScatterCycle<T, RADIX_DIGITS, UNGUARDED_IO, PostprocessFunctor>(exchange, d_out, digit_scan, digit_carry, extra_elements, SCATTER_CYCLE_DIGITS * 7); } template < typename K, typename V, CacheModifier CACHE_MODIFIER, int RADIX_DIGITS, int CYCLES_PER_TILE, int LOADS_PER_CYCLE, bool UNGUARDED_IO, typename PostprocessFunctor> __device__ __forceinline__ void SwapAndScatterSm10( typename VecType<K, 2>::Type keypairs[CYCLES_PER_TILE][LOADS_PER_CYCLE], int2 ranks[CYCLES_PER_TILE][LOADS_PER_CYCLE], int *exchange, typename VecType<V, 2>::Type *d_in_values, K *d_out_keys, V *d_out_values, int digit_carry[RADIX_DIGITS], int digit_scan[2][RADIX_DIGITS], const int &extra_elements) { // Swap and scatter keys SwapAndScatterPairs<K, RADIX_DIGITS, CYCLES_PER_TILE, LOADS_PER_CYCLE, UNGUARDED_IO, PostprocessFunctor>( keypairs, ranks, (K*) exchange, d_out_keys, digit_carry, digit_scan, extra_elements); if (!IsKeysOnly<V>()) { __syncthreads(); // N.B. -- I wish we could do some pragma unrolling here too, but the compiler won't comply, // telling me "Advisory: Loop was not unrolled, unexpected control flow" // Read input data typename VecType<V, 2>::Type datapairs[CYCLES_PER_TILE][LOADS_PER_CYCLE]; if (CYCLES_PER_TILE > 0) ReadCycle<V, CACHE_MODIFIER, UNGUARDED_IO, LOADS_PER_CYCLE, NopFunctor<V> >::Read(d_in_values, datapairs[0], B40C_RADIXSORT_THREADS * LOADS_PER_CYCLE * 0, extra_elements); if (CYCLES_PER_TILE > 1) ReadCycle<V, CACHE_MODIFIER, UNGUARDED_IO, LOADS_PER_CYCLE, NopFunctor<V> >::Read(d_in_values, datapairs[1], B40C_RADIXSORT_THREADS * LOADS_PER_CYCLE * 1, extra_elements); // Swap and scatter data SwapAndScatterPairs<V, RADIX_DIGITS, CYCLES_PER_TILE, LOADS_PER_CYCLE, UNGUARDED_IO, NopFunctor<V> >( datapairs, ranks, (V*) exchange, d_out_values, digit_carry, digit_scan, extra_elements); } } /****************************************************************************** * Tile of RADIXSORT_TILE_ELEMENTS keys (and values) ******************************************************************************/ template < typename K, typename V, CacheModifier CACHE_MODIFIER, int BIT, bool UNGUARDED_IO, int RADIX_BITS, int RADIX_DIGITS, int SCAN_LANES_PER_LOAD, int LOADS_PER_CYCLE, int CYCLES_PER_TILE, int SCAN_LANES_PER_CYCLE, int RAKING_THREADS, int LOG_RAKING_THREADS_PER_LANE, int RAKING_THREADS_PER_LANE, int PARTIALS_PER_SEG, int PARTIALS_PER_ROW, int ROWS_PER_LANE, typename PreprocessFunctor, typename PostprocessFunctor> __device__ __forceinline__ void ScanDigitTile( typename VecType<K, 2>::Type *d_in_keys, typename VecType<V, 2>::Type *d_in_values, K *d_out_keys, V *d_out_values, int *exchange, int warpscan[SCAN_LANES_PER_CYCLE][3][RAKING_THREADS_PER_LANE], int digit_carry[RADIX_DIGITS], int digit_scan[2][RADIX_DIGITS], int digit_counts[CYCLES_PER_TILE][LOADS_PER_CYCLE][RADIX_DIGITS], int *base_partial, int *raking_partial, const int &extra_elements) { const int PADDED_PARTIALS_PER_LANE = ROWS_PER_LANE * (PARTIALS_PER_ROW + 1); const int LOADS_PER_TILE = CYCLES_PER_TILE * LOADS_PER_CYCLE; // N.B.: We use the following voodoo incantations to elide the compiler's miserable // "declared but never referenced" warnings for these (which are actually used for // template instantiation) SuppressUnusedConstantWarning(PADDED_PARTIALS_PER_LANE); SuppressUnusedConstantWarning(LOADS_PER_TILE); typename VecType<K, 2>::Type keypairs[CYCLES_PER_TILE][LOADS_PER_CYCLE]; int2 digits[CYCLES_PER_TILE][LOADS_PER_CYCLE]; int2 flag_offsets[CYCLES_PER_TILE][LOADS_PER_CYCLE]; // a byte offset int2 ranks[CYCLES_PER_TILE][LOADS_PER_CYCLE]; //------------------------------------------------------------------------- // Read keys //------------------------------------------------------------------------- // N.B. -- I wish we could do some pragma unrolling here too, but the compiler won't comply, // telling me "Advisory: Loop was not unrolled, unexpected control flow construct" // Read Keys if (CYCLES_PER_TILE > 0) ReadCycle<K, CACHE_MODIFIER, UNGUARDED_IO, LOADS_PER_CYCLE, PreprocessFunctor>::Read(d_in_keys, keypairs[0], B40C_RADIXSORT_THREADS * LOADS_PER_CYCLE * 0, extra_elements); if (CYCLES_PER_TILE > 1) ReadCycle<K, CACHE_MODIFIER, UNGUARDED_IO, LOADS_PER_CYCLE, PreprocessFunctor>::Read(d_in_keys, keypairs[1], B40C_RADIXSORT_THREADS * LOADS_PER_CYCLE * 1, extra_elements); //------------------------------------------------------------------------- // Lane-scanning Cycles //------------------------------------------------------------------------- if (CYCLES_PER_TILE > 0) { const int CYCLE = 0; ScanCycle<K, BIT, RADIX_BITS, RADIX_DIGITS, SCAN_LANES_PER_LOAD, LOADS_PER_CYCLE, RAKING_THREADS, SCAN_LANES_PER_CYCLE, LOG_RAKING_THREADS_PER_LANE, RAKING_THREADS_PER_LANE, PARTIALS_PER_SEG, PADDED_PARTIALS_PER_LANE, CYCLES_PER_TILE>( base_partial, raking_partial, warpscan, keypairs[CYCLE], digits[CYCLE], flag_offsets[CYCLE], ranks[CYCLE], CYCLES_PER_TILE - CYCLE - 1); // lower cycles get copied right } if (CYCLES_PER_TILE > 1) { const int CYCLE = 1; ScanCycle<K, BIT, RADIX_BITS, RADIX_DIGITS, SCAN_LANES_PER_LOAD, LOADS_PER_CYCLE, RAKING_THREADS, SCAN_LANES_PER_CYCLE, LOG_RAKING_THREADS_PER_LANE, RAKING_THREADS_PER_LANE, PARTIALS_PER_SEG, PADDED_PARTIALS_PER_LANE, CYCLES_PER_TILE>( base_partial, raking_partial, warpscan, keypairs[CYCLE], digits[CYCLE], flag_offsets[CYCLE], ranks[CYCLE], CYCLES_PER_TILE - CYCLE - 1); // lower cycles get copied right } //------------------------------------------------------------------------- // Digit-scanning //------------------------------------------------------------------------- // Recover second-half digit-counts, scan across all digit-counts if (threadIdx.x < RADIX_DIGITS) { int counts[CYCLES_PER_TILE][LOADS_PER_CYCLE]; // Recover digit-counts from warpscan padding #pragma unroll for (int CYCLE = 0; CYCLE < (int) CYCLES_PER_TILE; CYCLE++) { RecoverDigitCounts<SCAN_LANES_PER_CYCLE, RAKING_THREADS_PER_LANE, LOADS_PER_CYCLE, SCAN_LANES_PER_LOAD>( // first cycle, offset by 1 warpscan, counts[CYCLE], CYCLES_PER_TILE - CYCLE - 1); // lower cycles get copied right } // Check for overflows CorrectForOverflows<RADIX_DIGITS, CYCLES_PER_TILE, LOADS_PER_CYCLE, LOADS_PER_TILE, UNGUARDED_IO>( digits, counts, extra_elements); // Scan across my digit counts for each load int exclusive_total = 0; int inclusive_total = 0; #pragma unroll for (int CYCLE = 0; CYCLE < (int) CYCLES_PER_TILE; CYCLE++) { #pragma unroll for (int LOAD = 0; LOAD < (int) LOADS_PER_CYCLE; LOAD++) { inclusive_total += counts[CYCLE][LOAD]; counts[CYCLE][LOAD] = exclusive_total; exclusive_total = inclusive_total; } } // second half of digit_carry update int my_carry = digit_carry[threadIdx.x] + digit_scan[1][threadIdx.x]; // Perform overflow-free SIMD Kogge-Stone across digits int digit_prefix = WarpScan<RADIX_DIGITS, false>( digit_scan, inclusive_total, 0); // first-half of digit_carry update digit_carry[threadIdx.x] = my_carry - digit_prefix; #pragma unroll for (int CYCLE = 0; CYCLE < (int) CYCLES_PER_TILE; CYCLE++) { #pragma unroll for (int LOAD = 0; LOAD < (int) LOADS_PER_CYCLE; LOAD++) { digit_counts[CYCLE][LOAD][threadIdx.x] = counts[CYCLE][LOAD] + digit_prefix; } } } __syncthreads(); //------------------------------------------------------------------------- // Update Ranks //------------------------------------------------------------------------- UpdateRanks<RADIX_DIGITS, CYCLES_PER_TILE, LOADS_PER_CYCLE>(digits, ranks, digit_counts); //------------------------------------------------------------------------- // Scatter //------------------------------------------------------------------------- #if ((__CUDA_ARCH__ < 130) || FERMI_ECC) SwapAndScatterSm10<K, V, CACHE_MODIFIER, RADIX_DIGITS, CYCLES_PER_TILE, LOADS_PER_CYCLE, UNGUARDED_IO, PostprocessFunctor>( keypairs, ranks, exchange, d_in_values, d_out_keys, d_out_values, digit_carry, digit_scan, extra_elements); #else SwapAndScatterSm13<K, V, CACHE_MODIFIER, RADIX_BITS, RADIX_DIGITS, BIT, CYCLES_PER_TILE, LOADS_PER_CYCLE, UNGUARDED_IO, PostprocessFunctor>( keypairs, ranks, exchange, d_in_values, d_out_keys, d_out_values, digit_carry, extra_elements); #endif __syncthreads(); } template < typename K, typename V, CacheModifier CACHE_MODIFIER, int BIT, int RADIX_BITS, int RADIX_DIGITS, int SCAN_LANES_PER_LOAD, int LOADS_PER_CYCLE, int CYCLES_PER_TILE, int SCAN_LANES_PER_CYCLE, int RAKING_THREADS, int LOG_RAKING_THREADS_PER_LANE, int RAKING_THREADS_PER_LANE, int PARTIALS_PER_SEG, int PARTIALS_PER_ROW, int ROWS_PER_LANE, int TILE_ELEMENTS, typename PreprocessFunctor, typename PostprocessFunctor> __device__ __forceinline__ void ScanScatterDigitPass( int *d_spine, K *d_in_keys, V *d_in_values, K *d_out_keys, V *d_out_values, int *exchange, int warpscan[SCAN_LANES_PER_CYCLE][3][RAKING_THREADS_PER_LANE], int digit_carry[RADIX_DIGITS], int digit_scan[2][RADIX_DIGITS], int digit_counts[CYCLES_PER_TILE][LOADS_PER_CYCLE][RADIX_DIGITS], int *base_partial, int *raking_partial, int block_offset, const int &out_of_bounds, const int &extra_elements) { if (threadIdx.x < RADIX_DIGITS) { // Reset reused portion of digit_scan digit_scan[1][threadIdx.x] = 0; // Read digit_carry in parallel int spine_digit_offset = FastMul(gridDim.x, threadIdx.x) + blockIdx.x; int my_digit_carry; GlobalLoad<int, CACHE_MODIFIER>::Ld(my_digit_carry, d_spine, spine_digit_offset); digit_carry[threadIdx.x] = my_digit_carry; } // Scan in tiles of tile_elements while (block_offset < out_of_bounds) { ScanDigitTile<K, V, CACHE_MODIFIER, BIT, true, RADIX_BITS, RADIX_DIGITS, SCAN_LANES_PER_LOAD, LOADS_PER_CYCLE, CYCLES_PER_TILE, SCAN_LANES_PER_CYCLE, RAKING_THREADS, LOG_RAKING_THREADS_PER_LANE, RAKING_THREADS_PER_LANE, PARTIALS_PER_SEG, PARTIALS_PER_ROW, ROWS_PER_LANE, PreprocessFunctor, PostprocessFunctor>( reinterpret_cast<typename VecType<K, 2>::Type *>(&d_in_keys[block_offset]), reinterpret_cast<typename VecType<V, 2>::Type *>(&d_in_values[block_offset]), d_out_keys, d_out_values, exchange, warpscan, digit_carry, digit_scan, digit_counts, base_partial, raking_partial, extra_elements); block_offset += TILE_ELEMENTS; } if (extra_elements) { // Clean up with guarded-io ScanDigitTile<K, V, CACHE_MODIFIER, BIT, false, RADIX_BITS, RADIX_DIGITS, SCAN_LANES_PER_LOAD, LOADS_PER_CYCLE, CYCLES_PER_TILE, SCAN_LANES_PER_CYCLE, RAKING_THREADS, LOG_RAKING_THREADS_PER_LANE, RAKING_THREADS_PER_LANE, PARTIALS_PER_SEG, PARTIALS_PER_ROW, ROWS_PER_LANE, PreprocessFunctor, PostprocessFunctor>( reinterpret_cast<typename VecType<K, 2>::Type *>(&d_in_keys[block_offset]), reinterpret_cast<typename VecType<V, 2>::Type *>(&d_in_values[block_offset]), d_out_keys, d_out_values, exchange, warpscan, digit_carry, digit_scan, digit_counts, base_partial, raking_partial, extra_elements); } } template < typename K, typename V, int PASS, int RADIX_BITS, int BIT, typename PreprocessFunctor, typename PostprocessFunctor> __launch_bounds__ (B40C_RADIXSORT_THREADS, B40C_RADIXSORT_SCAN_SCATTER_CTA_OCCUPANCY(__CUDA_ARCH__)) __global__ void LsbScanScatterKernel( int *d_selectors, int* d_spine, K* d_keys0, K* d_keys1, V* d_values0, V* d_values1, CtaDecomposition work_decomposition) { const int RADIX_DIGITS = 1 << RADIX_BITS; const int TILE_ELEMENTS = B40C_RADIXSORT_TILE_ELEMENTS(__CUDA_ARCH__, K, V); const int LOG_SCAN_LANES_PER_LOAD = (RADIX_BITS > 2) ? RADIX_BITS - 2 : 0; // Always at one lane per load const int SCAN_LANES_PER_LOAD = 1 << LOG_SCAN_LANES_PER_LOAD; const int LOG_LOADS_PER_CYCLE = B40C_RADIXSORT_LOG_LOADS_PER_CYCLE(__CUDA_ARCH__); const int LOADS_PER_CYCLE = 1 << LOG_LOADS_PER_CYCLE; const int LOG_CYCLES_PER_TILE = B40C_RADIXSORT_LOG_CYCLES_PER_TILE(__CUDA_ARCH__, K, V); const int CYCLES_PER_TILE = 1 << LOG_CYCLES_PER_TILE; const int LOG_SCAN_LANES_PER_CYCLE = LOG_LOADS_PER_CYCLE + LOG_SCAN_LANES_PER_LOAD; const int SCAN_LANES_PER_CYCLE = 1 << LOG_SCAN_LANES_PER_CYCLE; const int LOG_PARTIALS_PER_LANE = B40C_RADIXSORT_LOG_THREADS; const int LOG_PARTIALS_PER_CYCLE = LOG_SCAN_LANES_PER_CYCLE + LOG_PARTIALS_PER_LANE; const int LOG_RAKING_THREADS = B40C_RADIXSORT_LOG_RAKING_THREADS(__CUDA_ARCH__); const int RAKING_THREADS = 1 << LOG_RAKING_THREADS; const int LOG_RAKING_THREADS_PER_LANE = LOG_RAKING_THREADS - LOG_SCAN_LANES_PER_CYCLE; const int RAKING_THREADS_PER_LANE = 1 << LOG_RAKING_THREADS_PER_LANE; const int LOG_PARTIALS_PER_SEG = LOG_PARTIALS_PER_LANE - LOG_RAKING_THREADS_PER_LANE; const int PARTIALS_PER_SEG = 1 << LOG_PARTIALS_PER_SEG; const int LOG_PARTIALS_PER_ROW = (LOG_PARTIALS_PER_SEG < B40C_LOG_MEM_BANKS(__CUDA_ARCH__)) ? B40C_LOG_MEM_BANKS(__CUDA_ARCH__) : LOG_PARTIALS_PER_SEG; // floor of MEM_BANKS partials per row const int PARTIALS_PER_ROW = 1 << LOG_PARTIALS_PER_ROW; const int PADDED_PARTIALS_PER_ROW = PARTIALS_PER_ROW + 1; const int LOG_SEGS_PER_ROW = LOG_PARTIALS_PER_ROW - LOG_PARTIALS_PER_SEG; const int SEGS_PER_ROW = 1 << LOG_SEGS_PER_ROW; const int LOG_ROWS_PER_LOAD = LOG_PARTIALS_PER_CYCLE - LOG_PARTIALS_PER_ROW; const int LOG_ROWS_PER_LANE = LOG_PARTIALS_PER_LANE - LOG_PARTIALS_PER_ROW; const int ROWS_PER_LANE = 1 << LOG_ROWS_PER_LANE; const int LOG_ROWS_PER_CYCLE = LOG_SCAN_LANES_PER_CYCLE + LOG_ROWS_PER_LANE; const int ROWS_PER_CYCLE = 1 << LOG_ROWS_PER_CYCLE; const int SCAN_LANE_BYTES = ROWS_PER_CYCLE * PADDED_PARTIALS_PER_ROW * sizeof(int); const int MAX_EXCHANGE_BYTES = (sizeof(K) > sizeof(V)) ? TILE_ELEMENTS * sizeof(K) : TILE_ELEMENTS * sizeof(V); const int SCAN_LANE_INT4S = (B40C_MAX(MAX_EXCHANGE_BYTES, SCAN_LANE_BYTES) + sizeof(int4) - 1) / sizeof(int4); // N.B.: We use the following voodoo incantations to elide the compiler's miserable // "declared but never referenced" warnings for these (which are actually used for // template instantiation) SuppressUnusedConstantWarning(SCAN_LANES_PER_LOAD); SuppressUnusedConstantWarning(PARTIALS_PER_SEG); SuppressUnusedConstantWarning(LOG_ROWS_PER_LOAD); SuppressUnusedConstantWarning(ROWS_PER_LANE); // scan_lanes is a int4[] to avoid alignment issues when casting to (K *) and/or (V *) __shared__ int4 scan_lanes[SCAN_LANE_INT4S]; __shared__ int warpscan[SCAN_LANES_PER_CYCLE][3][RAKING_THREADS_PER_LANE]; // One warpscan per fours-group __shared__ int digit_carry[RADIX_DIGITS]; __shared__ int digit_scan[2][RADIX_DIGITS]; __shared__ int digit_counts[CYCLES_PER_TILE][LOADS_PER_CYCLE][RADIX_DIGITS]; __shared__ bool non_trivial_digit_pass; __shared__ int selector; _B40C_SCANSCATTER_REG_MISER_ int extra_elements; _B40C_SCANSCATTER_REG_MISER_ int out_of_bounds; // calculate our threadblock's range int block_elements, block_offset; if (blockIdx.x < work_decomposition.num_big_blocks) { block_offset = work_decomposition.big_block_elements * blockIdx.x; block_elements = work_decomposition.big_block_elements; } else { block_offset = (work_decomposition.normal_block_elements * blockIdx.x) + (work_decomposition.num_big_blocks * TILE_ELEMENTS); block_elements = work_decomposition.normal_block_elements; } extra_elements = 0; if (blockIdx.x == gridDim.x - 1) { extra_elements = work_decomposition.extra_elements_last_block; if (extra_elements) { block_elements -= TILE_ELEMENTS; } } out_of_bounds = block_offset + block_elements; // location for placing 2-element partial reductions in the first lane of a cycle int row = threadIdx.x >> LOG_PARTIALS_PER_ROW; int col = threadIdx.x & (PARTIALS_PER_ROW - 1); int *base_partial = reinterpret_cast<int *>(scan_lanes) + (row * PADDED_PARTIALS_PER_ROW) + col; // location for raking across all loads within a cycle int *raking_partial = 0; if (threadIdx.x < RAKING_THREADS) { // initalize lane warpscans if (threadIdx.x < RAKING_THREADS_PER_LANE) { #pragma unroll for (int SCAN_LANE = 0; SCAN_LANE < (int) SCAN_LANES_PER_CYCLE; SCAN_LANE++) { warpscan[SCAN_LANE][0][threadIdx.x] = 0; } } // initialize digit warpscans if (threadIdx.x < RADIX_DIGITS) { // Initialize digit_scan digit_scan[0][threadIdx.x] = 0; // Determine where to read our input selector = (PASS == 0) ? 0 : d_selectors[PASS & 0x1]; if (PreprocessFunctor::MustApply() || PostprocessFunctor::MustApply()) { non_trivial_digit_pass = true; } else { // Determine whether or not we have work to do and setup the next round // accordingly. We can do this by looking at the first-block's // histograms and counting the number of digits with counts that are // non-zero and not-the-problem-size. int first_block_carry = d_spine[FastMul(gridDim.x, threadIdx.x)]; int predicate = ((first_block_carry > 0) && (first_block_carry < work_decomposition.num_elements)); non_trivial_digit_pass = (TallyWarpVote(RADIX_DIGITS, predicate, reinterpret_cast<int *>(scan_lanes)) > 0); } // Let the next round know which set of buffers to use if (blockIdx.x == 0) { d_selectors[(PASS + 1) & 0x1] = selector ^ non_trivial_digit_pass; } } // initialize raking segment row = threadIdx.x >> LOG_SEGS_PER_ROW; col = (threadIdx.x & (SEGS_PER_ROW - 1)) << LOG_PARTIALS_PER_SEG; raking_partial = reinterpret_cast<int *>(scan_lanes) + (row * PADDED_PARTIALS_PER_ROW) + col; } // Sync to acquire non_trivial_digit_pass and selector __syncthreads(); // Short-circuit this entire cycle if (!non_trivial_digit_pass) return; if (!selector) { // d_keys0 -> d_keys1 ScanScatterDigitPass<K, V, NONE, BIT, RADIX_BITS, RADIX_DIGITS, SCAN_LANES_PER_LOAD, LOADS_PER_CYCLE, CYCLES_PER_TILE, SCAN_LANES_PER_CYCLE, RAKING_THREADS, LOG_RAKING_THREADS_PER_LANE, RAKING_THREADS_PER_LANE, PARTIALS_PER_SEG, PARTIALS_PER_ROW, ROWS_PER_LANE, TILE_ELEMENTS, PreprocessFunctor, PostprocessFunctor>( d_spine, d_keys0, d_values0, d_keys1, d_values1, (int *) scan_lanes, warpscan, digit_carry, digit_scan, digit_counts, base_partial, raking_partial, block_offset, out_of_bounds, extra_elements); } else { // d_keys1 -> d_keys0 ScanScatterDigitPass<K, V, NONE, BIT, RADIX_BITS, RADIX_DIGITS, SCAN_LANES_PER_LOAD, LOADS_PER_CYCLE, CYCLES_PER_TILE, SCAN_LANES_PER_CYCLE, RAKING_THREADS, LOG_RAKING_THREADS_PER_LANE, RAKING_THREADS_PER_LANE, PARTIALS_PER_SEG, PARTIALS_PER_ROW, ROWS_PER_LANE, TILE_ELEMENTS, PreprocessFunctor, PostprocessFunctor>( d_spine, d_keys1, d_values1, d_keys0, d_values0, (int *) scan_lanes, warpscan, digit_carry, digit_scan, digit_counts, base_partial, raking_partial, block_offset, out_of_bounds, extra_elements); } } } // namespace b40c
the_stack
namespace fast_rnnt { // forward of mutual_information. See """... """ comment of // `mutual_information_recursion` in // in k2/python/k2/mutual_information.py for documentation of the // behavior of this function. // px: of shape [B, S, T+1] if !modified, else [B, S, T] <-- work out // `modified` from this. // py: of shape [B, S+1, T] // boundary: of shape [B, 4], containing (s_begin, t_begin, s_end, t_end) // defaulting to (0, 0, S, T). // p: of shape (S+1, T+1) // Computes the recursion: // if !modified: // p[b,s,t] = log_add(p[b,s-1,t] + px[b,s-1,t], // p[b,s,t-1] + py[b,s,t-1]) // if modified: // p[b,s,t] = log_add(p[b,s-1,t-1] + px[b,s-1,t-1], // p[b,s,t-1] + py[b,s,t-1]) // .. treating out-of-range elements as -infinity and with special cases: // p[b, s_begin, t_begin] = 0.0 // // and this function returns a tensor of shape (B,) consisting of elements // p[b, s_end, t_end] torch::Tensor MutualInformationCpu(torch::Tensor px, torch::Tensor py, torch::optional<torch::Tensor> opt_boundary, torch::Tensor p) { TORCH_CHECK(px.dim() == 3, "px must be 3-dimensional"); TORCH_CHECK(py.dim() == 3, "py must be 3-dimensional."); TORCH_CHECK(p.dim() == 3, "p must be 3-dimensional."); TORCH_CHECK(px.device().is_cpu() && py.device().is_cpu() && p.device().is_cpu(), "inputs must be CPU tensors"); bool modified = (px.size(2) == py.size(2)); auto scalar_t = px.scalar_type(); auto opts = torch::TensorOptions().dtype(scalar_t).device(px.device()); const int B = px.size(0), S = px.size(1), T = py.size(2); TORCH_CHECK(px.size(2) == (modified ? T : T + 1)); TORCH_CHECK(py.size(0) == B && py.size(1) == S + 1 && py.size(2) == T); TORCH_CHECK(p.size(0) == B && p.size(1) == S + 1 && p.size(2) == T + 1); auto boundary = opt_boundary.value_or( torch::tensor({0, 0, S, T}, torch::dtype(torch::kInt64).device(torch::kCPU)) .reshape({1, 4}) .expand({B, 4})); TORCH_CHECK(boundary.dim() == 2, "boundary must be 2-dimensional."); TORCH_CHECK(boundary.size(0) == B && boundary.size(1) == 4); TORCH_CHECK(boundary.device().is_cpu() && boundary.dtype() == torch::kInt64); torch::Tensor ans = torch::empty({B}, opts); AT_DISPATCH_FLOATING_TYPES( px.scalar_type(), "mutual_information_cpu_loop", ([&] { auto px_a = px.accessor<scalar_t, 3>(), py_a = py.accessor<scalar_t, 3>(), p_a = p.accessor<scalar_t, 3>(); auto boundary_a = boundary.accessor<int64_t, 2>(); auto ans_a = ans.accessor<scalar_t, 1>(); int t_offset = (modified ? -1 : 0); for (int b = 0; b < B; b++) { int s_begin = boundary_a[b][0]; int t_begin = boundary_a[b][1]; int s_end = boundary_a[b][2]; int t_end = boundary_a[b][3]; p_a[b][s_begin][t_begin] = 0.0; if (modified) { for (int s = s_begin + 1; s <= s_end; ++s) p_a[b][s][t_begin] = -std::numeric_limits<scalar_t>::infinity(); } else { // note: t_offset = 0 so don't need t_begin + t_offset below. for (int s = s_begin + 1; s <= s_end; ++s) p_a[b][s][t_begin] = p_a[b][s - 1][t_begin] + px_a[b][s - 1][t_begin]; } for (int t = t_begin + 1; t <= t_end; ++t) p_a[b][s_begin][t] = p_a[b][s_begin][t - 1] + py_a[b][s_begin][t - 1]; for (int s = s_begin + 1; s <= s_end; ++s) { scalar_t p_s_t1 = p_a[b][s][t_begin]; for (int t = t_begin + 1; t <= t_end; ++t) { // The following statement is a small optimization of: // p_a[b][s][t] = LogAdd( // p_a[b][s - 1][t + t_offset] + px_a[b][s -1][t + t_offset], // p_a[b][s][t - 1] + py_a[b][s][t - 1]); // .. which obtains p_a[b][s][t - 1] from a register. p_a[b][s][t] = p_s_t1 = LogAdd(p_a[b][s - 1][t + t_offset] + px_a[b][s - 1][t + t_offset], p_s_t1 + py_a[b][s][t - 1]); } } ans_a[b] = p_a[b][s_end][t_end]; } })); return ans; } // backward of mutual_information. Returns (px_grad, py_grad). // p corresponds to what we computed in the forward pass. std::vector<torch::Tensor> MutualInformationBackwardCpu(torch::Tensor px, torch::Tensor py, torch::optional<torch::Tensor> opt_boundary, torch::Tensor p, torch::Tensor ans_grad) { TORCH_CHECK(px.dim() == 3, "px must be 3-dimensional"); TORCH_CHECK(py.dim() == 3, "py must be 3-dimensional."); TORCH_CHECK(p.dim() == 3, "p must be 3-dimensional."); TORCH_CHECK(ans_grad.dim() == 1, "ans_grad must be 1-dimensional."); bool modified = (px.size(2) == py.size(2)); TORCH_CHECK(px.device().is_cpu() && py.device().is_cpu() && p.device().is_cpu() && ans_grad.device().is_cpu(), "inputs must be CPU tensors"); auto scalar_t = px.scalar_type(); auto opts = torch::TensorOptions().dtype(scalar_t).device(px.device()); const int B = px.size(0), S = px.size(1), T = py.size(2); TORCH_CHECK(px.size(2) == (modified ? T : T + 1)); TORCH_CHECK(py.size(0) == B && py.size(1) == S + 1); TORCH_CHECK(p.size(0) == B && p.size(1) == S + 1 && p.size(2) == T + 1); auto boundary = opt_boundary.value_or( torch::tensor({0, 0, S, T}, torch::dtype(torch::kInt64).device(torch::kCPU)) .reshape({1, 4}) .expand({B, 4})); TORCH_CHECK(boundary.dim() == 2, "boundary must be 2-dimensional."); TORCH_CHECK(boundary.size(0) == B && boundary.size(1) == 4); TORCH_CHECK(boundary.device().is_cpu() && boundary.dtype() == torch::kInt64); bool has_boundary = opt_boundary.has_value(); int T1 = T + (modified ? 0 : 1); torch::Tensor p_grad = torch::zeros({B, S + 1, T + 1}, opts), px_grad = (has_boundary ? torch::zeros({B, S, T1}, opts) : torch::empty({B, S, T1}, opts)), py_grad = (has_boundary ? torch::zeros({B, S + 1, T}, opts) : torch::empty({B, S + 1, T}, opts)); AT_DISPATCH_FLOATING_TYPES( px.scalar_type(), "mutual_information_cpu_backward_loop", ([&] { auto px_a = px.accessor<scalar_t, 3>(), p_a = p.accessor<scalar_t, 3>(), p_grad_a = p_grad.accessor<scalar_t, 3>(), px_grad_a = px_grad.accessor<scalar_t, 3>(), py_grad_a = py_grad.accessor<scalar_t, 3>(); auto ans_grad_a = ans_grad.accessor<scalar_t, 1>(); auto boundary_a = boundary.accessor<int64_t, 2>(); int t_offset = (modified ? -1 : 0); for (int b = 0; b < B; b++) { int s_begin = boundary_a[b][0]; int t_begin = boundary_a[b][1]; int s_end = boundary_a[b][2]; int t_end = boundary_a[b][3]; // Backprop for: ans_a[b] = p_a[b][s_end][t_end]; p_grad_a[b][s_end][t_end] = ans_grad_a[b]; for (int s = s_end; s > s_begin; --s) { for (int t = t_end; t > t_begin; --t) { // The s,t indexes correspond to // The statement we are backpropagating here is: // p_a[b][s][t] = LogAdd( // p_a[b][s - 1][t + t_offset] + px_a[b][s - 1][t + t_offset], // p_a[b][s][t - 1] + py_a[b][s][t - 1]); // .. which obtains p_a[b][s][t - 1] from a register. scalar_t term1 = p_a[b][s - 1][t + t_offset] + px_a[b][s - 1][t + t_offset], // term2 = p_a[b][s][t - 1] + py_a[b][s][t - 1], <-- not // actually needed.. total = p_a[b][s][t]; if (total - total != 0) total = 0; scalar_t term1_deriv = exp(term1 - total), term2_deriv = 1.0 - term1_deriv, grad = p_grad_a[b][s][t]; scalar_t term1_grad, term2_grad; if (term1_deriv - term1_deriv == 0.0) { term1_grad = term1_deriv * grad; term2_grad = term2_deriv * grad; } else { // could happen if total == -inf term1_grad = term2_grad = 0.0; } px_grad_a[b][s - 1][t + t_offset] = term1_grad; p_grad_a[b][s - 1][t + t_offset] = term1_grad; py_grad_a[b][s][t - 1] = term2_grad; p_grad_a[b][s][t - 1] += term2_grad; } } for (int t = t_end; t > t_begin; --t) { // Backprop for: // p_a[b][s_begin][t] = // p_a[b][s_begin][t - 1] + py_a[b][s_begin][t - 1]; scalar_t this_p_grad = p_grad_a[b][s_begin][t]; p_grad_a[b][s_begin][t - 1] += this_p_grad; py_grad_a[b][s_begin][t - 1] = this_p_grad; } if (!modified) { for (int s = s_end; s > s_begin; --s) { // Backprop for: // p_a[b][s][t_begin] = // p_a[b][s - 1][t_begin] + px_a[b][s - 1][t_begin]; scalar_t this_p_grad = p_grad_a[b][s][t_begin]; p_grad_a[b][s - 1][t_begin] += this_p_grad; px_grad_a[b][s - 1][t_begin] = this_p_grad; } } // else these were all -infinity's and there is nothing to // backprop. // There is no backprop for: // p_a[b][s_begin][t_begin] = 0.0; // .. but we can use this for a check, that the grad at the beginning // of the sequence is equal to the grad at the end of the sequence. if (ans_grad_a[b] != 0.0) { float grad_ratio = p_grad_a[b][s_begin][t_begin] / ans_grad_a[b]; if (fabs(grad_ratio - 1.0) > 0.01) { std::cout << "Warning: mutual_information backprop: expected these " << "numbers to be the same:" << static_cast<float>(p_grad_a[b][s_begin][t_begin]) << " vs " << static_cast<float>(ans_grad_a[b]); } } } })); return std::vector<torch::Tensor>({px_grad, py_grad}); } } // namespace fast_rnnt
the_stack
#include <nbla/cuda/function/depthwise_convolution.hpp> #include <nbla/cuda/math.hpp> #include <nbla/cuda/utils/block_reduce.cuh> #include <nbla/singleton_manager.hpp> namespace nbla { namespace depthwise_convolution_cuda { template <typename T, int K> __global__ void forward_kernel_1d(const T *input_data, T *output_data, const T *weight_data, const T *bias_data, const int output_data_size, const int2 sample, const int2 outmap, const int kernel, const int stride, const int padding, const int dilation, const int multiplier) { // sample/outmap (x, y) == (length, channels) // outmap.y == sample.y * multiplier const auto &sample_channels = sample.y; const auto &outmap_channels = outmap.y; const auto &sample_size = sample.x; const auto &outmap_size = outmap.x; const int KERNEL = (K != 0) ? K : kernel; NBLA_CUDA_KERNEL_LOOP(output_offset, output_data_size) { const int s = output_offset / (outmap_channels * outmap_size); const int outmap_x = output_offset % outmap_size; const int outmap_chan = (output_offset / outmap_size) % outmap_channels; const int sample_chan = outmap_chan / multiplier; const int sample_base = (s * sample_channels + sample_chan) * sample_size; int weight_offset = outmap_chan * kernel; T value = (bias_data != nullptr) ? bias_data[outmap_chan] : (T)0; #pragma unroll for (int k = 0; k < KERNEL; ++k) { const int sample_x = outmap_x * stride + k * dilation - padding; if ((sample_x >= 0) && (sample_x < sample_size)) { const int input_offset = sample_base + sample_x; value += weight_data[weight_offset] * input_data[input_offset]; } ++weight_offset; } output_data[output_offset] = value; } } template <typename T, int K> __global__ void forward_kernel_2d(const T *input_data, T *output_data, const T *weight_data, const T *bias_data, const int output_data_size, const int3 sample, const int3 outmap, const int2 kernel, const int2 stride, const int2 padding, const int2 dilation, const int multiplier) { // sample/outmap (x, y, z) == (width, height, channels) // outmap.z == sample.z * multiplier // sample/outmap/kernel size == width * height const auto &sample_channels = sample.z; const auto &outmap_channels = outmap.z; const int sample_size = sample.x * sample.y; const int outmap_size = outmap.x * outmap.y; const int KERNEL_X = (K != 0) ? K : kernel.x; const int KERNEL_Y = (K != 0) ? K : kernel.y; const int kernel_size = KERNEL_X * KERNEL_Y; NBLA_CUDA_KERNEL_LOOP(output_offset, output_data_size) { const int s = output_offset / (outmap_channels * outmap_size); const int outmap_y = (output_offset / outmap.x) % outmap.y; const int outmap_x = output_offset % outmap.x; const int outmap_chan = (output_offset / outmap_size) % outmap_channels; const int sample_chan = outmap_chan / multiplier; const int sample_base = (s * sample_channels + sample_chan) * sample_size; T value = (bias_data != nullptr) ? bias_data[outmap_chan] : (T)0; int weight_offset = outmap_chan * kernel_size; #pragma unroll for (int k_y = 0; k_y < KERNEL_Y; ++k_y) { #pragma unroll for (int k_x = 0; k_x < KERNEL_X; ++k_x) { const int sample_y = outmap_y * stride.y + k_y * dilation.y - padding.y; const int sample_x = outmap_x * stride.x + k_x * dilation.x - padding.x; if ((sample_y >= 0) && (sample_y < sample.y) && // (sample_x >= 0) && (sample_x < sample.x)) { int input_offset = sample_base + sample_y * sample.x + sample_x; value += weight_data[weight_offset] * input_data[input_offset]; } ++weight_offset; } } output_data[output_offset] = value; } } template <typename T, int K> __global__ void backprop_input_1d(T *input_grad, const T *output_grad, const T *weight_data, const int input_data_size, const int2 sample, const int2 outmap, const int kernel, const int stride, const int padding, const int dilation, const int multiplier) { // sample/outmap (x, y) == (length, channels) // outmap.y == sample.y * multiplier const auto &sample_channels = sample.y; const auto &outmap_channels = outmap.y; const auto &sample_size = sample.x; const auto &outmap_size = outmap.x; const int kernel_size = (K != 0) ? K : kernel; NBLA_CUDA_KERNEL_LOOP(input_offset, input_data_size) { const int s = input_offset / (sample_channels * sample_size); const int sample_x = input_offset % sample_size; const int sample_chan = (input_offset / sample_size) % sample_channels; const int outmap_chan = sample_chan * multiplier; const int outmap_base = (s * outmap_channels + outmap_chan) * outmap_size; const int weight_base = outmap_chan * kernel_size; T value = 0; #pragma unroll for (int kernel_x = 0; kernel_x < kernel_size; ++kernel_x) { int outmap_x = sample_x + padding - kernel_x * dilation; const int outmap_x_div_stride = outmap_x / stride; if (outmap_x - outmap_x_div_stride * stride == 0) { outmap_x = outmap_x_div_stride; if ((outmap_x >= 0) && (outmap_x < outmap.x)) { int output_offset = outmap_base + outmap_x; int weight_offset = weight_base + kernel_x; for (int m = 0; m < multiplier; ++m) { value += weight_data[weight_offset] * output_grad[output_offset]; output_offset += outmap_size; weight_offset += kernel_size; } } } } input_grad[input_offset] += value; } } template <typename T, int K> __global__ void backprop_input_2d(T *input_grad, const T *output_grad, const T *weight_data, const int input_data_size, const int3 sample, const int3 outmap, const int2 kernel, const int2 stride, const int2 padding, const int2 dilation, const int multiplier) { // sample/outmap (x, y, z) == (width, height, channels) // outmap.z == sample.z * multiplier // sample/outmap/kernel size == width * height const auto &sample_channels = sample.z; const auto &outmap_channels = outmap.z; const auto sample_size = sample.x * sample.y; const auto outmap_size = outmap.x * outmap.y; const int KERNEL_X = (K != 0) ? K : kernel.x; const int KERNEL_Y = (K != 0) ? K : kernel.y; const int kernel_size = KERNEL_X * KERNEL_Y; NBLA_CUDA_KERNEL_LOOP(input_offset, input_data_size) { const int s = input_offset / (sample_channels * sample_size); const int sample_y = (input_offset / sample.x) % sample.y; const int sample_x = input_offset % sample.x; const int sample_chan = (input_offset / sample_size) % sample_channels; const int outmap_chan = sample_chan * multiplier; const int outmap_base = (s * outmap_channels + outmap_chan) * outmap_size; const int weight_base = outmap_chan * kernel_size; int weight_incr = 0; T value = 0; #pragma unroll for (int k_y = 0; k_y < KERNEL_Y; ++k_y) { #pragma unroll for (int k_x = 0; k_x < KERNEL_X; ++k_x) { int outmap_y = sample_y + padding.y - k_y * dilation.y; int outmap_x = sample_x + padding.x - k_x * dilation.x; const int outmap_y_div_stride = outmap_y / stride.y; const int outmap_x_div_stride = outmap_x / stride.x; if ((outmap_y - outmap_y_div_stride * stride.y == 0) && (outmap_x - outmap_x_div_stride * stride.x == 0)) { outmap_y = outmap_y_div_stride; outmap_x = outmap_x_div_stride; if ((outmap_y >= 0) && (outmap_y < outmap.y) && // (outmap_x >= 0) && (outmap_x < outmap.x)) { int output_offset = outmap_base + outmap_y * outmap.x + outmap_x; int weight_offset = weight_base + weight_incr; for (int m = 0; m < multiplier; ++m) { value += weight_data[weight_offset] * output_grad[output_offset]; output_offset += outmap_size; weight_offset += kernel_size; } } } ++weight_incr; } } input_grad[input_offset] += value; } } template <typename T> __global__ void backprop_weights_1d(const T *output_grad, const T *input_data, T *weight_grad, T *bias_grad, const int batch_size, const int2 sample, const int2 outmap, const int kernel, const int stride, const int padding, const int dilation, const int multiplier) { const auto &sample_channels = sample.y; const auto &outmap_channels = outmap.y; const auto &sample_size = sample.x; const auto &outmap_size = outmap.x; // gridDim.x == blocks == outmap_channels * kernel_size == total weights // blockDim.x == threads == min(batch_size * warpSize, 256) // each block computes one weight value const int k_x = blockIdx.x % kernel; const int chan = blockIdx.x / kernel; const int samp = threadIdx.x / warpSize; const int lane = threadIdx.x % warpSize; const int warps = blockDim.x / warpSize; const int sample_stride = sample_channels * sample_size; const int outmap_stride = outmap_channels * outmap_size; const int sample_offset = (chan / multiplier) * sample_size; const int outmap_offset = chan * outmap_size; const int sample_skip_x = k_x * dilation; T weight_grad_value = 0; T bias_grad_value = 0; // Each thread block (of outmap-channels * kernel-size blocks) // computes a weight gradient. It also computes a bias gradient // even if that is done kernel-size times more often than // needed (but we won't gain with a conditional). for (int s = samp; s < batch_size; s += warps) { const int sample_base = s * sample_stride + sample_offset; const int outmap_base = s * outmap_stride + outmap_offset; for (int idx = lane; idx < outmap_size; idx += warpSize) { const int outmap_x = idx; const int sample_x = (outmap_x * stride) + sample_skip_x - padding; const T output_grad_value = output_grad[outmap_base + idx]; if ((sample_x >= 0) && (sample_x < sample.x)) { int input_offset = sample_base + sample_x; weight_grad_value += input_data[input_offset] * output_grad_value; } bias_grad_value += output_grad_value; } } __syncthreads(); // Accumulate thread local gradients. weight_grad_value = blockReduceSum(weight_grad_value); bias_grad_value = blockReduceSum(bias_grad_value); // The first thread has the accumulated gradients. The bias // gradient is needed only once per output channel. if (threadIdx.x == 0) { const int weight_offset = k_x + kernel * chan; weight_grad[weight_offset] += weight_grad_value; if (bias_grad && (blockIdx.x % kernel == 0)) { bias_grad[chan] += bias_grad_value; } } } template <typename T> __global__ void backprop_weights_2d(const T *output_grad, const T *input_data, T *weight_grad, T *bias_grad, const int batch_size, const int3 sample, const int3 outmap, const int2 kernel, const int2 stride, const int2 padding, const int2 dilation, const int multiplier) { const auto &sample_channels = sample.z; const auto &outmap_channels = outmap.z; const auto sample_size = sample.x * sample.y; const auto outmap_size = outmap.x * outmap.y; const auto kernel_size = kernel.x * kernel.y; // gridDim.x == blocks == outmap_channels * kernel_size == total weights // blockDim.x == threads == min(batch_size * warpSize, 256) // each block computes one weight value const int k_x = blockIdx.x % kernel.x; const int k_y = (blockIdx.x / kernel.x) % kernel.y; const int chan = blockIdx.x / kernel_size; const int samp = threadIdx.x / warpSize; const int lane = threadIdx.x % warpSize; const int warps = blockDim.x / warpSize; const int sample_stride = sample_channels * sample_size; const int outmap_stride = outmap_channels * outmap_size; const int sample_offset = (chan / multiplier) * sample_size; const int outmap_offset = chan * outmap_size; const int sample_skip_x = k_x * dilation.x; const int sample_skip_y = k_y * dilation.y; T weight_grad_value = 0; T bias_grad_value = 0; // Each thread block (of outmap-channels * kernel-size blocks) // computes a weight gradient. It also computes a bias gradient // even if that is done kernel-size times more often than // needed (but we won't gain with a conditional). for (int s = samp; s < batch_size; s += warps) { const int sample_base = s * sample_stride + sample_offset; const int outmap_base = s * outmap_stride + outmap_offset; for (int idx = lane; idx < outmap_size; idx += warpSize) { const int outmap_x = idx % outmap.x; const int outmap_y = idx / outmap.x; const int sample_x = (outmap_x * stride.x) + sample_skip_x - padding.x; const int sample_y = (outmap_y * stride.y) + sample_skip_y - padding.y; const T output_grad_value = output_grad[outmap_base + idx]; if ((sample_x >= 0) && (sample_x < sample.x) && // (sample_y >= 0) && (sample_y < sample.y)) { int input_offset = sample_base + (sample_y * sample.x) + sample_x; weight_grad_value += input_data[input_offset] * output_grad_value; } bias_grad_value += output_grad_value; } } __syncthreads(); // Accumulate thread local gradients. weight_grad_value = blockReduceSum(weight_grad_value); bias_grad_value = blockReduceSum(bias_grad_value); // The first thread has the accumulated gradients. The bias // gradient is needed only once per output channel. if (threadIdx.x == 0) { const int weight_offset = chan * kernel_size + k_y * kernel.x + k_x; weight_grad[weight_offset] += weight_grad_value; if (bias_grad && (blockIdx.x % kernel_size == 0)) { bias_grad[chan] += bias_grad_value; } } } } // namespace depthwise_convolution_cuda using namespace depthwise_convolution_cuda; template <typename T> void DepthwiseConvolutionCuda<T>::setup_impl(const Variables &inputs, const Variables &outputs) { cuda_set_device(std::stoi(this->ctx_.device_id)); DepthwiseConvolution<T>::setup_impl(inputs, outputs); input_data_size_ = inputs[0]->size(); output_data_size_ = outputs[0]->size(); NBLA_CHECK(inputs[1]->size() <= 65536, error_code::unclassified, "GPU implementation limit reached: output-channels x filter-size " "can not be more than 65536."); // see implementation note cudaFuncAttributes attr1, attr2, attr3; if (this->kernel_shape_.size() == 1) { sample_1d_ = make_int2(this->sample_shape_[0], this->sample_channels_); outmap_1d_ = make_int2(this->outmap_shape_[0], this->outmap_channels_); kernel_1d_ = this->kernel_shape_[0]; stride_1d_ = this->stride_[0]; padding_1d_ = this->padding_[0]; dilation_1d_ = this->dilation_[0]; if (kernel_1d_ == 3) { NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr1, forward_kernel_1d<Tc, 3>)); NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr2, backprop_input_1d<Tc, 3>)); } else if (kernel_1d_ == 5) { NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr1, forward_kernel_1d<Tc, 5>)); NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr2, backprop_input_1d<Tc, 5>)); } else { NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr1, forward_kernel_1d<Tc, 0>)); NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr2, backprop_input_1d<Tc, 0>)); } NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr3, backprop_weights_1d<Tc>)); } else { sample_2d_ = make_int3(this->sample_shape_[1], this->sample_shape_[0], this->sample_channels_); outmap_2d_ = make_int3(this->outmap_shape_[1], this->outmap_shape_[0], this->outmap_channels_); kernel_2d_ = make_int2(this->kernel_shape_[1], this->kernel_shape_[0]); stride_2d_ = make_int2(this->stride_[1], this->stride_[0]); padding_2d_ = make_int2(this->padding_[1], this->padding_[0]); dilation_2d_ = make_int2(this->dilation_[1], this->dilation_[0]); if ((kernel_2d_.x == 3) && (kernel_2d_.y == 3)) { NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr1, forward_kernel_2d<Tc, 3>)); NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr2, backprop_input_2d<Tc, 3>)); } else if ((kernel_2d_.x == 5) && (kernel_2d_.y == 5)) { NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr1, forward_kernel_2d<Tc, 5>)); NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr2, backprop_input_2d<Tc, 5>)); } else { NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr1, forward_kernel_2d<Tc, 0>)); NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr2, backprop_input_2d<Tc, 0>)); } NBLA_CUDA_CHECK(cudaFuncGetAttributes(&attr3, backprop_weights_2d<Tc>)); } forward_kernel_max_threads_per_block_ = attr1.maxThreadsPerBlock; backprop_input_max_threads_per_block_ = attr2.maxThreadsPerBlock; backprop_weights_max_threads_per_block_ = attr3.maxThreadsPerBlock; cudaDeviceProp prop; cudaGetDeviceProperties(&prop, std::stoi(this->ctx_.device_id)); warp_size_ = prop.warpSize; } template <typename T> void DepthwiseConvolutionCuda<T>::forward_impl(const Variables &inputs, const Variables &outputs) { cuda_set_device(std::stoi(this->ctx_.device_id)); Variable *const input = inputs[0]; Variable *const weight = inputs[1]; Variable *const bias = (inputs.size() == 3) ? inputs[2] : nullptr; Variable *const output = outputs[0]; const Tc *input_data = input->get_data_pointer<Tc>(this->ctx_); const Tc *weight_data = weight->get_data_pointer<Tc>(this->ctx_); const Tc *bias_data = (bias) ? bias->get_data_pointer<Tc>(this->ctx_) : nullptr; Tc *output_data = output->cast_data_and_get_pointer<Tc>(this->ctx_, true); const int threads = forward_kernel_max_threads_per_block_; const int blocks = (output_data_size_ + threads - 1) / threads; if (this->kernel_shape_.size() == 1) { if (kernel_1d_ == 3) { forward_kernel_1d<Tc, 3><<<blocks, threads>>>( input_data, output_data, weight_data, bias_data, output_data_size_, sample_1d_, outmap_1d_, kernel_1d_, stride_1d_, padding_1d_, dilation_1d_, this->multiplier_); } else if (kernel_1d_ == 5) { forward_kernel_1d<Tc, 5><<<blocks, threads>>>( input_data, output_data, weight_data, bias_data, output_data_size_, sample_1d_, outmap_1d_, kernel_1d_, stride_1d_, padding_1d_, dilation_1d_, this->multiplier_); } else { forward_kernel_1d<Tc, 0><<<blocks, threads>>>( input_data, output_data, weight_data, bias_data, output_data_size_, sample_1d_, outmap_1d_, kernel_1d_, stride_1d_, padding_1d_, dilation_1d_, this->multiplier_); } } else { if ((kernel_2d_.x == 3) && (kernel_2d_.y == 3)) { forward_kernel_2d<Tc, 3><<<blocks, threads>>>( input_data, output_data, weight_data, bias_data, output_data_size_, sample_2d_, outmap_2d_, kernel_2d_, stride_2d_, padding_2d_, dilation_2d_, this->multiplier_); } else if ((kernel_2d_.x == 5) && (kernel_2d_.y == 5)) { forward_kernel_2d<Tc, 5><<<blocks, threads>>>( input_data, output_data, weight_data, bias_data, output_data_size_, sample_2d_, outmap_2d_, kernel_2d_, stride_2d_, padding_2d_, dilation_2d_, this->multiplier_); } else { forward_kernel_2d<Tc, 0><<<blocks, threads>>>( input_data, output_data, weight_data, bias_data, output_data_size_, sample_2d_, outmap_2d_, kernel_2d_, stride_2d_, padding_2d_, dilation_2d_, this->multiplier_); } } } template <typename T> void DepthwiseConvolutionCuda<T>::backward_impl( const Variables &inputs, const Variables &outputs, const vector<bool> &propagate_down, const vector<bool> &accum) { if (!(propagate_down[0] || propagate_down[1] || (inputs.size() == 3 && propagate_down[2]))) { return; } cuda_set_device(std::stoi(this->ctx_.device_id)); Variable *const input = inputs[0]; Variable *const weight = inputs[1]; Variable *const bias = (inputs.size() == 3) ? inputs[2] : nullptr; Variable *const output = outputs[0]; const Tc *input_data = input->get_data_pointer<Tc>(this->ctx_); const Tc *weight_data = weight->get_data_pointer<Tc>(this->ctx_); const Tc *output_grad = output->get_grad_pointer<Tc>(this->ctx_); Tc *input_grad = nullptr; if (propagate_down[0]) { if (!accum[0]) input->grad()->zero(); // before cast! input_grad = input->cast_grad_and_get_pointer<Tc>(this->ctx_, false); } Tc *weight_grad = nullptr; if (propagate_down[1]) { if (!accum[1]) weight->grad()->zero(); // before cast! weight_grad = weight->cast_grad_and_get_pointer<Tc>(this->ctx_, false); } Tc *bias_grad = nullptr; if (inputs.size() == 3 && propagate_down[2]) { if (!accum[2]) bias->grad()->zero(); // before cast! bias_grad = bias->cast_grad_and_get_pointer<Tc>(this->ctx_, false); } if (input_grad) { // Compute the input gradient. Each thread of threads times // blocks computes one input gradient value. const int threads = backprop_input_max_threads_per_block_; const int blocks = (input_data_size_ + threads - 1) / threads; if (this->kernel_shape_.size() == 1) { if (kernel_1d_ == 3) { backprop_input_1d<Tc, 3><<<blocks, threads>>>( input_grad, output_grad, weight_data, input_data_size_, sample_1d_, outmap_1d_, kernel_1d_, stride_1d_, padding_1d_, dilation_1d_, this->multiplier_); } else if (kernel_1d_ == 5) { backprop_input_1d<Tc, 5><<<blocks, threads>>>( input_grad, output_grad, weight_data, input_data_size_, sample_1d_, outmap_1d_, kernel_1d_, stride_1d_, padding_1d_, dilation_1d_, this->multiplier_); } else { backprop_input_1d<Tc, 0><<<blocks, threads>>>( input_grad, output_grad, weight_data, input_data_size_, sample_1d_, outmap_1d_, kernel_1d_, stride_1d_, padding_1d_, dilation_1d_, this->multiplier_); } } else { if ((kernel_2d_.x == 3) && (kernel_2d_.y == 3)) { backprop_input_2d<Tc, 3><<<blocks, threads>>>( input_grad, output_grad, weight_data, input_data_size_, sample_2d_, outmap_2d_, kernel_2d_, stride_2d_, padding_2d_, dilation_2d_, this->multiplier_); } else if ((kernel_2d_.x == 5) && (kernel_2d_.y == 5)) { backprop_input_2d<Tc, 5><<<blocks, threads>>>( input_grad, output_grad, weight_data, input_data_size_, sample_2d_, outmap_2d_, kernel_2d_, stride_2d_, padding_2d_, dilation_2d_, this->multiplier_); } else { backprop_input_2d<Tc, 0><<<blocks, threads>>>( input_grad, output_grad, weight_data, input_data_size_, sample_2d_, outmap_2d_, kernel_2d_, stride_2d_, padding_2d_, dilation_2d_, this->multiplier_); } } NBLA_CUDA_KERNEL_CHECK(); } if (weight_grad) { // Compute the weight gradient and optionally the bias gradient // (if bias_grad is not a nullptr). The number of thread blocks is // the number of filter values multiplied by the number of output // channels, thus each block computes one filter value for a // specific output channel. For each of batch_size samples we // spawn warp_size (usually 32) threads for computation, but no // more than max_threads_per_block_ (usually 1024). More samples // than (max_threads_per_block_ / warp_size_) will stride loop // inside the cuda kernel. // // TODO: Note that the maximum number of thread blocks for kernel // invocation is 2^16 (in 2D case this limit could be reached for // example with a 128x128 filter and 1024 output channels). If // larger dimensions will ever be required, the blocks could be // provided as a dim3 structure using x and y members and the // kernel be modified to use blockIdx.x * blockIdx.y for offset // calculations. const int batch_size = this->batch_size_; const int max_threads_per_block = backprop_weights_max_threads_per_block_; const int threads = min(batch_size * warp_size_, max_threads_per_block); if (this->kernel_shape_.size() == 1) { const int kernel_size = kernel_1d_; const int output_channels = outmap_1d_.y; const int blocks = output_channels * kernel_size; backprop_weights_1d<Tc><<<blocks, threads>>>( output_grad, input_data, weight_grad, bias_grad, batch_size, sample_1d_, outmap_1d_, kernel_1d_, stride_1d_, padding_1d_, dilation_1d_, this->multiplier_); } else { const int kernel_size = kernel_2d_.x * kernel_2d_.y; const int output_channels = outmap_2d_.z; const int blocks = output_channels * kernel_size; backprop_weights_2d<Tc><<<blocks, threads>>>( output_grad, input_data, weight_grad, bias_grad, batch_size, sample_2d_, outmap_2d_, kernel_2d_, stride_2d_, padding_2d_, dilation_2d_, this->multiplier_); } NBLA_CUDA_KERNEL_CHECK(); } if (bias_grad && !weight_grad) { // Normally the bias gradient is computed along with the weight // gradient in the same cuda kernel. In the unlikely event that // only the bias gradient is requested, we fall back to this // slower method. if (this->kernel_shape_.size() == 1) { const int outmap_size = outmap_1d_.x; const int outmap_channels = outmap_1d_.y; const Tc *ones = static_cast<const Tc *>(SingletonManager::get<NNabla>()->ones( outmap_size, get_dtype<Tc>(), this->ctx_)); for (int samp = 0; samp < this->batch_size_; ++samp) { const int output_offset = samp * outmap_channels * outmap_size; cuda_gemv<Tc>(device_, bias_grad, &output_grad[output_offset], outmap_size, outmap_channels, true, ones, outmap_size, 1, 1); } } else { const int outmap_size = outmap_2d_.x * outmap_2d_.y; const int outmap_channels = outmap_2d_.z; const Tc *ones = static_cast<const Tc *>(SingletonManager::get<NNabla>()->ones( outmap_size, get_dtype<Tc>(), this->ctx_)); for (int samp = 0; samp < this->batch_size_; ++samp) { const int output_offset = samp * outmap_channels * outmap_size; cuda_gemv<Tc>(device_, bias_grad, &output_grad[output_offset], outmap_size, outmap_channels, true, ones, outmap_size, 1, 1); } } } } } // namespace nbla
the_stack
#include "gpu/image/sampling.hpp" #include "../deviceBuffer.hpp" #include "../deviceStream.hpp" #include "../surface.hpp" #include "../gpuKernelDef.h" #include "backend/common/vectorOps.hpp" #include "cuda/util.hpp" #include "image/kernels/sharedUtils.hpp" #include "backend/cuda/core1/kernels/samplingKernel.cu" #include <cuda_runtime.h> #include <cassert> #include "backend/common/image/sampling.gpu" namespace VideoStitch { namespace Image { // ------------------- Subsampling template <> Status subsample22(GPU::Buffer<unsigned char> dst, GPU::Buffer<const unsigned char> src, std::size_t srcWidth, std::size_t srcHeight, GPU::Stream gpuStream) { cudaStream_t stream = gpuStream.get(); std::size_t dstWidth = (srcWidth + 1) / 2; std::size_t dstHeight = (srcHeight + 1) / 2; // interior { dim3 dimBlock(16, 16, 1); dim3 dimGrid((unsigned)Cuda::ceilDiv(dstWidth, dimBlock.x), (unsigned)Cuda::ceilDiv(dstHeight, dimBlock.y), 1); subsample22RegularKernel<<<dimGrid, dimBlock, 0, stream>>>(dst.get().raw(), src.get().raw(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight); } // right boundary if (srcWidth & 1) { dim3 dimBlock(1, 256, 1); dim3 dimGrid(1, (unsigned)Cuda::ceilDiv(dstHeight, dimBlock.y), 1); subsample22RightBoundaryKernel<<<dimGrid, dimBlock, 0, stream>>>(dst.get().raw(), src.get().raw(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight); } // bottom boundary if (srcHeight & 1) { dim3 dimBlock(256, 1, 1); dim3 dimGrid((unsigned)Cuda::ceilDiv(dstWidth, dimBlock.x), 1, 1); subsample22BottomBoundaryKernel<<<dimGrid, dimBlock, 0, stream>>>(dst.get().raw(), src.get().raw(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight); } if ((srcWidth & 1) && (srcHeight & 1)) { // simple copy unsigned char* dstPtr = (unsigned char*)dst.get().raw(); unsigned char* srcPtr = (unsigned char*)src.get().raw(); return CUDA_ERROR(cudaMemcpyAsync(dstPtr + dstWidth * dstHeight - 1, srcPtr + srcHeight * srcWidth - 1, sizeof(unsigned char), cudaMemcpyDeviceToDevice, stream)); } return CUDA_STATUS; } template <> Status subsample22(GPU::Buffer<float2> dst, GPU::Buffer<const float2> src, std::size_t srcWidth, std::size_t srcHeight, GPU::Stream gpuStream) { cudaStream_t stream = gpuStream.get(); std::size_t dstWidth = (srcWidth + 1) / 2; std::size_t dstHeight = (srcHeight + 1) / 2; // interior { dim3 dimBlock(16, 16, 1); dim3 dimGrid((unsigned)Cuda::ceilDiv(dstWidth, dimBlock.x), (unsigned)Cuda::ceilDiv(dstHeight, dimBlock.y), 1); subsample22RegularKernelFloat2<<<dimGrid, dimBlock, 0, stream>>>(dst.get().raw(), src.get().raw(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight); } // right boundary if (srcWidth & 1) { dim3 dimBlock(1, 256, 1); dim3 dimGrid(1, (unsigned)Cuda::ceilDiv(dstHeight, dimBlock.y), 1); subsample22RightBoundaryKernelFloat2<<<dimGrid, dimBlock, 0, stream>>>(dst.get().raw(), src.get().raw(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight); } // bottom boundary if (srcHeight & 1) { dim3 dimBlock(256, 1, 1); dim3 dimGrid((unsigned)Cuda::ceilDiv(dstWidth, dimBlock.x), 1, 1); subsample22BottomBoundaryKernelFloat2<<<dimGrid, dimBlock, 0, stream>>>(dst.get().raw(), src.get().raw(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight); } if ((srcWidth & 1) && (srcHeight & 1)) { // simple copy float2* dstPtr = (float2*)dst.get().raw(); float2* srcPtr = (float2*)src.get().raw(); return CUDA_ERROR(cudaMemcpyAsync(dstPtr + dstWidth * dstHeight - 1, srcPtr + srcHeight * srcWidth - 1, sizeof(float2), cudaMemcpyDeviceToDevice, stream)); } return CUDA_STATUS; } template <> Status subsample22Mask(GPU::Buffer<float2> dst, GPU::Buffer<uint32_t> dstMask, GPU::Buffer<const float2> src, GPU::Buffer<const uint32_t> srcMask, std::size_t srcWidth, std::size_t srcHeight, unsigned blockSize, GPU::Stream gpuStream) { cudaStream_t stream = gpuStream.get(); std::size_t dstWidth = (srcWidth + 1) / 2; std::size_t dstHeight = (srcHeight + 1) / 2; // interior { dim3 dimBlock(blockSize, blockSize, 1); dim3 dimGrid((unsigned)Cuda::ceilDiv(dstWidth, dimBlock.x), (unsigned)Cuda::ceilDiv(dstHeight, dimBlock.y), 1); subsample22MaskRegularKernel<<<dimGrid, dimBlock, 0, stream>>>( dst.get().raw(), dstMask.get().raw(), src.get().raw(), srcMask.get().raw(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight); } // right boundary if (srcWidth & 1) { dim3 dimBlock(1, blockSize * blockSize, 1); dim3 dimGrid(1, (unsigned)Cuda::ceilDiv(dstHeight, dimBlock.y), 1); subsample22MaskRightBoundaryKernel<<<dimGrid, dimBlock, 0, stream>>>( dst.get().raw(), dstMask.get().raw(), src.get().raw(), srcMask.get().raw(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight); } // bottom boundary if (srcHeight & 1) { dim3 dimBlock(blockSize * blockSize, 1, 1); dim3 dimGrid((unsigned)Cuda::ceilDiv(dstWidth, dimBlock.x), 1, 1); subsample22MaskBottomBoundaryKernel<<<dimGrid, dimBlock, 0, stream>>>( dst.get().raw(), dstMask.get().raw(), src.get().raw(), srcMask.get().raw(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight); } if ((srcWidth & 1) && (srcHeight & 1)) { // simple copy float2* dstPtr = (float2*)dst.get().raw(); float2* srcPtr = (float2*)src.get().raw(); FAIL_RETURN(CUDA_ERROR(cudaMemcpyAsync(dstPtr + dstWidth * dstHeight - 1, srcPtr + srcHeight * srcWidth - 1, sizeof(float2), cudaMemcpyDeviceToDevice, stream))); uint32_t* dstMaskPtr = (uint32_t*)dstMask.get().raw(); uint32_t* srcMaskPtr = (uint32_t*)srcMask.get().raw(); FAIL_RETURN(CUDA_ERROR(cudaMemcpyAsync(dstMaskPtr + dstWidth * dstHeight - 1, srcMaskPtr + srcHeight * srcWidth - 1, sizeof(uint32_t), cudaMemcpyDeviceToDevice, stream))); } return CUDA_STATUS; } template <typename T> Status subsample22Nearest(GPU::Buffer<T> dst, GPU::Buffer<const T> src, std::size_t srcWidth, std::size_t srcHeight, unsigned blockSize, GPU::Stream gpuStream) { cudaStream_t stream = gpuStream.get(); std::size_t dstWidth = (srcWidth + 1) / 2; std::size_t dstHeight = (srcHeight + 1) / 2; // interior { dim3 dimBlock(blockSize, blockSize, 1); dim3 dimGrid((unsigned)Cuda::ceilDiv(dstWidth, dimBlock.x), (unsigned)Cuda::ceilDiv(dstHeight, dimBlock.y), 1); subsample22NearestRegularKernel<<<dimGrid, dimBlock, 0, stream>>>(dst.get().raw(), src.get().raw(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight); } // right boundary if (srcWidth & 1) { dim3 dimBlock(1, blockSize * blockSize, 1); dim3 dimGrid(1, (unsigned)Cuda::ceilDiv(dstHeight, dimBlock.y), 1); subsample22NearestRightBoundaryKernel<<<dimGrid, dimBlock, 0, stream>>>(dst.get().raw(), src.get().raw(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight); } if (srcHeight & 1) { dim3 dimBlock(blockSize * blockSize, 1, 1); dim3 dimGrid((unsigned)Cuda::ceilDiv(dstWidth, dimBlock.x), 1, 1); subsample22NearestBottomBoundaryKernel<<<dimGrid, dimBlock, 0, stream>>>(dst.get().raw(), src.get().raw(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth, (unsigned)dstHeight); } if ((srcWidth & 1) && (srcHeight & 1)) { // simple copy T* dstPtr = (T*)dst.get().raw(); T* srcPtr = (T*)src.get().raw(); return CUDA_ERROR(cudaMemcpyAsync(dstPtr + dstWidth * dstHeight - 1, srcPtr + srcHeight * srcWidth - 1, sizeof(T), cudaMemcpyDeviceToDevice, stream)); } return CUDA_STATUS; } // template // Status subsample22Nearest(GPU::Buffer<uint32_t> dst, GPU::Buffer<const uint32_t> src, std::size_t srcWidth, // std::size_t srcHeight, unsigned blockSize, GPU::Stream stream); template Status // subsample22Nearest(GPU::Buffer<unsigned char> dst, GPU::Buffer<const unsigned char> src, std::size_t srcWidth, // std::size_t srcHeight, unsigned blockSize, GPU::Stream stream); template Status subsample22Nearest(GPU::Buffer<float> // dst, GPU::Buffer<const float> src, std::size_t srcWidth, std::size_t srcHeight, unsigned blockSize, GPU::Stream // stream); Status subsample22RGBA(GPU::Buffer<uint32_t> dst, GPU::Buffer<const uint32_t> src, std::size_t srcWidth, std::size_t srcHeight, GPU::Stream gpuStream) { cudaStream_t stream = gpuStream.get(); std::size_t dstWidth = (srcWidth + 1) / 2; std::size_t dstHeight = (srcHeight + 1) / 2; // interior { dim3 dimBlock(16, 16, 1); dim3 dimGrid((unsigned)Cuda::ceilDiv(dstWidth, dimBlock.x), (unsigned)Cuda::ceilDiv(dstHeight, dimBlock.y), 1); subsample22RGBARegularKernel<<<dimGrid, dimBlock, 0, stream>>>(dst.get(), src.get(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth); } // right boundary if (srcWidth & 1) { dim3 dimBlock(1, 256, 1); dim3 dimGrid(1, (unsigned)Cuda::ceilDiv(dstHeight, dimBlock.y), 1); subsample22RGBARightBoundaryKernel<<<dimGrid, dimBlock, 0, stream>>>(dst.get(), src.get(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth); } if (srcHeight & 1) { dim3 dimBlock(256, 1, 1); dim3 dimGrid((unsigned)Cuda::ceilDiv(dstWidth, dimBlock.x), 1, 1); subsample22RGBABottomBoundaryKernel<<<dimGrid, dimBlock, 0, stream>>>(dst.get(), src.get(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth); } if ((srcWidth & 1) && (srcHeight & 1)) { // simple copy uint32_t* dstPtr = (uint32_t*)dst.get().raw(); uint32_t* srcPtr = (uint32_t*)src.get().raw(); return CUDA_ERROR(cudaMemcpyAsync(dstPtr + dstWidth * dstHeight - 1, srcPtr + srcHeight * srcWidth - 1, 4, cudaMemcpyDeviceToDevice, stream)); } return CUDA_STATUS; } // ------------------ Upsampling /** * Upsample @src by a factor of two on each dimension and put it in into @dst. * @dst has size (@dstWidth * @dstHeight), @dst has size ((@dstWidth + 1)/2 * (@dstHeight + 1)/2). * This is more complex than subsampling since we need to interpolate at the same time. * We use shared memory to share reads to global memory between threads. * In addition, we make sure that memory accesses are coalesced. * To avoid divergence in the regular case, there are two kernels: one that applies inside * the image, and one that applies to boundaries. * The alpha is taken to be solid if at least one sample is solid. */ /** // Bilinear interpolation. // +=======+=======+=======+ // | | | | // | A | B | C | // | | | | | | | // +=======+=======+= +=======+===+===+=======+ // | | | | | a | b | | // | D | E | | D +---+---+ F | // | | | | | c | d | | // +=======+=======+= => +=======+===+===+=======+ // | | | | | | | // | G | H | | G | H | I | // | | | | | | | // +=======+=======+= +=======+=======+=======+ // // The current thread loads source pixel E, then computes interpolated values for a, b, c, d: // a = 1 / 16 * A + 3 / 16 * [D + B] + 9 / 16 * E // b = 1 / 16 * C + 3 / 16 * [B + F] + 9 / 16 * E // c = 1 / 16 * G + 3 / 16 * [D + H] + 9 / 16 * E // d = 1 / 16 * I + 3 / 16 * [F + H] + 9 / 16 * E */ struct BilinearInterpolationRGB210 { typedef uint32_t Type; static inline __device__ uint32_t interpolate(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { // see above const int32_t alphaA = RGB210::a(a); const int32_t alphaB = RGB210::a(b); const int32_t alphaC = RGB210::a(c); const int32_t alphaD = RGB210::a(d); const int32_t divisor = 9 * alphaA + 3 * (alphaB + alphaC) + alphaD; return RGB210::pack( (alphaA * 9 * RGB210::r(a) + 3 * (alphaB * RGB210::r(b) + alphaC * RGB210::r(c)) + alphaD * RGB210::r(d)) / divisor, (alphaA * 9 * RGB210::g(a) + 3 * (alphaB * RGB210::g(b) + alphaC * RGB210::g(c)) + alphaD * RGB210::g(d)) / divisor, (alphaA * 9 * RGB210::b(a) + 3 * (alphaB * RGB210::b(b) + alphaC * RGB210::b(c)) + alphaD * RGB210::b(d)) / divisor, divisor > 0); } }; struct BilinearInterpolationRGBA { typedef uint32_t Type; static inline __device__ uint32_t interpolate(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { // see above const uint32_t alphaA = !!RGBA::a(a); const uint32_t alphaB = !!RGBA::a(b); const uint32_t alphaC = !!RGBA::a(c); const uint32_t alphaD = !!RGBA::a(d); const uint32_t divisor = 9 * alphaA + 3 * (alphaB + alphaC) + alphaD; if (divisor) { return RGBASolid::pack( (alphaA * 9 * RGBA::r(a) + 3 * (alphaB * RGBA::r(b) + alphaC * RGBA::r(c)) + alphaD * RGBA::r(d)) / divisor, (alphaA * 9 * RGBA::g(a) + 3 * (alphaB * RGBA::g(b) + alphaC * RGBA::g(c)) + alphaD * RGBA::g(d)) / divisor, (alphaA * 9 * RGBA::b(a) + 3 * (alphaB * RGBA::b(b) + alphaC * RGBA::b(c)) + alphaD * RGBA::b(d)) / divisor, 0xff); } else { return 0; } } }; template <typename T> struct BilinearInterpolation { typedef T Type; static inline __device__ T interpolate(T a, T b, T c, T d) { // see above return (T)(9.0f / 16.0f * a + 3.0f / 16.0f * (b + c) + 1.0f / 16.0f * d); } }; Status upsample22RGBA210(GPU::Buffer<uint32_t> dst, GPU::Buffer<const uint32_t> src, std::size_t dstWidth, std::size_t dstHeight, bool wrap, GPU::Stream stream) { const unsigned srcWidth = ((unsigned)dstWidth + 1) / 2; const unsigned srcHeight = ((unsigned)dstHeight + 1) / 2; const dim3 dimBlock(16, 16, 1); const dim3 dimGrid((unsigned)Cuda::ceilDiv(srcWidth, dimBlock.x), (unsigned)Cuda::ceilDiv(srcHeight, dimBlock.y), 1); if (wrap) { upsample22Kernel<HWrapBoundary<uint32_t>, BilinearInterpolationRGB210> <<<dimGrid, dimBlock, (16 + 2) * (16 + 2) * 4, stream.get()>>>(dst.get(), src.get(), (unsigned)dstWidth, (unsigned)dstHeight, srcWidth, srcHeight); } else { upsample22Kernel<ExtendBoundary<uint32_t>, BilinearInterpolationRGB210> <<<dimGrid, dimBlock, (16 + 2) * (16 + 2) * 4, stream.get()>>>(dst.get(), src.get(), (unsigned)dstWidth, (unsigned)dstHeight, srcWidth, srcHeight); } return CUDA_STATUS; } Status upsample22RGBA(GPU::Buffer<uint32_t> dst, GPU::Buffer<const uint32_t> src, std::size_t dstWidth, std::size_t dstHeight, bool wrap, GPU::Stream stream) { const unsigned srcWidth = ((unsigned)dstWidth + 1) / 2; const unsigned srcHeight = ((unsigned)dstHeight + 1) / 2; const dim3 dimBlock(16, 16, 1); const dim3 dimGrid((unsigned)Cuda::ceilDiv(srcWidth, dimBlock.x), (unsigned)Cuda::ceilDiv(srcHeight, dimBlock.y), 1); if (wrap) { upsample22Kernel<HWrapBoundary<uint32_t>, BilinearInterpolationRGBA> <<<dimGrid, dimBlock, (16 + 2) * (16 + 2) * 4, stream.get()>>>(dst.get(), src.get(), (unsigned)dstWidth, (unsigned)dstHeight, srcWidth, srcHeight); } else { upsample22Kernel<ExtendBoundary<uint32_t>, BilinearInterpolationRGBA> <<<dimGrid, dimBlock, (16 + 2) * (16 + 2) * 4, stream.get()>>>(dst.get(), src.get(), (unsigned)dstWidth, (unsigned)dstHeight, srcWidth, srcHeight); } return CUDA_STATUS; } template <typename T> Status upsample22(GPU::Buffer<T> dst, GPU::Buffer<const T> src, std::size_t dstWidth, std::size_t dstHeight, bool wrap, GPU::Stream stream) { const unsigned srcWidth = ((unsigned)dstWidth + 1) / 2; const unsigned srcHeight = ((unsigned)dstHeight + 1) / 2; const dim3 dimBlock(16, 16, 1); const dim3 dimGrid((unsigned)Cuda::ceilDiv(srcWidth, dimBlock.x), (unsigned)Cuda::ceilDiv(srcHeight, dimBlock.y), 1); if (wrap) { upsample22Kernel<HWrapBoundary<T>, BilinearInterpolation<T>><<<dimGrid, dimBlock, 0, stream.get()>>>( dst.get(), src.get(), (unsigned)dstWidth, (unsigned)dstHeight, srcWidth, srcHeight); } else { upsample22Kernel<ExtendBoundary<T>, BilinearInterpolation<T>><<<dimGrid, dimBlock, 0, stream.get()>>>( dst.get(), src.get(), (unsigned)dstWidth, (unsigned)dstHeight, srcWidth, srcHeight); } return CUDA_STATUS; } template Status upsample22(GPU::Buffer<uint32_t> dst, GPU::Buffer<const uint32_t> src, std::size_t dstWidth, std::size_t dstHeight, bool wrap, GPU::Stream stream); template Status upsample22(GPU::Buffer<unsigned char> dst, GPU::Buffer<const unsigned char> src, std::size_t dstWidth, std::size_t dstHeight, bool wrap, GPU::Stream stream); template Status upsample22(GPU::Buffer<float> dst, GPU::Buffer<const float> src, std::size_t dstWidth, std::size_t dstHeight, bool wrap, GPU::Stream stream); template Status upsample22(GPU::Buffer<float2> dst, GPU::Buffer<const float2> src, std::size_t dstWidth, std::size_t dstHeight, bool wrap, GPU::Stream stream); // ---------------- Masks sampling Status subsampleMask22(GPU::Buffer<unsigned char> dst, GPU::Buffer<const unsigned char> src, std::size_t srcWidth, std::size_t srcHeight, unsigned blockSize, GPU::Stream stream) { std::size_t dstWidth = (srcWidth + 1) / 2; std::size_t dstHeight = (srcHeight + 1) / 2; dim3 dimBlock(blockSize, blockSize, 1); dim3 dimGrid((unsigned)Cuda::ceilDiv(dstWidth, dimBlock.x), (unsigned)Cuda::ceilDiv(dstHeight, dimBlock.y), 1); subsampleMask22Kernel<<<dimGrid, dimBlock, 0, stream.get()>>>(dst.get(), src.get(), (unsigned)srcWidth, (unsigned)srcHeight, (unsigned)dstWidth); return CUDA_STATUS; } } // namespace Image } // namespace VideoStitch
the_stack
using namespace FW; __constant__ unsigned char c_constants[sizeof(Constants)]; texture<float4, 2> t_textureAtlas; //------------------------------------------------------------------------ // Lighting. //------------------------------------------------------------------------ __device__ Vec3f FW::evaluateLighting(Vec3f cameraPos, Vec3f cameraNormal, const Material& material, Vec3f diffuseColor) { Vec3f I = normalize(cameraPos); Vec3f N = normalize(cameraNormal); F32 dotIN = dot(I, N); Vec3f R = I - N * (dotIN * 2.0f); F32 diffuseCoef = fmaxf(-dotIN, 0.0f) * 0.75f + 0.25f; F32 specularCoef = powf(fmaxf(-dot(I, R), 0.0f), material.glossiness); return diffuseCoef * diffuseColor + specularCoef * material.specularColor; } //------------------------------------------------------------------------ // Vertex shaders. //------------------------------------------------------------------------ //extern "C" __global__ void FW::vertexShader_gouraud(const InputVertex* inPtr, ShadedVertex_gouraud* outPtr, int numVertices) //{ // // Pick a vertex. // // int vidx = threadIdx.x + blockDim.x * (threadIdx.y + blockDim.y * (blockIdx.x + gridDim.x * blockIdx.y)); // if (vidx >= numVertices) // return; // // const InputVertex& in = inPtr[vidx]; // ShadedVertex_gouraud& out = outPtr[vidx]; // // // Shade. // // Constants& constants = *(Constants*)&c_constants; // // out.clipPos = constants.posToClip * Vec4f(in.modelPos, 1.0f); // // Vec3f cameraPos = (constants.posToCamera * Vec4f(in.modelPos, 1.0f)).getXYZ(); // Vec3f cameraNormal = constants.normalToCamera * in.modelNormal; // Material& mat = *((Material*)materialbase); // Vec4f diffuseColor = mat.diffuseColor; // Vec3f color = evaluateLighting(cameraPos, cameraNormal, mat, diffuseColor.getXYZ()); // out.color = Vec4f(color, diffuseColor.w); //} extern "C" __global__ void FW::vertexShader_clipSpace(const ClipSpaceVertex* inPtr, ShadedVertex_clipSpace* outPtr, int numVertices) { // Pick a vertex. int vidx = threadIdx.x + blockDim.x * (threadIdx.y + blockDim.y * (blockIdx.x + gridDim.x * blockIdx.y)); if (vidx >= numVertices) return; const ClipSpaceVertex& in = inPtr[vidx]; ShadedVertex_clipSpace& out = outPtr[vidx]; // Shade. //Constants& constants = *(Constants*)&c_constants; out.clipPos = in.clipSpacePos; out.p = in.clipSpacePos; //Vec3f cameraPos = (constants.posToCamera * Vec4f(in.modelPos, 1.0f)).getXYZ(); //Vec3f cameraNormal = constants.normalToCamera * in.modelNormal; //Material& mat = *((Material*)materialbase); //Vec4f diffuseColor = mat.diffuseColor; //Vec3f color = evaluateLighting(cameraPos, cameraNormal, mat, diffuseColor.getXYZ()); //out.color = Vec4f(color, diffuseColor.w); //out.normal = in.clipSpacePos; //out.light = Vec4f(constants.normalToCamera * (constants.lightPos - in.modelPos), 1); } extern "C" __global__ void FW::vertexShader_eyecandy(const EyecandyVertex* inPtr, ShadedVertex_eyecandy* outPtr, int numVertices) { // Pick a vertex. int vidx = threadIdx.x + blockDim.x * (threadIdx.y + blockDim.y * (blockIdx.x + gridDim.x * blockIdx.y)); if (vidx >= numVertices) return; const EyecandyVertex& in = inPtr[vidx]; ShadedVertex_eyecandy& out = outPtr[vidx]; // Shade. //Constants& constants = *(Constants*)&c_constants; out.clipPos = in.pos; out.pos = in.pos; out.normal = in.normal; out.color = in.color; } extern "C" __global__ void FW::vertexShader_gouraud(const InputVertex* inPtr, ShadedVertex_gouraud* outPtr, int numVertices) { // Pick a vertex. int vidx = threadIdx.x + blockDim.x * (threadIdx.y + blockDim.y * (blockIdx.x + gridDim.x * blockIdx.y)); if (vidx >= numVertices) return; const InputVertex& in = inPtr[vidx]; ShadedVertex_gouraud& out = outPtr[vidx]; // Shade. Constants& constants = *(Constants*)&c_constants; out.clipPos = constants.posToClip * Vec4f(in.modelPos, 1.0f); //Vec3f cameraPos = (constants.posToCamera * Vec4f(in.modelPos, 1.0f)).getXYZ(); //Vec3f cameraNormal = constants.normalToCamera * in.modelNormal; //Material& mat = *((Material*)materialbase); //Vec4f diffuseColor = mat.diffuseColor; //Vec3f color = evaluateLighting(cameraPos, cameraNormal, mat, diffuseColor.getXYZ()); //out.color = Vec4f(color, diffuseColor.w); out.normal = Vec4f(constants.normalToCamera * in.modelNormal, 1); out.light = Vec4f(constants.normalToCamera * (constants.lightPos - in.modelPos), 1); } //------------------------------------------------------------------------ extern "C" __global__ void FW::vertexShader_texPhong(const InputVertex* inPtr, ShadedVertex_texPhong* outPtr, int numVertices) { // Pick a vertex. int vidx = threadIdx.x + blockDim.x * (threadIdx.y + blockDim.y * (blockIdx.x + gridDim.x * blockIdx.y)); if (vidx >= numVertices) return; const InputVertex& in = inPtr[vidx]; ShadedVertex_texPhong& out = outPtr[vidx]; // Shade. Constants& constants = *(Constants*)&c_constants; out.clipPos = constants.posToClip * Vec4f(in.modelPos, 1.0f); out.cameraPos = constants.posToCamera * Vec4f(in.modelPos, 1.0f); out.cameraNormal = Vec4f(constants.normalToCamera * in.modelNormal, 0.0f); out.texCoord = Vec4f(in.texCoord, 0.0f, 1.0f); } //------------------------------------------------------------------------ // Fragment shaders. //------------------------------------------------------------------------ typedef GouraudShader FragmentShader_gouraud; typedef GouraudShaderUnlit FragmentShader_gouraud_unlit; //------------------------------------------------------------------------ class FragmentShader_texPhong : public FragmentShaderBase { public: __device__ __inline__ Vec4f texture2D(const TextureSpec& spec, const Vec2f& tex, const Vec2f& texDX, const Vec2f& texDY) { // Choose LOD. F32 dxlen = sqr(texDX.x * spec.size.x) + sqr(texDX.y * spec.size.y); F32 dylen = sqr(texDY.x * spec.size.x) + sqr(texDY.y * spec.size.y); F32 lod = fminf(fmaxf(log2f(fmaxf(dxlen, dylen)) * 0.5f, 0.0f), (F32)(FW_ARRAY_SIZE(spec.mipLevels) - 2)); int levelIdx = (int)lod; Vec4f m0 = spec.mipLevels[levelIdx + 0]; Vec4f m1 = spec.mipLevels[levelIdx + 1]; // Perform two bilinear lookups and interpolate. F32 tx = tex.x - floorf(tex.x); F32 ty = tex.y - floorf(tex.y); float4 v0 = tex2D(t_textureAtlas, tx * m0.x + m0.z, ty * m0.y + m0.w); float4 v1 = tex2D(t_textureAtlas, tx * m1.x + m1.z, ty * m1.y + m1.w); return lerp(Vec4f(v0.x, v0.y, v0.z, v0.w), Vec4f(v1.x, v1.y, v1.z, v1.w), lod - (F32)levelIdx); } __device__ __inline__ void run(void) { // Interpolate attributes. Vec3f cameraPos = interpolateVarying(0, m_centroid).getXYZ(); Vec3f cameraNormal = interpolateVarying(1, m_centroid).getXYZ(); Vec2f tex, texDX, texDY; if ((RENDER_MODE_FLAGS & RenderModeFlag_EnableQuads) == 0) { // Sample at pixel centroid, use analytical derivatives. tex = interpolateVarying(2, m_centroid).getXY(); texDX = interpolateVarying(2, m_centroidDX).getXY(); texDY = interpolateVarying(2, m_centroidDY).getXY(); } else { // Sample at pixel center, use numerical derivatices. tex = interpolateVarying(2, m_center).getXY(); texDX = dFdx(tex); texDY = dFdy(tex); } // Fetch material and perform texture lookups. Constants& constants = *(Constants*)&c_constants; int materialIdx = ((const S32*)constants.triangleMaterialIdx)[m_triIdx]; const Material& material = ((const Material*)constants.materials)[materialIdx]; Vec4f diffuseColor = material.diffuseColor; if (material.diffuseTexture.size.x != 0.0f) diffuseColor = Vec4f(texture2D(material.diffuseTexture, tex, texDX, texDY).getXYZ(), diffuseColor.w); if (material.alphaTexture.size.x != 0.0f) diffuseColor.w = texture2D(material.alphaTexture, tex, texDX, texDY).y; // Alpha test. if (diffuseColor.w < 0.5f) { m_discard = true; return; } // Shading. Vec3f color = evaluateLighting(cameraPos, cameraNormal, material, diffuseColor.getXYZ()); m_color = toABGR(Vec4f(color, diffuseColor.w)); } }; class FragmentShader_clipSpace : public FragmentShaderBase { public: __device__ __inline__ void run(void) { //// Interpolate attributes. //if ((m_centroid.x + m_centroid.y > 0.95f && m_centroid.z < 0.05f) // || (m_centroid.x + m_centroid.z > 0.95f && m_centroid.y < 0.05f) // || (m_centroid.y + m_centroid.z > 0.95f && m_centroid.x < 0.05f)) //{ // Vec3f col(1, 1, 1); // m_color = toABGR(Vec4f(col, 1)); //} //else //{ // m_discard = true; // return; //} Vec4f p = interpolateVarying(0, m_centroid); float c = p.w * 0.01f; m_color = toABGR(Vec4f(c,c,c,1.0f)); } }; class FragmentShader_eyecandy : public FragmentShaderBase { public: __device__ __inline__ void run(void) { //// Interpolate attributes. Vec4f color_ = interpolateVarying(2, m_centroid); Vec3f color(color_.x, color_.y, color_.z); if (color.x == 0 && color.y == 0 && color.z == 0) { m_discard = true; return; } Vec4f normal_ = interpolateVarying(1, m_centroid); Vec3f normal = Vec3f(normal_.x, normal_.y, normal_.z); normal.normalize(); Vec4f res = Vec4f(color*(fabsf(normal.z) + 0.2f), 1.0f); //float v = min(min(__f[0], __f[1]), __f[2]); //if (v < 0.001f) //{ // res *= 1.6f; //} m_color = toABGR(res); } }; //------------------------------------------------------------------------ // Pixel pipes. //------------------------------------------------------------------------ CR_DEFINE_PIXEL_PIPE(PixelPipe_eyecandy, ShadedVertex_eyecandy, FragmentShader_eyecandy, BLEND_SHADER, SAMPLES_LOG2, RENDER_MODE_FLAGS) CR_DEFINE_PIXEL_PIPE(PixelPipe_clipSpace, ShadedVertex_clipSpace, FragmentShader_clipSpace, BLEND_SHADER, SAMPLES_LOG2, RENDER_MODE_FLAGS) CR_DEFINE_PIXEL_PIPE(PixelPipe_gouraud, ShadedVertex_gouraud, FragmentShader_gouraud, BLEND_SHADER, SAMPLES_LOG2, RENDER_MODE_FLAGS) CR_DEFINE_PIXEL_PIPE(PixelPipe_gouraud_unlit, ShadedVertex_gouraud, FragmentShader_gouraud_unlit, BLEND_SHADER, SAMPLES_LOG2, RENDER_MODE_FLAGS) CR_DEFINE_PIXEL_PIPE(PixelPipe_texPhong, ShadedVertex_texPhong, FragmentShader_texPhong, BLEND_SHADER, SAMPLES_LOG2, RENDER_MODE_FLAGS) //------------------------------------------------------------------------
the_stack
* \test Tests the performance of multiple inner products with a common vector. **/ // // *** System // #include <iostream> #include <iomanip> #include <iterator> // // *** ViennaCL // #include "viennacl/vector.hpp" #include "viennacl/vector_proxy.hpp" #include "viennacl/linalg/inner_prod.hpp" #include "viennacl/linalg/norm_1.hpp" #include "viennacl/linalg/norm_2.hpp" #include "viennacl/linalg/norm_inf.hpp" #include "viennacl/tools/random.hpp" // // ------------------------------------------------------------- // template<typename ScalarType> ScalarType diff(ScalarType const & s1, ScalarType const & s2) { viennacl::backend::finish(); if (s1 != s2) return (s1 - s2) / std::max(std::fabs(s1), std::fabs(s2)); return 0; } // // ------------------------------------------------------------- // template<typename ScalarType> ScalarType diff(ScalarType const & s1, viennacl::scalar<ScalarType> const & s2) { viennacl::backend::finish(); if (s1 != s2) return (s1 - s2) / std::max(std::fabs(s1), std::fabs(s2)); return 0; } // // ------------------------------------------------------------- // template<typename ScalarType> ScalarType diff(ScalarType const & s1, viennacl::entry_proxy<ScalarType> const & s2) { viennacl::backend::finish(); if (s1 != s2) return (s1 - s2) / std::max(std::fabs(s1), std::fabs(s2)); return 0; } // // ------------------------------------------------------------- // template<typename ScalarType, typename ViennaCLVectorType> ScalarType diff(std::vector<ScalarType> const & v1, ViennaCLVectorType const & vcl_vec) { std::vector<ScalarType> v2_cpu(vcl_vec.size()); viennacl::backend::finish(); viennacl::copy(vcl_vec, v2_cpu); for (unsigned int i=0;i<v1.size(); ++i) { if ( std::max( std::fabs(v2_cpu[i]), std::fabs(v1[i]) ) > 0 ) v2_cpu[i] = std::fabs(v2_cpu[i] - v1[i]) / std::max( std::fabs(v2_cpu[i]), std::fabs(v1[i]) ); else v2_cpu[i] = 0.0; } ScalarType norm_inf = 0; for (std::size_t i=0; i<v2_cpu.size(); ++i) norm_inf = std::max<ScalarType>(norm_inf, std::fabs(v2_cpu[i])); return norm_inf; } template<typename T1, typename T2> int check(T1 const & t1, T2 const & t2, double epsilon) { int retval = EXIT_SUCCESS; double temp = std::fabs(diff(t1, t2)); if (temp > epsilon) { std::cout << "# Error! Relative difference: " << temp << std::endl; retval = EXIT_FAILURE; } return retval; } // // ------------------------------------------------------------- // template< typename NumericT, typename Epsilon, typename STLVectorType1, typename STLVectorType2, typename STLVectorType3, typename STLVectorType4, typename ViennaCLVectorType1, typename ViennaCLVectorType2, typename ViennaCLVectorType3, typename ViennaCLVectorType4 > int test(Epsilon const& epsilon, STLVectorType1 & std_v1, STLVectorType2 & std_v2, STLVectorType3 & std_v3, STLVectorType4 & std_v4, ViennaCLVectorType1 & vcl_v1, ViennaCLVectorType2 & vcl_v2, ViennaCLVectorType3 & vcl_v3, ViennaCLVectorType4 & vcl_v4) { int retval = EXIT_SUCCESS; viennacl::tools::uniform_random_numbers<NumericT> randomNumber; for (std::size_t i=0; i<std_v1.size(); ++i) { std_v1[i] = NumericT(1.0) + randomNumber(); std_v2[i] = NumericT(1.0) + randomNumber(); std_v3[i] = NumericT(1.0) + randomNumber(); std_v4[i] = NumericT(1.0) + randomNumber(); } viennacl::copy(std_v1.begin(), std_v1.end(), vcl_v1.begin()); //resync viennacl::copy(std_v2.begin(), std_v2.end(), vcl_v2.begin()); viennacl::copy(std_v3.begin(), std_v3.end(), vcl_v3.begin()); viennacl::copy(std_v4.begin(), std_v4.end(), vcl_v4.begin()); std::cout << "Checking for successful copy..." << std::endl; if (check(std_v1, vcl_v1, epsilon) != EXIT_SUCCESS) return EXIT_FAILURE; if (check(std_v2, vcl_v2, epsilon) != EXIT_SUCCESS) return EXIT_FAILURE; if (check(std_v3, vcl_v3, epsilon) != EXIT_SUCCESS) return EXIT_FAILURE; if (check(std_v4, vcl_v4, epsilon) != EXIT_SUCCESS) return EXIT_FAILURE; std::vector<NumericT> ref_result(40, 0.0); viennacl::vector<NumericT> result = viennacl::scalar_vector<NumericT>(40, 0.0); std::cout << "Testing inner_prod with two vectors..." << std::endl; ref_result[2] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[2] += std_v1[i] * std_v1[i]; ref_result[5] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[5] += std_v1[i] * std_v2[i]; viennacl::project(result, viennacl::slice(2, 3, 2)) = viennacl::linalg::inner_prod(vcl_v1, viennacl::tie(vcl_v1, vcl_v2)); if (check(ref_result, result, epsilon) != EXIT_SUCCESS) { std::copy(ref_result.begin(), ref_result.end(), std::ostream_iterator<NumericT>(std::cout, " ")); std::cout << std::endl; std::cout << result << std::endl; return EXIT_FAILURE; } ref_result[3] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[3] += std_v1[i] * std_v3[i]; ref_result[7] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[7] += std_v1[i] * std_v4[i]; viennacl::project(result, viennacl::slice(3, 4, 2)) = viennacl::linalg::inner_prod(vcl_v1, viennacl::tie(vcl_v3, vcl_v4)); if (check(ref_result, result, epsilon) != EXIT_SUCCESS) { std::copy(ref_result.begin(), ref_result.end(), std::ostream_iterator<NumericT>(std::cout, " ")); std::cout << std::endl; std::cout << result << std::endl; return EXIT_FAILURE; } std::cout << "Testing inner_prod with three vectors..." << std::endl; ref_result[1] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[1] += std_v1[i] * std_v1[i]; ref_result[3] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[3] += std_v1[i] * std_v2[i]; ref_result[5] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[5] += std_v1[i] * std_v3[i]; viennacl::project(result, viennacl::slice(1, 2, 3)) = viennacl::linalg::inner_prod(vcl_v1, viennacl::tie(vcl_v1, vcl_v2, vcl_v3)); if (check(ref_result, result, epsilon) != EXIT_SUCCESS) { std::copy(ref_result.begin(), ref_result.end(), std::ostream_iterator<NumericT>(std::cout, " ")); std::cout << std::endl; std::cout << result << std::endl; return EXIT_FAILURE; } ref_result[2] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[2] += std_v1[i] * std_v3[i]; ref_result[6] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[6] += std_v1[i] * std_v2[i]; ref_result[10] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[10] += std_v1[i] * std_v4[i]; viennacl::project(result, viennacl::slice(2, 4, 3)) = viennacl::linalg::inner_prod(vcl_v1, viennacl::tie(vcl_v3, vcl_v2, vcl_v4)); if (check(ref_result, result, epsilon) != EXIT_SUCCESS) { std::copy(ref_result.begin(), ref_result.end(), std::ostream_iterator<NumericT>(std::cout, " ")); std::cout << std::endl; std::cout << result << std::endl; return EXIT_FAILURE; } std::cout << "Testing inner_prod with four vectors..." << std::endl; ref_result[4] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[4] += std_v1[i] * std_v1[i]; ref_result[5] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[5] += std_v1[i] * std_v2[i]; ref_result[6] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[6] += std_v1[i] * std_v3[i]; ref_result[7] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[7] += std_v1[i] * std_v4[i]; viennacl::project(result, viennacl::slice(4, 1, 4)) = viennacl::linalg::inner_prod(vcl_v1, viennacl::tie(vcl_v1, vcl_v2, vcl_v3, vcl_v4)); if (check(ref_result, result, epsilon) != EXIT_SUCCESS) { std::copy(ref_result.begin(), ref_result.end(), std::ostream_iterator<NumericT>(std::cout, " ")); std::cout << std::endl; std::cout << result << std::endl; return EXIT_FAILURE; } ref_result[3] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[3] += std_v1[i] * std_v3[i]; ref_result[6] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[6] += std_v1[i] * std_v2[i]; ref_result[9] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[9] += std_v1[i] * std_v4[i]; ref_result[12] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[12] += std_v1[i] * std_v1[i]; viennacl::project(result, viennacl::slice(3, 3, 4)) = viennacl::linalg::inner_prod(vcl_v1, viennacl::tie(vcl_v3, vcl_v2, vcl_v4, vcl_v1)); if (check(ref_result, result, epsilon) != EXIT_SUCCESS) { std::copy(ref_result.begin(), ref_result.end(), std::ostream_iterator<NumericT>(std::cout, " ")); std::cout << std::endl; std::cout << result << std::endl; return EXIT_FAILURE; } std::cout << "Testing inner_prod with five vectors..." << std::endl; ref_result[1] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[1] += std_v1[i] * std_v1[i]; ref_result[3] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[3] += std_v1[i] * std_v2[i]; ref_result[5] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[5] += std_v1[i] * std_v3[i]; ref_result[7] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[7] += std_v1[i] * std_v4[i]; ref_result[9] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[9] += std_v1[i] * std_v2[i]; viennacl::project(result, viennacl::slice(1, 2, 5)) = viennacl::linalg::inner_prod(vcl_v1, viennacl::tie(vcl_v1, vcl_v2, vcl_v3, vcl_v4, vcl_v2)); if (check(ref_result, result, epsilon) != EXIT_SUCCESS) { std::copy(ref_result.begin(), ref_result.end(), std::ostream_iterator<NumericT>(std::cout, " ")); std::cout << std::endl; std::cout << result << std::endl; return EXIT_FAILURE; } ref_result[2] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[2] += std_v1[i] * std_v3[i]; ref_result[4] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[4] += std_v1[i] * std_v2[i]; ref_result[6] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[6] += std_v1[i] * std_v4[i]; ref_result[8] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[8] += std_v1[i] * std_v1[i]; ref_result[10] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[10] += std_v1[i] * std_v2[i]; viennacl::project(result, viennacl::slice(2, 2, 5)) = viennacl::linalg::inner_prod(vcl_v1, viennacl::tie(vcl_v3, vcl_v2, vcl_v4, vcl_v1, vcl_v2)); if (check(ref_result, result, epsilon) != EXIT_SUCCESS) { std::copy(ref_result.begin(), ref_result.end(), std::ostream_iterator<NumericT>(std::cout, " ")); std::cout << std::endl; std::cout << result << std::endl; return EXIT_FAILURE; } std::cout << "Testing inner_prod with eight vectors..." << std::endl; ref_result[1] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[1] += std_v1[i] * std_v1[i]; ref_result[5] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[5] += std_v1[i] * std_v2[i]; ref_result[9] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[9] += std_v1[i] * std_v3[i]; ref_result[13] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[13] += std_v1[i] * std_v4[i]; ref_result[17] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[17] += std_v1[i] * std_v3[i]; ref_result[21] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[21] += std_v1[i] * std_v2[i]; ref_result[25] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[25] += std_v1[i] * std_v1[i]; ref_result[29] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[29] += std_v1[i] * std_v2[i]; std::vector<viennacl::vector_base<NumericT> const *> vecs1(8); vecs1[0] = &vcl_v1; vecs1[1] = &vcl_v2; vecs1[2] = &vcl_v3; vecs1[3] = &vcl_v4; vecs1[4] = &vcl_v3; vecs1[5] = &vcl_v2; vecs1[6] = &vcl_v1; vecs1[7] = &vcl_v2; viennacl::vector_tuple<NumericT> tuple1(vecs1); viennacl::project(result, viennacl::slice(1, 4, 8)) = viennacl::linalg::inner_prod(vcl_v1, tuple1); if (check(ref_result, result, epsilon) != EXIT_SUCCESS) { std::copy(ref_result.begin(), ref_result.end(), std::ostream_iterator<NumericT>(std::cout, " ")); std::cout << std::endl; std::cout << result << std::endl; return EXIT_FAILURE; } ref_result[3] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[3] += std_v1[i] * std_v2[i]; ref_result[5] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[5] += std_v1[i] * std_v4[i]; ref_result[7] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[7] += std_v1[i] * std_v1[i]; ref_result[9] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[9] += std_v1[i] * std_v2[i]; ref_result[11] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[11] += std_v1[i] * std_v2[i]; ref_result[13] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[13] += std_v1[i] * std_v1[i]; ref_result[15] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[15] += std_v1[i] * std_v4[i]; ref_result[17] = 0; for (std::size_t i=0; i<std_v1.size(); ++i) ref_result[17] += std_v1[i] * std_v2[i]; std::vector<viennacl::vector_base<NumericT> const *> vecs2(8); vecs2[0] = &vcl_v2; vecs2[1] = &vcl_v4; vecs2[2] = &vcl_v1; vecs2[3] = &vcl_v2; vecs2[4] = &vcl_v2; vecs2[5] = &vcl_v1; vecs2[6] = &vcl_v4; vecs2[7] = &vcl_v2; viennacl::vector_tuple<NumericT> tuple2(vecs2); viennacl::project(result, viennacl::slice(3, 2, 8)) = viennacl::linalg::inner_prod(vcl_v1, tuple2); if (check(ref_result, result, epsilon) != EXIT_SUCCESS) { std::copy(ref_result.begin(), ref_result.end(), std::ostream_iterator<NumericT>(std::cout, " ")); std::cout << std::endl; std::cout << result << std::endl; return EXIT_FAILURE; } // -------------------------------------------------------------------------- return retval; } template< typename NumericT, typename Epsilon > int test(Epsilon const& epsilon) { viennacl::tools::uniform_random_numbers<NumericT> randomNumber; int retval = EXIT_SUCCESS; std::size_t size = 8 * 1337; std::cout << "Running tests for vector of size " << size << std::endl; // // Set up STL objects // std::vector<NumericT> std_full_vec1(size); std::vector<NumericT> std_full_vec2(std_full_vec1.size()); for (std::size_t i=0; i<std_full_vec1.size(); ++i) { std_full_vec1[i] = NumericT(1.0) + randomNumber(); std_full_vec2[i] = NumericT(1.0) + randomNumber(); } std::vector<NumericT> std_slice_vec1(std_full_vec1.size() / 8); for (std::size_t i=0; i<std_slice_vec1.size(); ++i) std_slice_vec1[i] = std_full_vec1[ std_full_vec1.size() / 8 + i * 3]; std::vector<NumericT> std_slice_vec2(std_full_vec2.size() / 8); for (std::size_t i=0; i<std_slice_vec2.size(); ++i) std_slice_vec2[i] = std_full_vec2[2 * std_full_vec2.size() / 8 + i * 1]; std::vector<NumericT> std_slice_vec3(std_full_vec1.size() / 8); for (std::size_t i=0; i<std_slice_vec3.size(); ++i) std_slice_vec3[i] = std_full_vec1[4 * std_full_vec1.size() / 8 + i * 2]; std::vector<NumericT> std_slice_vec4(std_full_vec2.size() / 8); for (std::size_t i=0; i<std_slice_vec4.size(); ++i) std_slice_vec4[i] = std_full_vec2[3 * std_full_vec2.size() / 8 + i * 4]; // // Set up ViennaCL objects // viennacl::vector<NumericT> vcl_full_vec1(std_full_vec1.size()); viennacl::vector<NumericT> vcl_full_vec2(std_full_vec2.size()); viennacl::fast_copy(std_full_vec1.begin(), std_full_vec1.end(), vcl_full_vec1.begin()); viennacl::copy (std_full_vec2.begin(), std_full_vec2.end(), vcl_full_vec2.begin()); viennacl::slice vcl_s1( vcl_full_vec1.size() / 8, 3, vcl_full_vec1.size() / 8); viennacl::slice vcl_s2(2 * vcl_full_vec2.size() / 8, 1, vcl_full_vec2.size() / 8); viennacl::slice vcl_s3(4 * vcl_full_vec1.size() / 8, 2, vcl_full_vec1.size() / 8); viennacl::slice vcl_s4(3 * vcl_full_vec2.size() / 8, 4, vcl_full_vec2.size() / 8); viennacl::vector_slice< viennacl::vector<NumericT> > vcl_slice_vec1(vcl_full_vec1, vcl_s1); viennacl::vector_slice< viennacl::vector<NumericT> > vcl_slice_vec2(vcl_full_vec2, vcl_s2); viennacl::vector_slice< viennacl::vector<NumericT> > vcl_slice_vec3(vcl_full_vec1, vcl_s3); viennacl::vector_slice< viennacl::vector<NumericT> > vcl_slice_vec4(vcl_full_vec2, vcl_s4); viennacl::vector<NumericT> vcl_short_vec1(vcl_slice_vec1); viennacl::vector<NumericT> vcl_short_vec2 = vcl_slice_vec2; viennacl::vector<NumericT> vcl_short_vec3 = vcl_slice_vec2 + vcl_slice_vec1; viennacl::vector<NumericT> vcl_short_vec4 = vcl_short_vec1 + vcl_slice_vec2; std::vector<NumericT> std_short_vec1(std_slice_vec1); std::vector<NumericT> std_short_vec2(std_slice_vec2); std::vector<NumericT> std_short_vec3(std_slice_vec2.size()); for (std::size_t i=0; i<std_short_vec3.size(); ++i) std_short_vec3[i] = std_slice_vec2[i] + std_slice_vec1[i]; std::vector<NumericT> std_short_vec4(std_slice_vec2.size()); for (std::size_t i=0; i<std_short_vec4.size(); ++i) std_short_vec4[i] = std_slice_vec1[i] + std_slice_vec2[i]; std::cout << "Testing creation of vectors from slice..." << std::endl; if (check(std_short_vec1, vcl_short_vec1, epsilon) != EXIT_SUCCESS) return EXIT_FAILURE; if (check(std_short_vec2, vcl_short_vec2, epsilon) != EXIT_SUCCESS) return EXIT_FAILURE; if (check(std_short_vec3, vcl_short_vec3, epsilon) != EXIT_SUCCESS) return EXIT_FAILURE; if (check(std_short_vec4, vcl_short_vec4, epsilon) != EXIT_SUCCESS) return EXIT_FAILURE; // // Now start running tests for vectors, ranges and slices: // std::cout << " ** [vector|vector|vector|vector] **" << std::endl; retval = test<NumericT>(epsilon, std_short_vec1, std_short_vec2, std_short_vec2, std_short_vec2, vcl_short_vec1, vcl_short_vec2, vcl_short_vec3, vcl_short_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [vector|vector|vector|slice] **" << std::endl; retval = test<NumericT>(epsilon, std_short_vec1, std_short_vec2, std_short_vec2, std_slice_vec2, vcl_short_vec1, vcl_short_vec2, vcl_short_vec3, vcl_slice_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [vector|vector|slice|vector] **" << std::endl; retval = test<NumericT>(epsilon, std_short_vec1, std_short_vec2, std_slice_vec2, std_short_vec2, vcl_short_vec1, vcl_short_vec2, vcl_slice_vec3, vcl_short_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [vector|vector|slice|slice] **" << std::endl; retval = test<NumericT>(epsilon, std_short_vec1, std_short_vec2, std_slice_vec2, std_slice_vec2, vcl_short_vec1, vcl_short_vec2, vcl_slice_vec3, vcl_slice_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [vector|slice|vector|vector] **" << std::endl; retval = test<NumericT>(epsilon, std_short_vec1, std_slice_vec2, std_short_vec2, std_short_vec2, vcl_short_vec1, vcl_slice_vec2, vcl_short_vec3, vcl_short_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [vector|slice|vector|slice] **" << std::endl; retval = test<NumericT>(epsilon, std_short_vec1, std_slice_vec2, std_short_vec2, std_slice_vec2, vcl_short_vec1, vcl_slice_vec2, vcl_short_vec3, vcl_slice_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [vector|slice|slice|vector] **" << std::endl; retval = test<NumericT>(epsilon, std_short_vec1, std_slice_vec2, std_slice_vec2, std_short_vec2, vcl_short_vec1, vcl_slice_vec2, vcl_slice_vec3, vcl_short_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [vector|slice|slice|slice] **" << std::endl; retval = test<NumericT>(epsilon, std_short_vec1, std_slice_vec2, std_slice_vec2, std_slice_vec2, vcl_short_vec1, vcl_slice_vec2, vcl_slice_vec3, vcl_slice_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; ////////////////// std::cout << " ** [slice|vector|vector|vector] **" << std::endl; retval = test<NumericT>(epsilon, std_slice_vec1, std_short_vec2, std_short_vec2, std_short_vec2, vcl_slice_vec1, vcl_short_vec2, vcl_short_vec3, vcl_short_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [slice|vector|vector|slice] **" << std::endl; retval = test<NumericT>(epsilon, std_slice_vec1, std_short_vec2, std_short_vec2, std_slice_vec2, vcl_slice_vec1, vcl_short_vec2, vcl_short_vec3, vcl_slice_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [slice|vector|slice|vector] **" << std::endl; retval = test<NumericT>(epsilon, std_slice_vec1, std_short_vec2, std_slice_vec2, std_short_vec2, vcl_slice_vec1, vcl_short_vec2, vcl_slice_vec3, vcl_short_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [slice|vector|slice|slice] **" << std::endl; retval = test<NumericT>(epsilon, std_slice_vec1, std_short_vec2, std_slice_vec2, std_slice_vec2, vcl_slice_vec1, vcl_short_vec2, vcl_slice_vec3, vcl_slice_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [slice|slice|vector|vector] **" << std::endl; retval = test<NumericT>(epsilon, std_slice_vec1, std_slice_vec2, std_short_vec2, std_short_vec2, vcl_slice_vec1, vcl_slice_vec2, vcl_short_vec3, vcl_short_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [slice|slice|vector|slice] **" << std::endl; retval = test<NumericT>(epsilon, std_slice_vec1, std_slice_vec2, std_short_vec2, std_slice_vec2, vcl_slice_vec1, vcl_slice_vec2, vcl_short_vec3, vcl_slice_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [slice|slice|slice|vector] **" << std::endl; retval = test<NumericT>(epsilon, std_slice_vec1, std_slice_vec2, std_slice_vec2, std_short_vec2, vcl_slice_vec1, vcl_slice_vec2, vcl_slice_vec3, vcl_short_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; std::cout << " ** [slice|slice|slice|slice] **" << std::endl; retval = test<NumericT>(epsilon, std_slice_vec1, std_slice_vec2, std_slice_vec2, std_slice_vec2, vcl_slice_vec1, vcl_slice_vec2, vcl_slice_vec3, vcl_slice_vec4); if (retval != EXIT_SUCCESS) return EXIT_FAILURE; return EXIT_SUCCESS; } // // ------------------------------------------------------------- // int main() { std::cout << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << "## Test :: Vector multiple inner products" << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << std::endl; int retval = EXIT_SUCCESS; std::cout << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << std::endl; { typedef float NumericT; NumericT epsilon = static_cast<NumericT>(1.0E-4); std::cout << "# Testing setup:" << std::endl; std::cout << " eps: " << epsilon << std::endl; std::cout << " numeric: float" << std::endl; retval = test<NumericT>(epsilon); if ( retval == EXIT_SUCCESS ) std::cout << "# Test passed" << std::endl; else return retval; } std::cout << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << std::endl; #ifdef VIENNACL_WITH_OPENCL if ( viennacl::ocl::current_device().double_support() ) #endif { { typedef double NumericT; NumericT epsilon = 1.0E-12; std::cout << "# Testing setup:" << std::endl; std::cout << " eps: " << epsilon << std::endl; std::cout << " numeric: double" << std::endl; retval = test<NumericT>(epsilon); if ( retval == EXIT_SUCCESS ) std::cout << "# Test passed" << std::endl; else return retval; } std::cout << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << std::endl; } std::cout << std::endl; std::cout << "------- Test completed --------" << std::endl; std::cout << std::endl; return retval; }
the_stack
NTL_CLIENT #define bidx blockIdx.x #define bidy blockIdx.y #define bidz blockIdx.z #define tidx threadIdx.x #define tidy threadIdx.y #define tidz threadIdx.z #define bdimx blockDim.x #define bdimy blockDim.y #define bdimz blockDim.z #define gdimx gridDim.x #define gdimy gridDim.y #define gdimz gridDim.z namespace cuHE { /////////////////////////////////////////////////////////// // ntt twiddle factors in device global memory uint64 **d_roots_16k = NULL; uint64 **d_roots_32k = NULL; uint64 **d_roots_64k = NULL; // ntt twiddle factors in device texture memory texture<uint32, 1> tex_roots_16k; texture<uint32, 1> tex_roots_32k; texture<uint32, 1> tex_roots_64k; // pre-load ntt twiddle factors for a specific size void preload_ntt(int len) { if (len != 16384 && len != 32768 && len != 65536) { printf("Error: pre-load NTT with wrong length.\n"); exit(-1); } // generate twiddle factors on host const ZZ P = to_ZZ(0xffffffff00000001); const ZZ g = to_ZZ((uint64)15893793146607301539); int e0 = 65536/len; ZZ w0 = PowerMod(g, e0, P); uint64 *h_roots = new uint64[len]; for (int i=0; i<len; i++) conv(h_roots[i], PowerMod(w0, i, P)); // copy to device memory int nGPUs = numDevices(); if (len == 16384) { d_roots_16k = new uint64 *[nGPUs]; for (int dev=0; dev<nGPUs; dev++) { CSC(cudaSetDevice(dev)); CSC(cudaMalloc(&d_roots_16k[dev], len*sizeof(uint64))); CSC(cudaMemcpy(d_roots_16k[dev], h_roots, len*sizeof(uint64), cudaMemcpyHostToDevice)); CSC(cudaBindTexture(NULL, tex_roots_16k, d_roots_16k[dev], len*sizeof(uint64))); } } else if (len == 32768) { d_roots_32k = new uint64 *[nGPUs]; for (int dev=0; dev<nGPUs; dev++) { CSC(cudaSetDevice(dev)); CSC(cudaMalloc(&d_roots_32k[dev], len*sizeof(uint64))); CSC(cudaMemcpy(d_roots_32k[dev], h_roots, len*sizeof(uint64), cudaMemcpyHostToDevice)); CSC(cudaBindTexture(NULL, tex_roots_32k, d_roots_32k[dev], len*sizeof(uint64))); } } else if (len == 65536) { d_roots_64k = new uint64 *[nGPUs]; for (int dev=0; dev<nGPUs; dev++) { CSC(cudaSetDevice(dev)); CSC(cudaMalloc(&d_roots_64k[dev], len*sizeof(uint64))); CSC(cudaMemcpy(d_roots_64k[dev], h_roots, len*sizeof(uint64), cudaMemcpyHostToDevice)); CSC(cudaBindTexture(NULL, tex_roots_64k, d_roots_64k[dev], len*sizeof(uint64))); } } delete [] h_roots; return; } // free and delete allocated memory space void cleanup_ntt() { int nGPUs = numDevices(); if (d_roots_16k != NULL) { for (int dev=0; dev<nGPUs; dev++) { CSC(cudaSetDevice(dev)); CSC(cudaFree(d_roots_16k[dev])); } delete [] d_roots_16k; d_roots_16k = NULL; } if (d_roots_32k != NULL) { for (int dev=0; dev<nGPUs; dev++) { CSC(cudaSetDevice(dev)); CSC(cudaFree(d_roots_32k[dev])); } delete [] d_roots_32k; d_roots_32k = NULL; } if (d_roots_64k != NULL) { for (int dev=0; dev<nGPUs; dev++) { CSC(cudaSetDevice(dev)); CSC(cudaFree(d_roots_64k[dev])); } delete [] d_roots_64k; d_roots_64k = NULL; } return; } // crt constant memory #define maxNumPrimes 103 // chosen for 64 KB constant memory __constant__ uint32 const_p[maxNumPrimes]; __constant__ uint32 const_invp[maxNumPrimes*(maxNumPrimes-1)/2]; __constant__ uint32 const_M[maxNumPrimes]; __constant__ uint32 const_mi[maxNumPrimes*maxNumPrimes]; __constant__ uint32 const_bi[maxNumPrimes]; void preload_crt_p(uint32* src, int words) { for (int dev=0; dev<numDevices(); dev++) { CSC(cudaSetDevice(dev)); CSC(cudaMemcpyToSymbol(const_p, src, words*sizeof(uint32), 0, cudaMemcpyHostToDevice)); } } void preload_crt_invp(uint32* src, int words) { for (int dev=0; dev<numDevices(); dev++) { CSC(cudaSetDevice(dev)); CSC(cudaMemcpyToSymbol(const_invp, src, words*sizeof(uint32), 0, cudaMemcpyHostToDevice)); } } void load_icrt_M(uint32* src, int words, int dev, cudaStream_t st) { CSC(cudaSetDevice(dev)); CSC(cudaMemcpyToSymbolAsync(const_M, src, words*sizeof(uint32), 0, cudaMemcpyHostToDevice, st)); } void load_icrt_mi(uint32* src, int words, int dev, cudaStream_t st) { CSC(cudaSetDevice(dev)); CSC(cudaMemcpyToSymbolAsync(const_mi, src, words*sizeof(uint32), 0, cudaMemcpyHostToDevice, st)); } void load_icrt_bi(uint32* src, int words, int dev, cudaStream_t st) { CSC(cudaSetDevice(dev)); CSC(cudaMemcpyToSymbolAsync(const_bi, src, words*sizeof(uint32), 0, cudaMemcpyHostToDevice, st)); } // barrett reduction texture and device memory static uint64 **d_u_ntt; static uint64 **d_m_ntt; static uint32 **d_m_crt; texture<uint32, 1> tex_u_ntt; texture<uint32, 1> tex_m_ntt; texture<uint32, 1> tex_m_crt; void preload_barrett_u_n(uint64* src, size_t size) { d_u_ntt = new uint64*[numDevices()]; for (int dev=0; dev<numDevices(); dev++) { CSC(cudaSetDevice(dev)); CSC(cudaMalloc(&d_u_ntt[dev], size)); } CSC(cudaSetDevice(0)); for (int dev=0; dev<numDevices(); dev++) CSC(cudaMemcpyPeer(d_u_ntt[dev], dev, src, 0, size)); for (int dev=0; dev<numDevices(); dev++) { CSC(cudaSetDevice(dev)); CSC(cudaBindTexture(NULL, tex_u_ntt, d_u_ntt[dev], size)); } CSC(cudaStreamSynchronize(0)); } void preload_barrett_m_n(uint64* src, size_t size) { d_m_ntt = new uint64*[numDevices()]; for (int dev=0; dev<numDevices(); dev++) { CSC(cudaSetDevice(dev)); CSC(cudaMalloc(&d_m_ntt[dev], size)); } CSC(cudaSetDevice(0)); for (int dev=0; dev<numDevices(); dev++) CSC(cudaMemcpyPeer(d_m_ntt[dev], dev, src, 0, size)); for (int dev=0; dev<numDevices(); dev++) { CSC(cudaSetDevice(dev)); CSC(cudaBindTexture(NULL, tex_m_ntt, d_m_ntt[dev], size)); } } void preload_barrett_m_c(uint32* src, size_t size) { d_m_crt = new uint32*[numDevices()]; for (int dev=0; dev<numDevices(); dev++) { CSC(cudaSetDevice(dev)); CSC(cudaMalloc(&d_m_crt[dev], size)); } CSC(cudaSetDevice(0)); for (int dev=0; dev<numDevices(); dev++) CSC(cudaMemcpyPeer(d_m_crt[dev], dev, src, 0, size)); for (int dev=0; dev<numDevices(); dev++) { CSC(cudaSetDevice(dev)); CSC(cudaBindTexture(NULL, tex_m_crt, d_m_crt[dev], size)); } } /////////////////////////////////////////////////////////// // 4-point NTT __inline__ __device__ void _ntt4(uint64 *x) { register uint64 s[4], temp; s[0] = _add_modP(x[0], x[2]); s[1] = _sub_modP(x[0], x[2]); s[2] = _add_modP(x[1], x[3]); s[3] = _sub_modP(x[1], x[3]); temp = _ls_modP(s[3], 48); x[0] = _add_modP(s[0], s[2]); x[1] = _add_modP(s[1], temp); x[2] = _sub_modP(s[0], s[2]); x[3] = _sub_modP(s[1], temp); } // 8-point NTT with 0 paddings __inline__ __device__ void _ntt8_ext(uint64 *x) { register uint64 s[8], temp; temp = _ls_modP(x[2], 48); s[0] = _add_modP(x[0], x[2]); s[1] = _add_modP(x[0], temp); s[2] = _sub_modP(x[0], x[2]); s[3] = _sub_modP(x[0], temp); temp = _ls_modP(x[3], 48); s[4] = _add_modP(x[1], x[3]); s[5] = _add_modP(x[1], temp); s[6] = _sub_modP(x[1], x[3]); s[7] = _sub_modP(x[1], temp); x[0] = _add_modP(s[0], s[4]); x[4] = _sub_modP(s[0], s[4]); temp = _ls_modP(s[5], 24); x[1] = _add_modP(s[1], temp); x[5] = _sub_modP(s[1], temp); temp = _ls_modP(s[6], 48); x[2] = _add_modP(s[2], temp); x[6] = _sub_modP(s[2], temp); temp = _ls_modP(s[7], 72); x[3] = _add_modP(s[3], temp); x[7] = _sub_modP(s[3], temp); } // 8-point NTT __inline__ __device__ void _ntt8(uint64 *x) { register uint64 s[8], temp; s[0] = _add_modP(x[0], x[4]); s[1] = _sub_modP(x[0], x[4]); s[2] = _add_modP(x[2], x[6]); s[3] = _sub_modP(x[2], x[6]); s[4] = _add_modP(x[1], x[5]); s[5] = _sub_modP(x[1], x[5]); s[6] = _add_modP(x[3], x[7]); s[7] = _sub_modP(x[3], x[7]); x[0] = _add_modP(s[0], s[2]); x[2] = _sub_modP(s[0], s[2]); temp = _ls_modP(s[3], 48); x[1] = _add_modP(s[1], temp); x[3] = _sub_modP(s[1], temp); x[4] = _add_modP(s[4], s[6]); x[6] = _sub_modP(s[4], s[6]); temp = _ls_modP(s[7], 48); x[5] = _add_modP(s[5], temp); x[7] = _sub_modP(s[5], temp); s[0] = _add_modP(x[0], x[4]); s[4] = _sub_modP(x[0], x[4]); temp = _ls_modP(x[5], 24); s[1] = _add_modP(x[1], temp); s[5] = _sub_modP(x[1], temp); temp = _ls_modP(x[6], 48); s[2] = _add_modP(x[2], temp); s[6] = _sub_modP(x[2], temp); temp = _ls_modP(x[7], 72); s[3] = _add_modP(x[3], temp); s[7] = _sub_modP(x[3], temp); x[0] = s[0]; x[1] = s[1]; x[2] = s[2]; x[3] = s[3]; x[4] = s[4]; x[5] = s[5]; x[6] = s[6]; x[7] = s[7]; } // 16384-point NTT/INTT __global__ void ntt_1_16k_ext(uint64 *dst, uint32 *src) { __shared__ uint64 buffer[512]; __shared__ uint64 roots[128]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; // from/to mem/buffer addr mapping //coalesced global memory access & minimum shared memory bank conflicts fmem = ((tidx&0x38)<<5)|(bidx<<3)|(tidx&0x7); tbuf = ((tidx&0x38)<<3)|(tidx&0x7); fbuf = tidx; tmem = (bidx<<9)|((tidx&0x7)>>2<<8)|(tidx>>3<<2)|(tidx&0x3); roots[tidx] = tex1Dfetch(tex_roots_16k, (((bidx*2)*tidx)<<3)+1); roots[tidx] <<= 32; roots[tidx] += tex1Dfetch(tex_roots_16k, ((bidx*2)*tidx)<<3); roots[tidx+64] = tex1Dfetch(tex_roots_16k, (((bidx*2+1)*tidx)<<3)+1); roots[tidx+64] <<= 32; roots[tidx+64] += tex1Dfetch(tex_roots_16k, ((bidx*2+1)*tidx)<<3); //load 4 or 8 samples from global memory, compute 8-sample ntt #pragma unroll for (int i=0; i<4; i++) samples[i] = (src+(bidy<<14))[(i<<11)|fmem]; _ntt8_ext(samples); //times twiddle factors of 64 samples, store to buffer #pragma unroll for(int i=0; i<8; i++) buffer[(i<<3)|tbuf] = _ls_modP(samples[i], (tidx>>3)*i*3); __syncthreads(); //load 8 samples from shared mem in transposed way, compute 8-sample ntt #pragma unroll for(int i=0; i<8; i++) samples[i] = buffer[(i<<6)|fbuf]; _ntt8(samples); #pragma unroll for(int i=0; i<8; i++) (dst+(bidy<<14))[tmem|(i<<5)] = _mul_modP(samples[i], roots[((tidx&0x7)>>2<<6)|(tidx>>3)|(i<<3)]); } __global__ void ntt_1_16k_ext_block(uint64 *dst, uint32 *src, int w, int wid, int w32){ __shared__ uint64 buffer[512], roots[128]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = ((tidx&0x38)<<5)|(bidx<<3)|(tidx&0x7); tbuf = ((tidx&0x38)<<3)|(tidx&0x7); fbuf = tidx; tmem = (bidx<<9)|((tidx&0x7)>>2<<8)|(tidx>>3<<2)|(tidx&0x3); roots[tidx] = tex1Dfetch(tex_roots_16k, (((bidx*2)*tidx)<<3)+1); roots[tidx] <<= 32; roots[tidx] += tex1Dfetch(tex_roots_16k, ((bidx*2)*tidx)<<3); roots[tidx+64] = tex1Dfetch(tex_roots_16k, (((bidx*2+1)*tidx)<<3)+1); roots[tidx+64] <<= 32; roots[tidx+64] += tex1Dfetch(tex_roots_16k, ((bidx*2+1)*tidx)<<3); #pragma unroll for (int i=0; i<4; i++) { if ((((w*wid)>>5)+1) < w32) { samples[i] = (src+(bidy<<14)*w32)[((i<<11)|fmem)*w32+((w*wid)>>5)+1]; samples[i] <<= 32; samples[i] += (src+(bidy<<14)*w32)[((i<<11)|fmem)*w32+((w*wid)>>5)]; } else samples[i] = (src+(bidy<<14)*w32)[((i<<11)|fmem)*w32+((w*wid)>>5)]; samples[i] >>= (w*wid)&0x1f; samples[i] &= (0x1<<w)-1; } _ntt8_ext(samples); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<3)|tbuf] = _ls_modP(samples[i], (tidx>>3)*i*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[(i<<6)|fbuf]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<14))[tmem|(i<<5)] = _mul_modP(samples[i], roots[((tidx&0x7)>>2<<6)|(tidx>>3)|(i<<3)]); } __global__ void ntt_2_16k(uint64 *src) { __shared__ uint64 buffer[512]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf, addrx, addry; fmem = (tidx>>3<<8)|(bidx<<3)|((tidx&0x7)>>2<<2)|(tidx&0x3); tbuf = ((tidx&0x38)<<3)|(tidx&0x7); fbuf = tidx; tmem = fmem; addrx = tmem&0x3; addry = tmem>>2; #pragma unroll for (int i=0; i<8; i++) samples[i] = (src+(bidy<<14))[(i<<11)|fmem]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<3)|tbuf] = _ls_modP(samples[i], ((tidx>>3)*i)*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[(i<<6)|fbuf]; _ntt8(samples); register uint64 root; #pragma unroll for (int i=0; i<8; i++) { root = tex1Dfetch(tex_roots_16k, ((addry|(i<<9))*addrx*2)+1); root <<= 32; root += tex1Dfetch(tex_roots_16k, (addry|(i<<9))*addrx*2); (src+(bidy<<14))[(i<<11)|tmem] = _mul_modP(samples[i], root); } } __global__ void ntt_3_16k(uint64 *dst, uint64 *src) { __shared__ uint64 buffer[512]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = (bidx<<9)|tidx; tbuf = tidx; fbuf = tidx<<3; tmem = (bidx<<7)|(tidx<<1); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<6)|tbuf] = (src+(bidy<<14))[(i<<6)|fmem]; __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[fbuf|i]; _ntt4(samples); _ntt4(samples+4); #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<14))[((i&0x3)<<12)|((i&0x7)>>2)|tmem] = samples[i]; } __global__ void intt_1_16k(uint64 *dst, uint64 *src) { __shared__ uint64 buffer[512], roots[128]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = (tidx>>3<<8)|(bidx<<3)|((tidx&0x7)>>2<<2)|(tidx&0x3); tbuf = ((tidx&0x38)<<3)|(tidx&0x7); fbuf = tidx; tmem = (bidx<<9)|((tidx&0x7)>>2<<8)|(tidx>>3<<2)|(tidx&0x3); roots[tidx] = tex1Dfetch(tex_roots_16k, (((bidx*2)*tidx)<<3)+1); roots[tidx] <<= 32; roots[tidx] += tex1Dfetch(tex_roots_16k, ((bidx*2)*tidx)<<3); roots[tidx+64] = tex1Dfetch(tex_roots_16k, (((bidx*2+1)*tidx)<<3)+1); roots[tidx+64] <<= 32; roots[tidx+64] += tex1Dfetch(tex_roots_16k, ((bidx*2+1)*tidx)<<3); #pragma unroll for (int i=0; i<8; i++) samples[i] = (src+(bidy<<14))[(16384-((i<<11)|fmem))%16384]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<3)|tbuf] = _ls_modP(samples[i], (tidx>>3)*i*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[(i<<6)|fbuf]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<14))[tmem|(i<<5)] = _mul_modP(samples[i], roots[((tidx&0x7)>>2<<6)|(tidx>>3)|(i<<3)]); } __global__ void intt_3_16k_modcrt(uint32 *dst, uint64 *src, int crtidx) { __shared__ uint64 buffer[512]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = (bidx<<9)|tidx; tbuf = tidx; fbuf = tidx<<3; tmem = (bidx<<7)|(tidx<<1); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<6)|tbuf] = (src+(bidy<<14))[(i<<6)|fmem]; __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[fbuf|i]; _ntt4(samples); _ntt4(samples+4); #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<14))[((i&0x3)<<12)|((i&0x7)>>2)|tmem] = (uint32)(_mul_modP(samples[i], 18445618169508003841)%const_p[crtidx]); } // 32768-point NTT/INTT __global__ void ntt_1_32k_ext(uint64 *dst, uint32 *src) { __shared__ uint64 buffer[512], roots[64]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = ((tidx&0x38)<<6)|(bidx<<3)|(tidx&0x7); tbuf = ((tidx&0x38)<<3)|(tidx&0x7); fbuf = tidx; tmem = (bidx<<9)|fbuf; roots[tidx] = tex1Dfetch(tex_roots_32k, ((bidx*tidx)<<4)+1); roots[tidx] <<= 32; roots[tidx] += tex1Dfetch(tex_roots_32k, (bidx*tidx)<<4); #pragma unroll for (int i=0; i<4; i++) samples[i] = (src+(bidy<<15))[(i<<12)|fmem]; _ntt8_ext(samples); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<3)|tbuf] = _ls_modP(samples[i], (tidx>>3)*i*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[fbuf|(i<<6)]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<15))[tmem|(i<<6)] = _mul_modP(samples[i], roots[(tidx>>3)|(i<<3)]); } __global__ void ntt_1_32k_ext_block(uint64 *dst, uint32 *src, int w, int wid, int w32) { __shared__ uint64 buffer[512], roots[64]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = ((tidx&0x38)<<6)|(bidx<<3)|(tidx&0x7); tbuf = ((tidx&0x38)<<3)|(tidx&0x7); fbuf = tidx; tmem = (bidx<<9)|fbuf; roots[tidx] = tex1Dfetch(tex_roots_32k, ((bidx*tidx)<<4)+1); roots[tidx] <<= 32; roots[tidx] += tex1Dfetch(tex_roots_32k, (bidx*tidx)<<4); #pragma unroll for (int i=0; i<4; i++) { if ((((w*wid)>>5)+1) < w32) { samples[i] = (src+(bidy<<15)*w32)[((i<<12)|fmem)*w32+((w*wid)>>5)+1]; samples[i] <<= 32; samples[i] += (src+(bidy<<15)*w32)[((i<<12)|fmem)*w32+((w*wid)>>5)]; } else samples[i] = (src+(bidy<<15)*w32)[((i<<12)|fmem)*w32+((w*wid)>>5)]; samples[i] >>= (w*wid)&0x1f; samples[i] &= (0x1<<w)-1; } _ntt8_ext(samples); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<3)|tbuf] = _ls_modP(samples[i], (tidx>>3)*i*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[fbuf|(i<<6)]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<15))[tmem|(i<<6)] = _mul_modP(samples[i], roots[(tidx>>3)|(i<<3)]); } __global__ void ntt_2_32k(uint64 *src) { __shared__ uint64 buffer[512]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf, addrx, addry; fmem = ((tidx&0x38)<<6)|(bidx<<3)|(tidx&0x7); tbuf = ((tidx&0x38)<<3)|(tidx&0x7); fbuf = tidx; tmem = ((tidx&0x38)<<6)|(bidx<<3)|(tidx&0x7); addrx = (tidx&0x7); addry = ((tidx&0x38)<<3)|bidx; #pragma unroll for (int i=0; i<8; i++) samples[i] = (src+(bidy<<15))[(i<<12)|fmem]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<3)|tbuf] = _ls_modP(samples[i], ((tidx>>3)*i)*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[(i<<6)|fbuf]; _ntt8(samples); register uint64 root; #pragma unroll for (int i=0; i<8; i++){ root = tex1Dfetch(tex_roots_32k, ((addry|(i<<9))*addrx*2)+1); root <<= 32; root += tex1Dfetch(tex_roots_32k, (addry|(i<<9))*addrx*2); (src+(bidy<<15))[(i<<12) | tmem] = _mul_modP(samples[i], root); } } __global__ void ntt_3_32k(uint64 *dst, uint64 *src) { __shared__ uint64 buffer[512]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = (bidx<<9)|tidx; tbuf = tidx; fbuf = tidx<<3; tmem = (bidx<<6)|tidx; #pragma unroll for (int i=0; i<8; i++) buffer[(i<<6)|tbuf] = (src+(bidy<<15))[(i<<6)|fmem]; __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[fbuf|i]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<15))[(i<<12)|tmem] = samples[i]; } __global__ void intt_1_32k(uint64 *dst, uint64 *src) { __shared__ uint64 buffer[512], roots[64]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = ((tidx&0x38)<<6)|(bidx<<3)|(tidx&0x7); tbuf = (tidx&0x38)<<3|(tidx&0x7); fbuf = tidx; tmem = (bidx<<9)|fbuf; roots[tidx] = tex1Dfetch(tex_roots_32k, ((bidx*tidx)<<4)+1); roots[tidx] <<= 32; roots[tidx] += tex1Dfetch(tex_roots_32k, (bidx*tidx)<<4); #pragma unroll for (int i=0; i<8; i++) samples[i] = (src+(bidy<<15))[(32768-((i<<12)|fmem))%32768]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<3)|tbuf] = _ls_modP(samples[i], ((tidx>>3)*i)*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[fbuf|(i<<6)]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<15))[tmem|(i<<6)] = _mul_modP(samples[i], roots[(tidx>>3)|(i<<3)]); } __global__ void intt_3_32k_modcrt(uint32 *dst, uint64 *src, int crtidx) { __shared__ uint64 buffer[512]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = (bidx<<9)|tidx; tbuf = tidx; fbuf = tidx<<3; tmem = (bidx<<6)|tidx; #pragma unroll for (int i=0; i<8; i++) buffer[(i<<6)|tbuf] = (src+(bidy<<15))[(i<<6)|fmem]; __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[fbuf|i]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<15))[(i<<12)|tmem] = (uint32)(_mul_modP(samples[i], 18446181119461294081)%const_p[crtidx]); } // 65536-point NTT/INTT __global__ void ntt_1_64k_ext(uint64 *dst, uint32 *src) { __shared__ uint64 buffer[512], roots[64]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = ((tidx&0x38)<<7)|(bidx<<3)|(tidx&0x7); tbuf = ((tidx&0x38)<<3)|(tidx&0x7); fbuf = tidx; tmem = ((bidx&0x7E)<<9)|((tidx&0x38)<<1)|((bidx&0x1)<<3)|(tidx&0x7); roots[tidx] = tex1Dfetch(tex_roots_64k, (((bidx>>1)*tidx)<<5)+1); roots[tidx] <<= 32; roots[tidx] += tex1Dfetch(tex_roots_64k, ((bidx>>1)*tidx)<<5); #pragma unroll for (int i=0; i<4; i++) samples[i] = (src+(bidy<<16))[(i<<13)|fmem]; _ntt8_ext(samples); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<3) | tbuf] = _ls_modP(samples[i], ((tidx>>3)*i)*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[fbuf | (i<<6)]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<16))[tmem | (i<<7)] = _mul_modP(samples[i], roots[(tidx>>3)|(i<<3)]); } __global__ void ntt_1_64k_ext_block(uint64 *dst, uint32 *src, int w, int wid, int w32) { __shared__ uint64 buffer[512], roots[64]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = ((tidx&0x38)<<7)|(bidx<<3)|(tidx&0x7); tbuf = ((tidx&0x38)<<3)|(tidx&0x7); fbuf = tidx; tmem = ((bidx&0x7E)<<9)|((tidx&0x38)<<1)|((bidx&0x1)<<3)|(tidx&0x7); roots[tidx] = tex1Dfetch(tex_roots_64k, (((bidx>>1)*tidx)<<5)+1); roots[tidx] <<= 32; roots[tidx] += tex1Dfetch(tex_roots_64k, ((bidx>>1)*tidx)<<5); #pragma unroll for (int i=0; i<4; i++) { if ((((w*wid)>>5)+1) < w32) { samples[i] = (src+(bidy<<16)*w32)[((i<<13)|fmem)*w32+((w*wid)>>5)+1]; samples[i] <<= 32; samples[i] += (src+(bidy<<16)*w32)[((i<<13)|fmem)*w32+((w*wid)>>5)]; } else samples[i] = (src+(bidy<<16)*w32)[((i<<13)|fmem)*w32+((w*wid)>>5)]; samples[i] >>= (w*wid)&0x1f; samples[i] &= (0x1<<w)-1; } _ntt8_ext(samples); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<3)|tbuf] = _ls_modP(samples[i], ((tidx>>3)*i)*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[fbuf|(i<<6)]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<16))[tmem|(i<<7)] = _mul_modP(samples[i], roots[(tidx>>3)|(i<<3)]); } __global__ void ntt_2_64k(uint64 *src) { __shared__ uint64 buffer[512]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf, addrx, addry; fmem = ((tidx&0x38)<<7)|(bidx<<3)|(tidx&0x7); tbuf = (tidx&0x38)<<3|(tidx&0x7); fbuf = tidx; tmem = fmem; addrx = (tidx&0x7)|((bidx&0x1)<<3); addry = ((tidx&0x38)<<3)|(bidx>>1); #pragma unroll for (int i=0; i<8; i++) samples[i] = (src+(bidy<<16))[(i<<13)|fmem]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<3)|tbuf] = _ls_modP(samples[i], (tidx>>3)*i*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[(i<<6)|fbuf]; _ntt8(samples); register uint64 root; #pragma unroll for (int i=0; i<8; i++) { root = tex1Dfetch(tex_roots_64k, ((addry|(i<<9))*addrx*2)+1); root <<= 32; root += tex1Dfetch(tex_roots_64k, (addry|(i<<9))*addrx*2); (src+(bidy<<16))[(i<<13)|tmem] = _mul_modP(samples[i], root); } } __global__ void ntt_3_64k(uint64 *dst, uint64 *src) { __shared__ uint64 buffer[512]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = (bidx<<9)|((tidx&0x3E)<<3)|(tidx&0x1); tbuf = tidx<<3; fbuf = ((tidx&0x38)<<3)|(tidx&0x7); tmem = (bidx<<9)|((tidx&0x38)<<3)|(tidx&0x7); #pragma unroll for (int i=0; i<8; i++) samples[i] = (src+(bidy<<16))[fmem|(i<<1)]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) buffer[i|tbuf] = _ls_modP(samples[i], ((tidx&0x1)<<2)*i*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[fbuf|(i<<3)]; register uint32 addr; #pragma unroll for (int i=0; i<4; i++) { addr = tmem|((2*i)<<3); (dst+(bidy<<16))[((addr&0xf)<<12)|(addr>>4)] = _add_modP(samples[2*i], samples[2*i+1]); addr = tmem|((2*i+1)<<3); (dst+(bidy<<16))[((addr&0xf)<<12)|(addr>>4)] = _sub_modP(samples[2*i], samples[2*i+1]); } } __global__ void intt_1_64k(uint64 *dst, uint64 *src) { __shared__ uint64 buffer[512], roots[64]; register uint64 samples[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = ((tidx&0x38)<<7)|(bidx<<3)|(tidx&0x7); tbuf = (tidx&0x38)<<3|(tidx&0x7); fbuf = tidx; tmem = ((bidx&0x7E)<<9)|((tidx&0x38)<<1)|((bidx&0x1)<<3)|(tidx&0x7); roots[tidx] = tex1Dfetch(tex_roots_64k, (((bidx>>1)*tidx)<<5)+1); roots[tidx] <<= 32; roots[tidx] += tex1Dfetch(tex_roots_64k, ((bidx>>1)*tidx)<<5); #pragma unroll for (uint32 i=0; i<8; i++) samples[i] = (src+(bidy<<16))[(65536-(fmem|(i<<13)))%65536]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) buffer[(i<<3)|tbuf] = _ls_modP(samples[i], ((tidx>>3)*i)*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[fbuf|(i<<6)]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<16))[tmem|(i<<7)] = _mul_modP(samples[i], roots[(tidx>>3)|(i<<3)]); } __global__ void intt_3_64k_modcrt(uint32 *dst, uint64 *src, int crtidx) { __shared__ uint64 buffer[512]; register uint64 samples[8], s8[8]; register uint32 fmem, tmem, fbuf, tbuf; fmem = (bidx<<9)|((tidx&0x3E)<<3)|(tidx&0x1); tbuf = tidx<<3; fbuf = ((tidx&0x38)<<3) | (tidx&0x7); tmem = (bidx<<9)|((tidx&0x38)<<3) | (tidx&0x7); #pragma unroll for (int i=0; i<8; i++) samples[i] = (src+(bidy<<16))[fmem|(i<<1)]; _ntt8(samples); #pragma unroll for (int i=0; i<8; i++) buffer[tbuf|i] = _ls_modP(samples[i], ((tidx&0x1)<<2)*i*3); __syncthreads(); #pragma unroll for (int i=0; i<8; i++) samples[i] = buffer[fbuf|(i<<3)]; #pragma unroll for (int i=0; i<4; i++) { s8[2*i] = _add_modP(samples[2*i], samples[2*i+1]); s8[2*i+1] = _sub_modP(samples[2*i], samples[2*i+1]); } #pragma unroll for (int i=0; i<8; i++) (dst+(bidy<<16))[(((tmem|(i<<3))&0xf)<<12)|((tmem|(i<<3))>>4)] = (uint32)(_mul_modP(s8[i], 18446462594437939201)%const_p[crtidx]); } // CRT kernels __device__ __inline__ bool leq_M(unsigned int *x, int M_w32) { // less or equal than M ? if (x[M_w32] > 0) return true; for (int i=M_w32-1; i>=0; i--) { if (x[i] < const_M[i]) return false; else if (x[i] > const_M[i]) return true; } return true; } __global__ void crt(uint32 *dst, uint32 *src, int pnum, int w32, int mlen, int clen) { register int idx = bidx*bdimx+tidx; extern __shared__ uint32 buff[]; uint32 *in = buff; for (int i=0; i<w32; i++) in[bdimx*i+tidx] = src[bidx*bdimx*w32+bdimx*i+tidx]; __syncthreads(); if (idx < mlen) { uint32 *coeff = &in[tidx*w32]; register uint32 h, l; for (int crt=0; crt<pnum; crt++) { l = coeff[w32-1]; l %= const_p[crt]; for (int i = w32-2; i>=0; i--) { h = l; l = coeff[i]%const_p[crt]; l = (uint32)((((uint64)h<<32)+l)%const_p[crt]); } dst[crt*clen+idx] = l; } } } __global__ void icrt(uint32 *dst, uint32 *src, int pnum, int M_w32, int mi_w32, int mlen, int clen) { int idx = bidx*bdimx+tidx; if (idx < mlen) { register uint32 sum[maxNumPrimes+1]; register uint64 tar; register uint32 tt; for (int i=0; i<maxNumPrimes+1; i++) sum[i] = 0; for (int crt=0; crt<pnum; crt++) { tar = src[crt*clen+idx]; tar %= const_p[crt]; tar *= const_bi[crt]; tt = (uint32)(tar%const_p[crt]); // low asm("mad.lo.cc.u32 %0,%1,%2,%3;" : "=r"(sum[0]) : "r"(tt), "r"(const_mi[crt*mi_w32+0]), "r"(sum[0])); for (int i=1; i<mi_w32; i++) asm("madc.lo.cc.u32 %0,%1,%2,%3;" : "=r"(sum[i]) : "r"(tt), "r"(const_mi[crt*mi_w32+i]), "r"(sum[i])); for (int i=mi_w32; i<M_w32; i++) asm("addc.cc.u32 %0,%0,%1;" : "+r"(sum[i]) : "r"(0)); asm("addc.u32 %0,%0,%1;" : "+r"(sum[M_w32]) : "r"(0)); // high asm("mad.hi.cc.u32 %0,%1,%2,%3;" : "=r"(sum[1]) : "r"(tt), "r"(const_mi[crt*mi_w32+0]), "r"(sum[1])); for (int i=1; i<mi_w32; i++) asm("madc.hi.cc.u32 %0,%1,%2,%3;" : "=r"(sum[i+1]) : "r"(tt), "r"(const_mi[crt*mi_w32+i]), "r"(sum[i+1])); for (int i=mi_w32; i<M_w32-1; i++) asm("addc.cc.u32 %0,%0,%1;" : "+r"(sum[i+1]) : "r"(0)); asm("addc.u32 %0,%0,%1;" : "+r"(sum[M_w32]) : "r"(0)); // mod M if (leq_M(sum, M_w32)) { asm("sub.cc.u32 %0,%0,%1;" : "+r"(sum[0]) : "r"(const_M[0])); for (int i=1; i<M_w32; i++) asm("subc.cc.u32 %0,%0,%1;" : "+r"(sum[i]) : "r"(const_M[i])); asm("subc.u32 %0,%0,%1;" : "+r"(sum[M_w32]) : "r"(0)); } } for (int i=0; i<M_w32; i++) dst[bidx*M_w32*bdimx+tidx*M_w32+i] = sum[i]; // not coalesced??? } } // Barrett Reduction kernels __global__ void barrett_mul_un(uint64 *tar, int pnum, int nlen) { register int idx = bidx*bdimx+tidx; register uint64 a, b, offset = 0; for (int crt=0; crt<pnum; crt++) { a = tar[offset+idx]; b = tex1Dfetch(tex_u_ntt, offset*2+idx*2+1); b <<= 32; b += tex1Dfetch(tex_u_ntt, offset*2+idx*2); tar[offset+idx] = _mul_modP(a, b); offset += nlen; } } __global__ void barrett_mul_mn(uint64 *tar, int pnum, int nlen) { register int idx = bidx*bdimx+tidx; register uint64 a, b, offset = 0; for (int crt=0; crt<pnum; crt++) { a = tar[offset+idx]; b = tex1Dfetch(tex_m_ntt, offset*2+idx*2+1); b <<= 32; b += tex1Dfetch(tex_m_ntt, offset*2+idx*2); tar[offset+idx] = _mul_modP(a, b); offset += nlen; } } __global__ void barrett_sub_1(uint32 *y, uint32 *x, int pnum, int mlen, int nlen) { register int idx = bidx*bdimx+tidx; register uint32 a, b; if (idx < mlen) { for (int crt=0; crt<pnum; crt++) { a = y[crt*nlen+mlen+idx]; b = x[crt*nlen+mlen+idx]; if (a < b) a += const_p[crt]; a -= b; y[crt*nlen+mlen+idx] = a; } } } __global__ void barrett_sub_2(uint32 *y, uint32 *x, int pnum, int nlen) { register int idx = bidx*bdimx+tidx; register uint32 a, b; for (int crt=0; crt<pnum; crt++) { a = y[crt*nlen+idx]; b = x[crt*nlen+idx]; if (a < b) a += const_p[crt]; a -= b; y[crt*nlen+idx] = a; } } __global__ void barrett_sub_mc(uint32 *x, int pnum, int mlen, int clen, int nlen) { register int idx = bidx*bdimx+tidx; register uint32 d, s; extern __shared__ uint32 t[]; int offset = 0; while (offset+tidx < pnum) { t[offset+tidx] = x[(offset+tidx)*nlen+mlen]; offset += bdimx; } __syncthreads(); if (idx < mlen-1) { for (int crt=0; crt<pnum; crt++) { if (t[crt] > 0) { d = x[crt*nlen+idx]; s = tex1Dfetch(tex_m_crt, crt*clen+idx); if (d < s) d += const_p[crt]; d -= s; x[crt*nlen+idx] = d; } } } } // Relinearization kernels // ek[knum][pnum][NTTLEN] __global__ void relinMulAddAll(uint64 *dst, uint64 *c, uint64 *ek, int pnum, int knum, int nlen) { register int idx = bidx*bdimx+tidx; extern __shared__ uint64 cbuff[]; // cache c[knum*bdimx] for (int i=0; i<knum; i++) cbuff[i*bdimx+tidx] = c[i*nlen+idx]; __syncthreads(); register uint64 sum = 0, offset = 0; for (int i=0; i<pnum; i++) { sum = 0; offset = i*nlen; for (int j=0; j<knum; j++) { sum = _add_modP(sum, _mul_modP(cbuff[j*bdimx+tidx], ek[offset+idx])); offset += pnum*nlen; } dst[i*nlen+idx] = sum; } } // pnum * ek[knum][NTTLEN] __global__ void relinMulAddPerCrt(uint64 *dst, uint64 *c, uint64 *ek, int knum, int nlen) { register int idx = bidx*bdimx+tidx; register uint64 sum = 0, offset = 0; for (int i=0; i<knum; i++) { sum = _add_modP(sum, _mul_modP(c[offset+idx], ek[offset+idx])); offset += nlen; } dst[idx] = sum; } // NTT domain arithmetic __global__ void ntt_mul(uint64 *z, uint64 *x, uint64 *y, int pnum, int nlen) { register int idx = bidx*bdimx+tidx; register uint64 a, b, offset = 0; for (int crt=0; crt<pnum; crt++) { a = x[offset+idx]; b = y[offset+idx]; z[offset+idx] = _mul_modP(a, b); offset += nlen; } } __global__ void ntt_add(uint64 *z, uint64 *x, uint64 *y, int pnum, int nlen) { register int idx = bidx*bdimx+tidx; register uint64 a, b, offset = 0; for (int crt=0; crt<pnum; crt++) { a = x[offset+idx]; b = y[offset+idx]; z[offset+idx] = _add_modP(a, b); offset += nlen; } } __global__ void ntt_mul_nx1(uint64 *z, uint64 *x, uint64 *scalar, int pnum, int nlen) { register int idx = bidx*bdimx+tidx; register uint64 a, b = scalar[idx], offset = 0; for (int crt=0; crt<pnum; crt++) { a = x[offset+idx]; z[offset+idx] = _mul_modP(a, b); offset += nlen; } } __global__ void ntt_add_nx1(uint64 *z, uint64 *x, uint64 *scalar, int pnum, int nlen) { register int idx = bidx*bdimx+tidx; register uint64 a, b = scalar[idx], offset = 0; for (int crt=0; crt<pnum; crt++) { a = x[offset+idx]; z[offset+idx] = _add_modP(a, b); offset += nlen; } } // CRT domain arithmetic __global__ void crt_mul_int(uint32 *y, uint32 *x, int a, int pnum, int clen) { register int idx = bidx*bdimx+tidx; if (idx < pnum) { register uint64 temp; temp = x[idx*clen]; temp *= a; temp %= const_p[idx]; y[idx*clen] = temp; } } __global__ void crt_add(uint32 *x, uint32 *a, uint32 *b, int pnum, int mlen, int clen) { register int idx = bidx*bdimx+tidx; if (idx < mlen) { for (int i=0; i<pnum; i++) x[i*clen+idx] = (a[i*clen+idx]+b[i*clen+idx])%const_p[i]; } } __global__ void crt_add_int(uint32 *y, uint32 *x, int a, int pnum, int clen) { register int idx = bidx*bdimx+tidx; if (idx < pnum) y[idx*clen] = (x[idx*clen]+(a%const_p[idx]))%const_p[idx]; } __global__ void crt_add_nx1(uint32 *x, uint32 *a, uint32 *scalar, int pnum, int mlen, int clen) { register int idx = bidx*bdimx+tidx; register uint32 b = scalar[idx]; if (idx < mlen) { for (int i=0; i<pnum; i++) x[i*clen+idx] = (a[i*clen+idx]+b)%const_p[i]; } } // Modulus Switching __global__ void modswitch(uint32 *dst, uint32 *src, int pnum, int mlen, int clen, int modmsg) { register int idx = bidx*bdimx+tidx; if (idx < mlen) { register int dirty = src[(pnum-1)*clen+idx]; register uint32 pt = const_p[pnum-1]; register int ep = dirty%modmsg; if (ep != 0) { if (dirty>((pt-1)/2)) dirty -= ep*pt; else dirty += ep*pt; } register int temp; register uint64 tt; for (int i=0; i<pnum-1; i++) { temp = src[i*clen+idx]; while (temp < dirty) temp += const_p[i]; temp -= dirty; tt = temp; tt *= const_invp[(pnum-1)*(pnum-2)/2+i]; tt %= const_p[i]; dst[i*clen+idx] = (uint32)tt; } } } } // namespace cuHE
the_stack
#include <cuda.h> #include <cuda_runtime.h> #include <cuda_runtime_api.h> #include "cuda_util.h" #include <iostream> #include "mat.h" #include <float.h> #include "pooling_cuda.h" __global__ void gpu_pooling_cuda_forward_global_max(const float* a_input, const ncnn::CudaMatInfo a_info, float* output, const ncnn::CudaMatInfo output_info, const ncnn::Pooling_cuda::Pooling_info pooling_info, int* pooling_lock) { const int column = blockIdx.x * blockDim.x + threadIdx.x; const int row = blockIdx.y * blockDim.y + threadIdx.y; const int channel = blockIdx.z * blockDim.z + threadIdx.z; const int block_column = threadIdx.x; const int block_row = threadIdx.y; extern __shared__ float buffer[]; buffer[block_row * blockDim.x + block_column] = -FLT_MAX; if (column >= a_info.w || row >= a_info.h || channel >= a_info.c) { return; } const float* input_ptr = a_input+channel*a_info.cstep + row*a_info.w + column; buffer[block_row * blockDim.x + block_column] = *input_ptr; __syncthreads(); if (block_column == 0) { float max_row_value = -FLT_MAX; for (int i = 0; i < blockDim.x; ++i) { if (buffer[block_row * blockDim.x + i] > max_row_value) { max_row_value = buffer[block_row * blockDim.x + i]; } } buffer[block_row * blockDim.x] = max_row_value; __syncthreads(); if (block_row == 0) { float max_block_value = -FLT_MAX; for (int i=0; i<blockDim.y; ++i) { if (max_block_value < buffer[i*blockDim.x]) { max_block_value = buffer[i * blockDim.x]; } } cuda_lock(pooling_lock); if (output[channel] < max_block_value) { output[channel] = max_block_value; } cuda_unlock(pooling_lock); } } } __global__ void gpu_pooling_cuda_forward_global_sum(const float* a_input, const ncnn::CudaMatInfo a_info, float* output, const ncnn::CudaMatInfo output_info, const ncnn::Pooling_cuda::Pooling_info pooling_info, int* pooling_lock) { const int column = blockIdx.x * blockDim.x + threadIdx.x; const int row = blockIdx.y * blockDim.y + threadIdx.y; const int channel = blockIdx.z * blockDim.z + threadIdx.z; const int block_column = threadIdx.x; const int block_row = threadIdx.y; extern __shared__ float buffer[]; buffer[block_row * blockDim.x + block_column] = 0; if (column >= a_info.w || row >= a_info.h || channel >= a_info.c) { return; } const float* input_ptr = a_input+channel*a_info.cstep + row*a_info.w + column; buffer[block_row * blockDim.x + block_column] = *input_ptr; __syncthreads(); if (block_column == 0) { float sum_row_value = 0; for (int i = 0; i < blockDim.x; ++i) { sum_row_value += buffer[block_row * blockDim.x + i]; } // printf("Row: %d sum_row_value: %f\n", row, sum_row_value); buffer[block_row * blockDim.x] = sum_row_value; __syncthreads(); if (block_row == 0) { float sum_block_value = 0; for (int i=0; i<blockDim.y; ++i) { sum_block_value += buffer[i*blockDim.x]; } // printf("Row: %d sum_block_value: %f\n", row, sum_block_value); cuda_lock(pooling_lock); output[channel] += sum_block_value; // printf("TWO channel:%d output[channel]: %f sum_block_value: %f\n", channel, output[channel], sum_block_value); cuda_unlock(pooling_lock); } } } __global__ void gpu_pooling_cuda_forward_global_sum_total(float* output, const ncnn::CudaMatInfo input_info, const int size) { const int column = blockIdx.x * blockDim.x + threadIdx.x; const int row = blockIdx.y * blockDim.y + threadIdx.y; const int channel = blockIdx.z * blockDim.z + threadIdx.z; if (column >= 1 || row >= 1 || channel >= input_info.c) { return; } output[channel] = output[channel] / size; } __global__ void gpu_pooling_cuda_forward_max(const float* a_input, const ncnn::CudaMatInfo a_info, float* output, const ncnn::CudaMatInfo output_info, const ncnn::Pooling_cuda::Pooling_info pooling_info, const int* gpu_space_offset) { const int output_column = blockIdx.x * blockDim.x + threadIdx.x; const int output_row = blockIdx.y * blockDim.y + threadIdx.y; const int channel = blockIdx.z * blockDim.z + threadIdx.z; if (output_column >= output_info.w || output_row >= output_info.h || channel >= output_info.c) { return; } const float* input_ptr = a_input + channel * a_info.cstep + output_row * a_info.w * pooling_info.stride_h + output_column * pooling_info.stride_w; float max_value = -FLT_MAX; for (int k = 0; k < pooling_info.maxk; k++) { const float val = input_ptr[gpu_space_offset[k]]; max_value = max(max_value, val); } float* output_ptr = output + channel * output_info.cstep + output_row * output_info.w + output_column; *output_ptr = max_value; } __global__ void gpu_pooling_cuda_forward_sum0(const float* a_input, const ncnn::CudaMatInfo a_info, float* output, const ncnn::CudaMatInfo output_info, const ncnn::Pooling_cuda::Pooling_info pooling_info, int* pooling_lock) { const int output_column = blockIdx.x * blockDim.x + threadIdx.x; const int output_row = blockIdx.y * blockDim.y + threadIdx.y; const int channel = blockIdx.z * blockDim.z + threadIdx.z; if (output_column >= output_info.w || output_row >= output_info.h || channel >= output_info.c) { return; } const float* input_ptr_channel = a_input + channel * a_info.cstep; const int sy0 = output_row * pooling_info.stride_h; const int sx0 = output_column * pooling_info.stride_w; float sum = 0; int area = 0; for (int ki = 0; ki < pooling_info.kernel_h; ki++) { int sy = sy0 + ki; if (sy < pooling_info.pad_top) continue; if (sy >= a_info.h - pooling_info.pad_bottom - pooling_info.htailpad) break; for (int kj = 0; kj < pooling_info.kernel_w; kj++) { int sx = sx0 + kj; if (sx < pooling_info.pad_left) continue; if (sx >= a_info.w - pooling_info.pad_right - pooling_info.wtailpad) break; float val = *(input_ptr_channel+sy*a_info.w+sx); sum += val; area += 1; } } float* output_ptr = output + channel * output_info.cstep + output_row * output_info.w + output_column; *output_ptr = sum / area; } __global__ void gpu_pooling_cuda_forward_sum1(const float* a_input, const ncnn::CudaMatInfo a_info, float* output, const ncnn::CudaMatInfo output_info, const ncnn::Pooling_cuda::Pooling_info pooling_info, const int* gpu_space_offset) { const int output_column = blockIdx.x * blockDim.x + threadIdx.x; const int output_row = blockIdx.y * blockDim.y + threadIdx.y; const int channel = blockIdx.z * blockDim.z + threadIdx.z; if (output_column >= output_info.w || output_row >= output_info.h || channel >= output_info.c) { return; } const float* input_ptr = a_input + channel * a_info.cstep + output_row * a_info.w * pooling_info.stride_h + output_column * pooling_info.stride_w; float sum = 0; for (int k = 0; k < pooling_info.maxk; k++) { const float val = input_ptr[gpu_space_offset[k]]; sum += val; } float* output_ptr = output + channel * output_info.cstep + output_row * output_info.w + output_column; *output_ptr = sum / pooling_info.maxk; } namespace ncnn { int pooling_cuda_forward_global(const CudaMat& bottom_blob, CudaMat& top_blob, const Pooling_cuda::Pooling_info& info) { const int number_of_threads = bottom_blob.w; int thread_per_block_x = ((number_of_threads - 1) / 32 + 1) * 32; if (thread_per_block_x > 64) thread_per_block_x = 64; int thread_per_block_y = ((bottom_blob.h - 1) / 8 + 1) * 8; if (thread_per_block_y > 8) thread_per_block_y = 8; const int thread_per_block_z = 1; const int total_number_of_channels = bottom_blob.c; const int total_number_of_columns = bottom_blob.w; const int total_number_of_rows = bottom_blob.h; const dim3 block_size(thread_per_block_x, thread_per_block_y, thread_per_block_z); const dim3 grid_size((total_number_of_columns - 1) / thread_per_block_x + 1, (total_number_of_rows - 1) / thread_per_block_y + 1, (total_number_of_channels - 1) / thread_per_block_z + 1); const ncnn::CudaMatInfo bottom_blob_info{bottom_blob}; const ncnn::CudaMatInfo top_blob_info{top_blob}; if (info.pooling_type == Pooling::PoolMethod_MAX) { top_blob.fill(-FLT_MAX); gpu_pooling_cuda_forward_global_max<<<grid_size, block_size, block_size.x * block_size.y * sizeof(float)>>>(static_cast<const float*>(bottom_blob.get_craw_data()), bottom_blob_info, static_cast<float*>(top_blob.get_raw_data()), top_blob_info, info, info.pooling_lock); } else if (info.pooling_type == Pooling::PoolMethod_AVE) { top_blob.fill(0); gpu_pooling_cuda_forward_global_sum<<<grid_size, block_size, block_size.x * block_size.y * sizeof(float)>>>(static_cast<const float*>(bottom_blob.get_craw_data()), bottom_blob_info, static_cast<float*>(top_blob.get_raw_data()), top_blob_info, info, info.pooling_lock); const int thread_per_block_z_sum = 16; const dim3 block_size_sum(1, 1, thread_per_block_z_sum); const dim3 grid_size_sum(1, 1, (total_number_of_channels - 1) / thread_per_block_z_sum + 1); gpu_pooling_cuda_forward_global_sum_total<<<grid_size_sum, block_size_sum>>>(static_cast<float*>(top_blob.get_raw_data()), bottom_blob_info, (bottom_blob_info.w * bottom_blob_info.h)); } return 0; } int pooling_cuda_forward(const CudaMat& bottom_blob_bordered, CudaMat& top_blob, const Pooling_cuda::Pooling_info& info) { const int number_of_threads = top_blob.w; int thread_per_block_x = ((number_of_threads - 1) / 32 + 1) * 32; if (thread_per_block_x > 64) thread_per_block_x = 64; int thread_per_block_y = ((top_blob.h - 1) / 8 + 1) * 8; if (thread_per_block_y > 8) thread_per_block_y = 8; const int thread_per_block_z = 1; const int total_number_of_channels = top_blob.c; const int total_number_of_columns = top_blob.w; const int total_number_of_rows = top_blob.h; const dim3 block_size(thread_per_block_x, thread_per_block_y, thread_per_block_z); const dim3 grid_size((total_number_of_columns - 1) / thread_per_block_x + 1, (total_number_of_rows - 1) / thread_per_block_y + 1, (total_number_of_channels - 1) / thread_per_block_z + 1); const ncnn::CudaMatInfo bottom_blob_bordered_info{bottom_blob_bordered}; const ncnn::CudaMatInfo top_blob_info{top_blob}; if (info.pooling_type == Pooling::PoolMethod_MAX) { top_blob.fill(-FLT_MAX); gpu_pooling_cuda_forward_max<<<grid_size, block_size>>>(static_cast<const float*>(bottom_blob_bordered.get_craw_data()), bottom_blob_bordered_info, static_cast<float*>(top_blob.get_raw_data()), top_blob_info, info, info.gpu_space_ofs.get()); } else if (info.pooling_type == Pooling::PoolMethod_AVE) { if (info.avgpool_count_include_pad == 0) { top_blob.fill(0); gpu_pooling_cuda_forward_sum0<<<grid_size, block_size>>>(static_cast<const float*>(bottom_blob_bordered.get_craw_data()), bottom_blob_bordered_info, static_cast<float*>(top_blob.get_raw_data()), top_blob_info, info, info.pooling_lock); } else { top_blob.fill(0); gpu_pooling_cuda_forward_sum1<<<grid_size, block_size>>>(static_cast<const float*>(bottom_blob_bordered.get_craw_data()), bottom_blob_bordered_info, static_cast<float*>(top_blob.get_raw_data()), top_blob_info, info, info.gpu_space_ofs.get()); } } return 0; } }
the_stack
// All of the following CUDA kernels and constants are copied from PyTorch (link // below) and modified/optimized for NNabla. // https://github.com/pytorch/pytorch/blob/32b37ba2462d9d87337a4fe332f95524a4c49777/aten/src/ATen/native/cuda/Normalization.cuh #include <nbla/cuda/common.hpp> namespace nbla { // The maximum number of threads in a block #if defined(__HIP_PLATFORM_HCC__) constexpr int SYNC_BN_MAX_BLOCK_SIZE = 256; #else constexpr int SYNC_BN_MAX_BLOCK_SIZE = 512; #endif constexpr unsigned SYNC_BN_MAX_GRID_SIZE = 65535u; constexpr int SYNC_BN_ELEMENTS_PER_ITER = 4; // enables concurrency within each thread to hide latency constexpr int SYNC_BN_ELEMENTS_PER_THREAD = 16; constexpr int SYNC_BN_OPTIMAL_TILE_W = 32; constexpr int SYNC_BN_MAX_H_BLOCK = 128; // Number of threads in a block given an input size up to SYNC_BN_MAX_BLOCK_SIZE static int getNumThreads(int nElem) { #if defined(__HIP_PLATFORM_HCC__) int threadSizes[5] = {16, 32, 64, 128, SYNC_BN_MAX_BLOCK_SIZE}; #else int threadSizes[5] = {32, 64, 128, 256, SYNC_BN_MAX_BLOCK_SIZE}; #endif for (int i = 0; i != 5; ++i) { if (nElem <= threadSizes[i]) { return threadSizes[i]; } } return SYNC_BN_MAX_BLOCK_SIZE; } // returns 2**floor(log2(n)) static int lastPow2(unsigned int n) { n |= (n >> 1); n |= (n >> 2); n |= (n >> 4); n |= (n >> 8); n |= (n >> 16); return std::max<int>(1, n - (n >> 1)); } // Returns the index of the most significant 1 bit in `val`. __device__ __forceinline__ int getMSB(int val) { return 31 - __clz(val); } template <typename T> __device__ __forceinline__ T WARP_SHFL_XOR(T value, int laneMask, int width = warpSize, unsigned int mask = 0xffffffff) { #ifndef __HIP_PLATFORM_HCC__ return __shfl_xor_sync(mask, value, laneMask, width); #else return __shfl_xor(value, laneMask, width); #endif } // Sum across all threads within a warp template <typename T> static __device__ __forceinline__ T warpSum(T val) { for (int i = 0; i < getMSB(CUDA_WARP_SIZE); ++i) { val += WARP_SHFL_XOR(val, 1 << i, CUDA_WARP_SIZE); } return val; } struct InvStd { template <typename T> __device__ __forceinline__ T operator()(T var, double epsilon) const { T invstd = 0; if (var != static_cast<T>(0) || epsilon != static_cast<T>(0)) { invstd = static_cast<T>(1) / sqrt(var + epsilon); } return invstd; } }; struct Var { template <typename T> __device__ __forceinline__ T operator()(T var, double epsilon) const { return var; } }; __host__ void flexible_launch_configs(const int reduction, const int stride, dim3 &block, dim3 &grid, const bool coop_flag = false) { int block_x = std::min(lastPow2(stride), SYNC_BN_OPTIMAL_TILE_W); int block_y = std::min( lastPow2(NBLA_CEIL_INT_DIV(reduction, SYNC_BN_ELEMENTS_PER_THREAD)), SYNC_BN_MAX_BLOCK_SIZE / block_x); if (block_x * block_y != SYNC_BN_MAX_BLOCK_SIZE) { block_x = std::min(lastPow2(stride), SYNC_BN_MAX_BLOCK_SIZE / block_y); } int grid_x = NBLA_CEIL_INT_DIV(stride, block_x); int grid_y = std::min( NBLA_CEIL_INT_DIV(reduction, block_y * SYNC_BN_ELEMENTS_PER_THREAD), SYNC_BN_MAX_H_BLOCK); if (coop_flag) { // it's not worth having a grid reduction if the reduction dimension is not // big enough grid_y = grid_y < 8 ? 1 : grid_y; } block.x = block_x; block.y = block_y; block.z = 1; grid.x = grid_x; grid.y = grid_y; grid.z = 1; } template <typename VarTransform, typename input_scalar_t, typename stat_accscalar_t, typename index_t> __global__ void batch_norm_collect_statistics_kernel( const input_scalar_t *input, const stat_accscalar_t epsilon, stat_accscalar_t *save_mean, stat_accscalar_t *save_transformed_var, const Size_t size0, const Size_t size1, const Size_t size2) { __shared__ int shared_n[2 * 2 * CUDA_WARP_SIZE + CUDA_WARP_SIZE]; int plane = blockIdx.x; Size_t N = size0 * size2; int tid = threadIdx.x + threadIdx.y * blockDim.x; // Compute the mean and variance across (batch, x/y/z) // this uses the Welford (in the for loop)/parallel algorithm (to sum across // the block) // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_Online_algorithm // and the parallel algorithm on the same page. // We use two shuffles to reduce across the entire block. // https://devblogs.nvidia.com/faster-parallel-reductions-kepler/ has a // description. stat_accscalar_t *shared_avg_var = (stat_accscalar_t *)&shared_n[CUDA_WARP_SIZE]; // first the reductions each thread does separately stat_accscalar_t avg = 0; stat_accscalar_t var_n = 0; int n = 0; for (index_t batch = threadIdx.y; batch < size0; batch += blockDim.y) { // Unroll and prefetch for latency hiding optimization constexpr int B = 4; stat_accscalar_t reg[B]; for (index_t x = threadIdx.x; x < size2; x += blockDim.x * B) { const int base_idx = (batch * size1 + plane) * size2 + x; if (x + blockDim.x * (B - 1) < size2) { // No need to consider boundary condition inside the loop. // Prefetch #pragma unroll for (int k = 0; k < B; k++) { const int idx = base_idx + blockDim.x * k; reg[k] = input[idx]; } // Calculate mean and variance #pragma unroll for (int k = 0; k < B; k++) { stat_accscalar_t d1 = reg[k] - avg; n++; avg += d1 / n; var_n += d1 * (reg[k] - avg); } } else { // Prefetch #pragma unroll for (int k = 0; k < B; k++) { const int idx = base_idx + blockDim.x * k; if (x + blockDim.x * k < size2) { reg[k] = input[idx]; } } // Calculate mean and variance #pragma unroll for (int k = 0; k < B; k++) { if (x + blockDim.x * k < size2) { stat_accscalar_t d1 = reg[k] - avg; n++; avg += d1 / n; var_n += d1 * (reg[k] - avg); } } } } } // first warpSum to get one value per thread to // one value per warp for (int i = 0; i < getMSB(CUDA_WARP_SIZE); ++i) { stat_accscalar_t o_avg = WARP_SHFL_XOR(avg, 1 << i, CUDA_WARP_SIZE); int o_n = WARP_SHFL_XOR(n, 1 << i, CUDA_WARP_SIZE); stat_accscalar_t factor = 1.0 / fmaxf(1.0, n + o_n); var_n += WARP_SHFL_XOR(var_n, 1 << i, CUDA_WARP_SIZE) + (avg - o_avg) * (avg - o_avg) * n * o_n * factor; avg = (n * avg + o_n * o_avg) * factor; n += o_n; } // this writes each warps item into shared memory // there are at most CUDA_WARP_SIZE items left because // there are at most CUDA_WARP_SIZE**2 threads at the beginning __syncthreads(); if (tid % CUDA_WARP_SIZE == 0) { shared_n[tid / CUDA_WARP_SIZE] = n; shared_avg_var[tid / CUDA_WARP_SIZE * 2] = avg; shared_avg_var[tid / CUDA_WARP_SIZE * 2 + 1] = var_n; } __syncthreads(); // now have a second warpSum to reduce the intermediate values // from shared memory to a single number. The very first // thread writes it to shared memory. if (tid < CUDA_WARP_SIZE) { n = (tid < blockDim.x * blockDim.y / CUDA_WARP_SIZE ? shared_n[tid] : 0); avg = (tid < blockDim.x * blockDim.y / CUDA_WARP_SIZE ? shared_avg_var[2 * tid] : stat_accscalar_t(0)); var_n = (tid < blockDim.x * blockDim.y / CUDA_WARP_SIZE ? shared_avg_var[2 * tid + 1] : stat_accscalar_t(0)); } for (int i = 0; i < getMSB(CUDA_WARP_SIZE); ++i) { stat_accscalar_t o_avg = WARP_SHFL_XOR(avg, 1 << i, CUDA_WARP_SIZE); int o_n = WARP_SHFL_XOR(n, 1 << i, CUDA_WARP_SIZE); stat_accscalar_t factor = 1.0 / fmaxf(1.0, n + o_n); var_n += WARP_SHFL_XOR(var_n, 1 << i, CUDA_WARP_SIZE) + (avg - o_avg) * (avg - o_avg) * n * o_n * factor; avg = (n * avg + o_n * o_avg) * factor; n += o_n; } // Save the mean, variance, and moving averages if (tid == 0) { if (save_mean != NULL) { save_mean[plane] = avg; } if (save_transformed_var != NULL) { save_transformed_var[plane] = VarTransform{}(var_n / N, epsilon); } } } template <typename T, typename C> __device__ __forceinline__ void welford_merge_element(C &count, T &mean, T &m2n, const C &count_new, const T &mean_new, const T &m2n_new) { T factor = T(1.0) / ::max(1, (count + count_new)); T delta0 = mean - mean_new; mean = (mean_new * count_new + mean * count) * factor; m2n += m2n_new + delta0 * delta0 * count_new * count * factor; count += count_new; } // merge mean/m2n among threadIdx.y within block template <typename T, typename C> __device__ __forceinline__ void welford_merge_block_vertical(C &count, T &mean, T &m2n, C *shmem_count, T *shmem_mean, T *shmem_m2n) { // write to shared memory auto address_base = threadIdx.x + threadIdx.y * blockDim.x; #pragma unroll for (int offset = blockDim.y / 2; offset > 0; offset >>= 1) { if (threadIdx.y < offset * 2) { shmem_mean[address_base] = mean; shmem_m2n[address_base] = m2n; shmem_count[address_base] = count; } __syncthreads(); if (threadIdx.y < offset && threadIdx.y + offset < blockDim.y) { auto address = address_base + offset * blockDim.x; // read shared memory back to register for reduction auto count_new = shmem_count[address]; auto mean_new = shmem_mean[address]; auto m2n_new = shmem_m2n[address]; welford_merge_element(count, mean, m2n, count_new, mean_new, m2n_new); } } } // welford kernel for c last tensor calculating // mean/biased_variance/unbiased_variance // original apex name: welford_kernel_c_last template <typename VarTransform, typename scalar_t, typename accscalar_t, typename index_t, int PARALLEL_LOADS> __global__ void batch_norm_collect_statistics_channels_last_kernel( const scalar_t *__restrict__ input, accscalar_t *__restrict__ out_mean, accscalar_t *__restrict__ out_invstd, volatile accscalar_t *staging_data, int *semaphores, const int reduction_size, const int stride, accscalar_t epsilon) { // hide latency with concurrency accscalar_t x_mean[PARALLEL_LOADS]; accscalar_t m_2_n[PARALLEL_LOADS]; int count[PARALLEL_LOADS]; #pragma unroll for (int i = 0; i < PARALLEL_LOADS; i++) { x_mean[i] = accscalar_t(0); m_2_n[i] = accscalar_t(0); count[i] = accscalar_t(0); } // tensor dimension (m,c) // loop along m dimension index_t inner_loop_stride = blockDim.y * gridDim.y; // offset along m dimension index_t m_offset = blockIdx.y * blockDim.y + threadIdx.y; index_t c_offset = blockIdx.x * blockDim.x + threadIdx.x; index_t loop_count = 1 + (reduction_size - 1) / (inner_loop_stride * PARALLEL_LOADS); index_t address_base = m_offset * stride + c_offset; index_t address_increment = inner_loop_stride * stride; for (int i = 0; i < loop_count; i++) { accscalar_t x_math[PARALLEL_LOADS]; accscalar_t x_count_inv[PARALLEL_LOADS]; accscalar_t is_valid[PARALLEL_LOADS]; // load multiple data in #pragma unroll for (int j = 0; j < PARALLEL_LOADS; j++) { if (c_offset < stride && m_offset < reduction_size) { x_math[j] = input[address_base]; count[j]++; x_count_inv[j] = accscalar_t(1) / count[j]; is_valid[j] = accscalar_t(1); } else { x_math[j] = accscalar_t(0); x_count_inv[j] = accscalar_t(0); is_valid[j] = accscalar_t(0); } m_offset += inner_loop_stride; address_base += address_increment; } // calculate mean/m2n with welford #pragma unroll for (int j = 0; j < PARALLEL_LOADS; j++) { accscalar_t delta0 = x_math[j] - x_mean[j]; x_mean[j] += delta0 * x_count_inv[j]; accscalar_t delta1 = x_math[j] - x_mean[j]; m_2_n[j] += delta0 * delta1 * is_valid[j]; } } // thread reduction to accumulate mean/m_2_n/count between PARALLEL_LOADS #pragma unroll for (int j = 1; j < PARALLEL_LOADS; j++) { welford_merge_element(count[0], x_mean[0], m_2_n[0], count[j], x_mean[j], m_2_n[j]); } // release x_mean / m_2_n auto mean_th = x_mean[0]; auto m2_th = m_2_n[0]; auto count_th = count[0]; // block-wise reduction with shared memory (since reduction cannot be done // within a warp) static __shared__ accscalar_t shmem_mean[SYNC_BN_MAX_BLOCK_SIZE]; static __shared__ accscalar_t shmem_m2n[SYNC_BN_MAX_BLOCK_SIZE]; static __shared__ int shmem_count[SYNC_BN_MAX_BLOCK_SIZE]; welford_merge_block_vertical(count_th, mean_th, m2_th, shmem_count, shmem_mean, shmem_m2n); if (gridDim.y > 1) { volatile accscalar_t *staging_mean = staging_data; volatile accscalar_t *staging_m2n = &staging_data[stride * gridDim.y]; volatile int *staging_count = reinterpret_cast<volatile int *>(&staging_m2n[stride * gridDim.y]); address_base = c_offset + blockIdx.y * stride; // write data to staging_data; if (threadIdx.y == 0 && c_offset < stride) { staging_mean[address_base] = mean_th; staging_m2n[address_base] = m2_th; staging_count[address_base] = count_th; } __threadfence(); __syncthreads(); // ensuring writes to staging_ is visible to all blocks __shared__ bool is_last_block_done; // mark block done if (threadIdx.x == 0 && threadIdx.y == 0) { int old = atomicAdd(&semaphores[blockIdx.x], 1); is_last_block_done = (old == (gridDim.y - 1)); } __syncthreads(); // check that all data is now available in global memory if (is_last_block_done) { count_th = 0; mean_th = accscalar_t(0.0); m2_th = accscalar_t(0.0); for (int y = threadIdx.y; y < gridDim.y; y += blockDim.y) { address_base = c_offset + y * stride; int count_new = c_offset < stride ? staging_count[address_base] : 0; accscalar_t mean_new = c_offset < stride ? staging_mean[address_base] : accscalar_t(0.0); accscalar_t m2n_new = c_offset < stride ? staging_m2n[address_base] : accscalar_t(0.0); welford_merge_element(count_th, mean_th, m2_th, count_new, mean_new, m2n_new); } welford_merge_block_vertical(count_th, mean_th, m2_th, shmem_count, shmem_mean, shmem_m2n); if (threadIdx.y == 0 && c_offset < stride) { out_mean[c_offset] = static_cast<accscalar_t>(mean_th); out_invstd[c_offset] = VarTransform{}(m2_th / count_th, epsilon); } } } else { if (blockIdx.y == 0 && threadIdx.y == 0 && c_offset < stride) { out_mean[c_offset] = static_cast<accscalar_t>(mean_th); out_invstd[c_offset] = VarTransform{}(m2_th / count_th, epsilon); } } } template <typename scalar_t, typename accscalar_t, typename index_t> __global__ void batch_norm_reduce_statistics_kernel( const accscalar_t *vec_mean, const accscalar_t *vec_invstd, accscalar_t *mean, accscalar_t *var, scalar_t *running_mean, scalar_t *running_var, const accscalar_t epsilon, const accscalar_t decay_rate, const scalar_t *counts, const int feature_size, const int world_size) { int bid = blockIdx.x; int tid = threadIdx.x; // first the reductions each thread does separately for (int i = bid * blockDim.x + tid; i < feature_size; i += gridDim.x * blockDim.x) { accscalar_t avg = 0; accscalar_t var_n = 0; index_t n = 0; for (int j = 0; j < world_size; j++) { scalar_t count = counts[j]; accscalar_t m = vec_mean[j * feature_size + i]; accscalar_t v = accscalar_t(1.0) / (vec_invstd[j * feature_size + i]); v = (v * v - epsilon) * count; accscalar_t factor = 1.0 / ((accscalar_t)n + count); var_n += v + (avg - m) * (avg - m) * n * count * factor; avg = n * factor * avg + count * factor * m; n += (index_t)count; } mean[i] = avg; var[i] = var_n / n; if (running_mean != NULL) { running_mean[i] = static_cast<scalar_t>(decay_rate * running_mean[i] + (1.0 - decay_rate) * avg); } accscalar_t unbiasedVar = var_n / (n - 1); if (running_var != NULL) { running_var[i] = static_cast<scalar_t>(decay_rate * running_var[i] + (1.0 - decay_rate) * unbiasedVar); } } } // template <typename input_scalar_t, typename stat_scalar_t, typename // stat_accscalar_t, bool train, typename index_t> template <typename input_scalar_t, typename stat_scalar_t, typename stat_accscalar_t, typename index_t> __global__ void batch_norm_transform_input_kernel( const input_scalar_t *input, input_scalar_t *output, const stat_accscalar_t *mean_, const stat_accscalar_t *var, const stat_scalar_t *weight, const stat_scalar_t *bias, const stat_accscalar_t epsilon, const int size0, const int size1, const int size2) { index_t plane = blockIdx.x; if (plane >= size1) { return; } stat_accscalar_t gamma = weight ? static_cast<stat_accscalar_t>(weight[plane]) : static_cast<stat_accscalar_t>(1); stat_accscalar_t beta = bias ? static_cast<stat_accscalar_t>(bias[plane]) : static_cast<stat_accscalar_t>(0); stat_accscalar_t mean = static_cast<stat_accscalar_t>(mean_[plane]); stat_accscalar_t invstd = static_cast<stat_accscalar_t>(1) / sqrt(static_cast<stat_accscalar_t>(var[plane]) + epsilon); index_t bs = size0; index_t fs = size2; index_t bstep = blockDim.y * gridDim.y; for (index_t batch = threadIdx.y + blockIdx.y * blockDim.y; batch < bs; batch += bstep) { auto o = &output[(batch * size1 + plane) * size2]; auto i = &input[(batch * size1 + plane) * size2]; for (index_t feature = threadIdx.x; feature < fs; feature += blockDim.x) { o[feature] = static_cast<input_scalar_t>( gamma * (i[feature] - mean) * invstd + beta); } } } // elementwise BN kernel // original apex name: batchnorm_forward_c_last_kernel template <typename scalar_t, typename accscalar_t, typename layerscalar_t, typename index_t, int PARALLEL_LOADS> __global__ void batch_norm_transform_input_channels_last_kernel( const scalar_t *__restrict__ input, const accscalar_t *__restrict__ mean, // const accscalar_t* __restrict__ inv_std, const accscalar_t *__restrict__ var, const layerscalar_t *__restrict__ weight, // sacle or gamma const layerscalar_t *__restrict__ shift, // bias or beta scalar_t *__restrict__ out, const accscalar_t epsilon, const index_t reduction_size, const index_t stride) { // tensor dimension (m,c) // loop along m dimension index_t inner_loop_stride = blockDim.y * gridDim.y; // offset along m dimension index_t m_offset = blockIdx.y * blockDim.y + threadIdx.y; index_t c_offset = blockIdx.x * blockDim.x + threadIdx.x; if (c_offset >= stride || m_offset >= reduction_size) { return; } auto m_c = mean[c_offset]; auto inv_std_c = static_cast<accscalar_t>(1) / sqrt(var[c_offset] + epsilon); auto w_c = weight == nullptr ? accscalar_t(1.0) : static_cast<accscalar_t>(weight[c_offset]); auto s_c = shift == nullptr ? accscalar_t(0.0) : static_cast<accscalar_t>(shift[c_offset]); index_t loop_count = 1 + (reduction_size - 1) / (inner_loop_stride * PARALLEL_LOADS); index_t address_base = m_offset * stride + c_offset; index_t address_increment = inner_loop_stride * stride; for (int i = 0; i < loop_count; i++) { #pragma unroll for (int j = 0; j < PARALLEL_LOADS; j++) { if (c_offset < stride && m_offset < reduction_size) { auto tmp = w_c * (static_cast<accscalar_t>(input[address_base]) - m_c) * inv_std_c + s_c; out[address_base] = static_cast<scalar_t>(tmp); } m_offset += inner_loop_stride; address_base += address_increment; } } } template <typename scalar_t, typename accscalar_t> struct GradOp { __device__ GradOp(accscalar_t m, const scalar_t *i, const scalar_t *g) : mean(m), input(i), grad_output(g) {} __device__ __forceinline__ void operator()(accscalar_t *dy, accscalar_t *dy_xmu, int idx) { accscalar_t g = grad_output[idx]; accscalar_t c = static_cast<accscalar_t>(input[idx]) - mean; *dy = g; *dy_xmu = g * c; } const accscalar_t mean; const scalar_t *input; const scalar_t *grad_output; }; // Sum across (batch, x/y/z) applying Op() pointwise // this works by first having each thread sum it's part // of the data. Then there is a double-shuffling reduction. // First each warp (of CUDA_WARP_SIZE threads) uses warpSum to reduce its // data to the "warp leader", who writes its value into shared memory. // Then a single warp reads the remaining (at most CUDA_WARP_SIZE) items // and reduces them using another warpSum. // The implicit assumption is that there are no more // than CUDA_WARP_SIZE**2 threads. template <typename Op, typename scalar_t, typename accscalar_t, typename index_t> __device__ void reduce(Op op, scalar_t *sum_dy_o, accscalar_t *sum_dy_xmu_o, const index_t plane, const Size_t size0, const Size_t size1, const Size_t size2) { // first the reductions each thread does separately accscalar_t sum_dy = static_cast<accscalar_t>(0); accscalar_t sum_dy_xmu = static_cast<accscalar_t>(0); for (index_t batch = threadIdx.y; batch < size0; batch += blockDim.y) { // Prefetch and unrolling for latency hiding optimization. constexpr int B = 8; accscalar_t reg_dy[B]; accscalar_t reg_dy_xmu[B]; for (index_t x = threadIdx.x; x < size2; x += blockDim.x * B) { const index_t base_idx = (batch * size1 + plane) * size2 + x; // Prefetch #pragma unroll for (int k = 0; k < B; k++) { const index_t idx = base_idx + blockDim.x * k; if (x + blockDim.x * k < size2) { op(&reg_dy[k], &reg_dy_xmu[k], idx); } } // Calculation #pragma unroll for (int k = 0; k < B; k++) { if (x + blockDim.x * k < size2) { sum_dy += reg_dy[k]; sum_dy_xmu += reg_dy_xmu[k]; } } } } // first warpSum to get one value per thread to // one value per warp sum_dy = warpSum(sum_dy); sum_dy_xmu = warpSum(sum_dy_xmu); // this writes each warps item into shared memory // there are at most CUDA_WARP_SIZE items left because // there are at most CUDA_WARP_SIZE**2 threads at the beginning __shared__ accscalar_t shared_dy[CUDA_WARP_SIZE]; __shared__ accscalar_t shared_dy_xmu[CUDA_WARP_SIZE]; __syncthreads(); int tid = threadIdx.x + threadIdx.y * blockDim.x; if (tid % CUDA_WARP_SIZE == 0) { shared_dy[tid / CUDA_WARP_SIZE] = sum_dy; shared_dy_xmu[tid / CUDA_WARP_SIZE] = sum_dy_xmu; } if (tid >= blockDim.x * blockDim.y / CUDA_WARP_SIZE && tid < CUDA_WARP_SIZE) { // zero out the other entries in shared shared_dy[tid] = (scalar_t)0; shared_dy_xmu[tid] = (scalar_t)0; } __syncthreads(); // now have a second warpSum to reduce the intermediate values // from shared memory to a single number. The very first // thread writes it to shared memory. if (tid / CUDA_WARP_SIZE == 0) { sum_dy = warpSum(shared_dy[tid]); sum_dy_xmu = warpSum(shared_dy_xmu[tid]); if (tid == 0) { shared_dy[0] = sum_dy; shared_dy_xmu[0] = sum_dy_xmu; } } __syncthreads(); // Everyone picks it up, should be broadcast into the whole grad_input *sum_dy_o = shared_dy[0]; *sum_dy_xmu_o = shared_dy_xmu[0]; } template <typename input_scalar_t, typename stat_scalar_t, typename stat_accscalar_t, typename index_t> __global__ void batch_norm_backward_reduce_kernel( const input_scalar_t *input, const input_scalar_t *grad_output, const stat_accscalar_t *mean, const stat_accscalar_t *var, stat_accscalar_t *sum_dy_o, stat_accscalar_t *sum_dy_xmu_o, stat_scalar_t *grad_weight, stat_scalar_t *grad_bias, const stat_accscalar_t epsilon, const Size_t size0, const Size_t size1, const Size_t size2) { index_t plane = blockIdx.x; stat_accscalar_t r_mean = mean[plane]; stat_accscalar_t factor = static_cast<stat_accscalar_t>(1) / sqrt(var[plane] + epsilon); GradOp<input_scalar_t, stat_accscalar_t> g(r_mean, input, grad_output); stat_scalar_t sum_dy; stat_accscalar_t sum_dy_xmu; reduce(g, &sum_dy, &sum_dy_xmu, plane, size0, size1, size2); if (threadIdx.x == 0) { if (grad_weight) { grad_weight[plane] = static_cast<stat_scalar_t>(sum_dy_xmu * factor); } if (grad_bias) { grad_bias[plane] = static_cast<stat_scalar_t>(sum_dy); } if (sum_dy_o) { sum_dy_o[plane] = static_cast<stat_accscalar_t>(sum_dy); } if (sum_dy_xmu_o) { sum_dy_xmu_o[plane] = static_cast<stat_accscalar_t>(sum_dy_xmu); } } } template <typename T> __device__ __forceinline__ void merge_block_vertical_backward(T &sum_dy, T &sum_dy_xmu, T *shmem_sum_dy, T *shmem_sum_dy_xmu) { // write to shared memory auto address_base = threadIdx.x + threadIdx.y * blockDim.x; #pragma unroll for (int offset = blockDim.y / 2; offset > 0; offset >>= 1) { if (threadIdx.y < offset * 2) { shmem_sum_dy[address_base] = sum_dy; shmem_sum_dy_xmu[address_base] = sum_dy_xmu; } __syncthreads(); if (threadIdx.y < offset && threadIdx.y + offset < blockDim.y) { auto address = address_base + offset * blockDim.x; sum_dy += shmem_sum_dy[address]; sum_dy_xmu += shmem_sum_dy_xmu[address]; } } } // batchnorm backward kernel for c last tensor // original apex name: reduce_bn_c_last_kernel template <int PARALLEL_LOADS, typename scalar_t, typename accscalar_t, typename layerscalar_t, typename index_t> __global__ void batch_norm_backward_reduce_channels_last_kernel( const scalar_t *__restrict__ input, const scalar_t *__restrict__ grad_output, const accscalar_t *__restrict__ mean, const accscalar_t *__restrict__ var, accscalar_t *__restrict__ sum_dy_o, accscalar_t *__restrict__ sum_dy_xmu_o, layerscalar_t *__restrict__ grad_weight, layerscalar_t *__restrict__ grad_bias, volatile accscalar_t *staging_data, int *semaphores, const index_t reduction_size, const index_t stride, const accscalar_t epsilon) { // hide latency with concurrency accscalar_t sum_dy[PARALLEL_LOADS]; accscalar_t sum_dy_xmu[PARALLEL_LOADS]; #pragma unroll for (int i = 0; i < PARALLEL_LOADS; i++) { sum_dy[i] = accscalar_t(0); sum_dy_xmu[i] = accscalar_t(0); } // tensor dimension (m,c) // loop along m dimension index_t inner_loop_stride = blockDim.y * gridDim.y; // offset along m dimension index_t m_offset = blockIdx.y * blockDim.y + threadIdx.y; index_t c_offset = blockIdx.x * blockDim.x + threadIdx.x; if (c_offset >= stride || m_offset >= reduction_size) { return; } index_t loop_count = 1 + (reduction_size - 1) / (inner_loop_stride * PARALLEL_LOADS); index_t address_base = m_offset * stride + c_offset; index_t address_increment = inner_loop_stride * stride; auto r_mean = mean[c_offset]; // auto factor = inv_std[c_offset]; auto factor = 1.0 / sqrt(var[c_offset] + epsilon); for (int i = 0; i < loop_count; i++) { accscalar_t x_input[PARALLEL_LOADS]; accscalar_t x_grad_output[PARALLEL_LOADS]; // load multiple data in #pragma unroll for (int j = 0; j < PARALLEL_LOADS; j++) { if (c_offset < stride && m_offset < reduction_size) { x_input[j] = input[address_base]; x_grad_output[j] = grad_output[address_base]; } else { x_input[j] = accscalar_t(0); x_grad_output[j] = accscalar_t(0); } m_offset += inner_loop_stride; address_base += address_increment; } // calculate sum_dy / sum_dy_xmu #pragma unroll for (int j = 0; j < PARALLEL_LOADS; j++) { sum_dy[j] += x_grad_output[j]; sum_dy_xmu[j] += x_grad_output[j] * (x_input[j] - r_mean); } } // thread reduction to accumulate sum_dy / sum_dy_xmu between PARALLEL_LOADS #pragma unroll for (int j = 1; j < PARALLEL_LOADS; j++) { sum_dy[0] += sum_dy[j]; sum_dy_xmu[0] += sum_dy_xmu[j]; } // release array of registers auto sum_dy_th = sum_dy[0]; auto sum_dy_xmu_th = sum_dy_xmu[0]; // block-wise reduction with shared memory (since reduction cannot be done // within a warp) static __shared__ accscalar_t shmem_sum_dy[SYNC_BN_MAX_BLOCK_SIZE]; static __shared__ accscalar_t shmem_sum_dy_xmu[SYNC_BN_MAX_BLOCK_SIZE]; merge_block_vertical_backward(sum_dy_th, sum_dy_xmu_th, shmem_sum_dy, shmem_sum_dy_xmu); if (gridDim.y > 1) { volatile accscalar_t *staging_sum_dy = staging_data; volatile accscalar_t *staging_sum_dy_xmu = &staging_data[stride * gridDim.y]; address_base = c_offset + blockIdx.y * stride; // write data to staging_data; if (threadIdx.y == 0 && c_offset < stride) { staging_sum_dy[address_base] = sum_dy_th; staging_sum_dy_xmu[address_base] = sum_dy_xmu_th; } __threadfence(); __syncthreads(); // ensuring writes to staging_ is visible to all blocks __shared__ bool is_last_block_done; // mark block done if (threadIdx.x == 0 && threadIdx.y == 0) { int old = atomicAdd(&semaphores[blockIdx.x], 1); is_last_block_done = (old == (gridDim.y - 1)); } __syncthreads(); // check that all data is now available in global memory if (is_last_block_done) { sum_dy_th = accscalar_t(0.0); sum_dy_xmu_th = accscalar_t(0.0); for (int y = threadIdx.y; y < gridDim.y; y += blockDim.y) { address_base = c_offset + y * stride; sum_dy_th += (c_offset < stride ? staging_sum_dy[address_base] : accscalar_t(0.0)); sum_dy_xmu_th += (c_offset < stride ? staging_sum_dy_xmu[address_base] : accscalar_t(0.0)); } merge_block_vertical_backward(sum_dy_th, sum_dy_xmu_th, shmem_sum_dy, shmem_sum_dy_xmu); if (threadIdx.y == 0 && c_offset < stride) { if (grad_bias != nullptr) { grad_bias[c_offset] = static_cast<layerscalar_t>(sum_dy_th); } if (grad_weight != nullptr) { grad_weight[c_offset] = static_cast<layerscalar_t>(sum_dy_xmu_th * factor); } sum_dy_o[c_offset] = sum_dy_th; sum_dy_xmu_o[c_offset] = sum_dy_xmu_th; } } } else { if (blockIdx.y == 0 && threadIdx.y == 0 && c_offset < stride) { if (grad_bias != nullptr) { grad_bias[c_offset] = static_cast<layerscalar_t>(sum_dy_th); } if (grad_weight != nullptr) { grad_weight[c_offset] = static_cast<layerscalar_t>(sum_dy_xmu_th * factor); } sum_dy_o[c_offset] = sum_dy_th; sum_dy_xmu_o[c_offset] = sum_dy_xmu_th; } } } template <bool accum, typename input_scalar_t, typename stat_scalar_t, typename stat_accscalar_t, typename index_t> __global__ void batch_norm_backward_elemt_kernel( const input_scalar_t *input, const input_scalar_t *grad_output, const stat_accscalar_t *mean, const stat_accscalar_t *var, const stat_accscalar_t *dmean, const stat_accscalar_t *dvar, const stat_scalar_t *weight, const stat_accscalar_t *sum_dy, const stat_accscalar_t *sum_dy_xmu, input_scalar_t *grad_input, const stat_accscalar_t epsilon, const int *__restrict__ numel, const int world_size, const index_t size0, const index_t size1, const index_t size2) { index_t plane = blockIdx.x; if (plane >= size1) { return; } // Inverted total reduction size. int64_t total_numel = 0; for (int i = 0; i < world_size; i++) { total_numel += numel[i]; } const stat_accscalar_t norm_fct = static_cast<stat_accscalar_t>(1) / static_cast<stat_accscalar_t>(total_numel); // weight, mean and invstd const stat_accscalar_t w_c = weight[plane]; const stat_accscalar_t m_c = mean[plane]; const stat_accscalar_t invstd_c = 1.0 / sqrt(var[plane] + epsilon); // dmean and dvar stat_scalar_t dv = w_c * sum_dy_xmu[plane]; dv = dv * (-0.5) * pow(invstd_c, 3) + (dvar ? dvar[plane] : 0); stat_scalar_t dm = w_c * sum_dy[plane]; dm = dm * -invstd_c + (dmean ? dmean[plane] : 0); // Pre-calculation of factors for optimization. const stat_scalar_t factor1 = w_c * invstd_c; const stat_scalar_t factor2 = dv * 2 * norm_fct; const stat_scalar_t factor3 = (dm - dv * 2 * m_c) * norm_fct; index_t bs = size0; index_t fs = size2; index_t bstep = blockDim.y * gridDim.y; for (index_t batch = threadIdx.y + blockIdx.y * blockDim.y; batch < bs; batch += bstep) { const int idx_offset = (batch * size1 + plane) * size2; auto *g_i = &grad_input[idx_offset]; auto *g_o = &grad_output[idx_offset]; auto *i = &input[idx_offset]; for (index_t feature = threadIdx.x; feature < fs; feature += blockDim.x) { const stat_scalar_t grad = g_o[feature] * factor1 + i[feature] * factor2 + factor3; if (accum) { g_i[feature] += grad; } else { g_i[feature] = grad; } } } } // elementwise BN kernel // original apex name: batchnorm_backward_c_last_kernel template <int PARALLEL_LOADS, bool accum, typename scalar_t, typename accscalar_t, typename layerscalar_t, typename index_t> __global__ void batch_norm_backward_elemt_channels_last_kernel( const scalar_t *__restrict__ grad_output, const scalar_t *__restrict__ input, const accscalar_t *__restrict__ mean, // const accscalar_t* __restrict__ inv_std, const accscalar_t *__restrict__ var, const accscalar_t *__restrict__ dmean, const accscalar_t *__restrict__ dvar, const layerscalar_t *__restrict__ weight, const accscalar_t *__restrict__ sum_dy, const accscalar_t *__restrict__ sum_dy_xmu, const int *__restrict__ numel, scalar_t *__restrict__ grad_input, const int world_size, const index_t reduction_size, const index_t stride, const accscalar_t epsilon) { // tensor dimension (m,c) // loop along m dimension int inner_loop_stride = blockDim.y * gridDim.y; // offset along m dimension int m_offset = blockIdx.y * blockDim.y + threadIdx.y; int c_offset = blockIdx.x * blockDim.x + threadIdx.x; if (c_offset >= stride || m_offset >= reduction_size) { return; } // Inverted total reduction size. int64_t total_numel = 0; for (int i = 0; i < world_size; i++) { total_numel += numel[i]; } auto norm_fct = static_cast<accscalar_t>(1) / static_cast<accscalar_t>(total_numel); // weight, mean and invstd const accscalar_t w_c = weight[c_offset]; const accscalar_t m_c = mean[c_offset]; const accscalar_t invstd_c = 1.0 / sqrt(var[c_offset] + epsilon); // dmean and dvar scalar_t dv = w_c * sum_dy_xmu[c_offset]; dv = dv * (-0.5) * pow(invstd_c, 3) + (dvar ? dvar[c_offset] : 0); scalar_t dm = w_c * sum_dy[c_offset]; dm = dm * -invstd_c + (dmean ? dmean[c_offset] : 0); // Pre-calculation of factors for optimization. const scalar_t factor1 = w_c * invstd_c; const scalar_t factor2 = dv * 2 * norm_fct; const scalar_t factor3 = (dm - dv * 2 * m_c) * norm_fct; index_t loop_count = 1 + (reduction_size - 1) / (inner_loop_stride * PARALLEL_LOADS); index_t address_base = m_offset * stride + c_offset; index_t address_increment = inner_loop_stride * stride; for (int i = 0; i < loop_count; i++) { #pragma unroll for (int j = 0; j < PARALLEL_LOADS; j++) { if (c_offset < stride && m_offset < reduction_size) { const scalar_t grad = grad_output[address_base] * factor1 + input[address_base] * factor2 + factor3; if (accum) { grad_input[address_base] += grad; } else { grad_input[address_base] = grad; } } m_offset += inner_loop_stride; address_base += address_increment; } } } }
the_stack
#include <cmath> #include <cub/cub.cuh> #include <memory> namespace dietgpu { template <int Threads> __device__ void histogramSingle( const ANSDecodedT* __restrict__ in, uint32_t size, uint32_t* __restrict__ out) { constexpr int kWarps = Threads / kWarpSize; static_assert(Threads == kNumSymbols, ""); // +1 in order to force very common symbols that could overlap into different // banks? __shared__ uint32_t buckets[kWarps][kNumSymbols + 1]; int warpId = threadIdx.x / kWarpSize; #pragma unroll for (int i = 0; i < kWarps; ++i) { buckets[i][threadIdx.x] = 0; } __syncthreads(); uint32_t* warpBucket = buckets[warpId]; // If the size of batch is smaller than the increment for alignment, we only // handle the batch auto roundUp4 = min(size, getAlignmentRoundUp<sizeof(uint4)>(in)); // The size of data that remains after alignment auto remaining = size - roundUp4; // The size of data (in uint4 words) that we can process with alignment uint32_t numU4 = divDown(remaining, sizeof(uint4)); auto inAligned = in + roundUp4; auto inAligned4 = (const uint4*)inAligned; // Handle the non-aligned portion that we have to load as single words, if any if (blockIdx.x == 0 && threadIdx.x < roundUp4) { static_assert(sizeof(uint4) <= Threads, ""); atomicAdd(&warpBucket[in[threadIdx.x]], 1); } // Handle the portion that is aligned and uint4 vectorizable // 37.60 us / 80.76% gmem / 51.29% smem for uint4 on A100 for (uint32_t i = blockIdx.x * Threads + threadIdx.x; i < numU4; i += gridDim.x * Threads) { uint4 v = inAligned4[i]; { uint32_t x = v.x; atomicAdd(&warpBucket[x & 0xff], 1); x >>= 8; atomicAdd(&warpBucket[x & 0xff], 1); x >>= 8; atomicAdd(&warpBucket[x & 0xff], 1); x >>= 8; atomicAdd(&warpBucket[x], 1); } { uint32_t y = v.y; atomicAdd(&warpBucket[y & 0xff], 1); y >>= 8; atomicAdd(&warpBucket[y & 0xff], 1); y >>= 8; atomicAdd(&warpBucket[y & 0xff], 1); y >>= 8; atomicAdd(&warpBucket[y], 1); } { uint32_t z = v.z; atomicAdd(&warpBucket[z & 0xff], 1); z >>= 8; atomicAdd(&warpBucket[z & 0xff], 1); z >>= 8; atomicAdd(&warpBucket[z & 0xff], 1); z >>= 8; atomicAdd(&warpBucket[z], 1); } { uint32_t w = v.w; atomicAdd(&warpBucket[w & 0xff], 1); w >>= 8; atomicAdd(&warpBucket[w & 0xff], 1); w >>= 8; atomicAdd(&warpBucket[w & 0xff], 1); w >>= 8; atomicAdd(&warpBucket[w], 1); } } if (blockIdx.x == 0) { // Handle the remainder portion that doesn't comprise full words int i = numU4 * sizeof(uint4) + threadIdx.x; if (i < remaining) { atomicAdd(&warpBucket[inAligned[i]], 1); } } __syncthreads(); uint32_t sum = buckets[0][threadIdx.x]; #pragma unroll for (int j = 1; j < kWarps; ++j) { sum += buckets[j][threadIdx.x]; } // The count for the thread's bucket could be 0 if (sum) { atomicAdd(&out[threadIdx.x], sum); } } template <typename InProvider, int Threads> __global__ void histogramBatch(InProvider in, uint32_t* out) { int batch = blockIdx.y; out += batch * kNumSymbols; histogramSingle<Threads>( (const ANSDecodedT*)in.getBatchStart(batch), in.getBatchSize(batch), out); } // sum that allows passing in smem for usage, so as to avoid a trailing // syncthreads and associated latency template <int Threads> __device__ inline int blockSum(int warpId, int laneId, int valForSum, int* smem) { static_assert(isEvenDivisor(Threads, kWarpSize), ""); constexpr int kWarps = Threads / kWarpSize; auto allSum = warpReduceAllSum(valForSum); if (laneId == 0) { smem[warpId] = allSum; } __syncthreads(); if (warpId == 0) { int v = laneId < kWarps ? smem[laneId] : 0; v = warpReduceAllSum(v); if (laneId == 0) { smem[0] = v; } } __syncthreads(); // trailing syncthreads is elsewhere return smem[0]; } // Function that allows normalization of symbol probabilities with a varying // (statically known) number of threads, to allow for kernel fusion as needed // Stand-alone normalization will use Threads == kNumSymbols (256) template <int Threads> __device__ void normalizeProbabilitiesFromHistogram( // Size 256 histogram in gmem const uint32_t* __restrict__ counts, uint32_t totalNum, int probBits, uint4* __restrict__ table) { static_assert( kNumSymbols == Threads || isEvenDivisor(kNumSymbols, uint32_t(Threads)), ""); constexpr int kNumSymPerThread = kNumSymbols == Threads ? 1 : (kNumSymbols / Threads); // There's nothing to do if the input array in the batch was of zero size if (totalNum == 0) { return; } constexpr int kWarps = Threads / kWarpSize; uint32_t kProbWeight = 1 << probBits; int tid = threadIdx.x; int warpId = tid / kWarpSize; int laneId = getLaneId(); // Load the current count and compute the min/max non-zero values, then // perform an approximate quantization uint32_t qProb[kNumSymPerThread]; int qProbSum = 0; #pragma unroll for (int i = 0; i < kNumSymPerThread; ++i) { int curSym = i * Threads + tid; uint32_t count = counts[curSym]; // Rough initial quantization qProb[i] = kProbWeight * ((float)count / (float)totalNum); // All weights for symbols present must be > 0 qProb[i] = (count > 0 && qProb[i] == 0) ? 1 : qProb[i]; qProbSum += qProb[i]; } // Sum qProbSym across all threads __shared__ int smemSum[kWarps]; qProbSum = blockSum<Threads>(warpId, laneId, qProbSum, smemSum); // In order to use radix sorting, and also in order to only sort a single // word, pack both the weight and index into a single integer uint32_t sortedPair[kNumSymPerThread]; #pragma unroll for (int i = 0; i < kNumSymPerThread; ++i) { int curSym = i * Threads + tid; sortedPair[i] = (qProb[i] << 16) | curSym; } // The sort assumes a blocked arrangement as input, which we don't have, but // this doesn't matter as we only care about the arrangement post-sort using Sort = cub::BlockRadixSort<uint32_t, Threads, kNumSymPerThread>; __shared__ typename Sort::TempStorage smemSort; Sort(smemSort).SortDescending(sortedPair); // The (prob, symbol) pair that each thread is considered to // hold is the following: uint32_t tidSymbol[kNumSymPerThread]; // Recover the values #pragma unroll for (int i = 0; i < kNumSymPerThread; ++i) { tidSymbol[i] = sortedPair[i] & 0xffffU; qProb[i] = sortedPair[i] >> 16; } // How far below (positive) or above (negative) our current first-pass // quantization is from our target sum 2^probBits int diff = (int)kProbWeight - (int)qProbSum; if (diff > 0) { // We are below our total sum target; add 1 to largest values // FIXME: use div/mod to avoid iterations while (diff > 0) { int iterToApply = diff < kNumSymbols ? diff : kNumSymbols; #pragma unroll for (int i = 0; i < kNumSymPerThread; ++i) { int curSym = tidSymbol[i]; if (curSym < iterToApply) { qProb[i] += 1; } } diff -= iterToApply; } } else if (diff < 0) { // We are above our total sum target; subtract 1 from the smallest values // that are > 1 (all symbols with a weight of 1 cannot go to zero as they // are assumed present in the input) diff = -diff; while (diff > 0) { // Need to determine the number of int qNumGt1s = 0; #pragma unroll for (int i = 0; i < kNumSymPerThread; ++i) { qNumGt1s += (int)(qProb[i] > 1); } // We need to determine the remaining number of >1 values // We reuse smemSum but there is a syncthreads in the sort above, and at // the end of the loop below qNumGt1s = blockSum<Threads>(warpId, laneId, qNumGt1s, smemSum); __syncthreads(); // FIXME: not needed? // subtract from smallest >1 values // This should be the index of the first 1 value // FIXME: use div/mod to avoid iterations int iterToApply = diff < qNumGt1s ? diff : qNumGt1s; assert(iterToApply > 0); int startIndex = qNumGt1s - iterToApply; #pragma unroll for (int i = 0; i < kNumSymPerThread; ++i) { // Post-sort, the data is in a blocked arrangement int curSym = tid * kNumSymPerThread + i; if (curSym >= startIndex && curSym < qNumGt1s) { qProb[i] -= 1; } } diff -= iterToApply; __syncthreads(); } } // Recover the pre-sort order __shared__ uint32_t smemPdf[kNumSymbols]; #pragma unroll for (int i = 0; i < kNumSymPerThread; ++i) { smemPdf[tidSymbol[i]] = qProb[i]; } __syncthreads(); // NOTE: we need to have a contiguous blocked arrangement for cub::BlockScan // when kNumSymPerThread > 1, so the order is now tid * kNumSymPerThread + reg uint32_t symPdf[kNumSymPerThread]; #pragma unroll for (int i = 0; i < kNumSymPerThread; ++i) { int curSym = tid * kNumSymPerThread + i; symPdf[i] = smemPdf[curSym]; } using Scan = cub::BlockScan<uint32_t, Threads>; __shared__ typename Scan::TempStorage smemScan; // FIXME: initialize to 0? uint32_t symCdf[kNumSymPerThread]; Scan(smemScan).ExclusiveSum(symPdf, symCdf); // Compute divisor information (constant division via integer // multiplication + shift) uint32_t shift[kNumSymPerThread]; uint32_t magic[kNumSymPerThread]; #pragma unroll for (int i = 0; i < kNumSymPerThread; ++i) { shift[i] = 32 - __clz(symPdf[i] - 1); constexpr uint64_t one = 1; uint64_t magic64 = ((one << 32) * ((one << shift[i]) - symPdf[i])) / symPdf[i] + 1; // should not overflow magic[i] = (uint32_t)magic64; } #pragma unroll for (int i = 0; i < kNumSymPerThread; ++i) { // Same blocked contiguous ordering as before // Note that this is no longer a coalesced write int curSym = tid * kNumSymPerThread + i; table[curSym] = uint4{symPdf[i], symCdf[i], magic[i], shift[i]}; } } template <typename SizeProvider, int Threads> __global__ void quantizeWeights( const uint32_t* __restrict__ counts, SizeProvider sizeProvider, int probBits, uint4* __restrict__ table) { int batch = blockIdx.x; normalizeProbabilitiesFromHistogram<Threads>( counts + batch * kNumSymbols, sizeProvider.getBatchSize(batch), probBits, table + batch * kNumSymbols); } template <typename InProvider> void ansHistogramBatch( uint32_t numInBatch, InProvider inProvider, // size numInBatch * kNumSymbols uint32_t* histogram_dev, cudaStream_t stream) { // 1. Compute symbol histogram // zero out buckets before proceeding, as we aggregate with atomic adds CUDA_VERIFY(cudaMemsetAsync( histogram_dev, 0, sizeof(uint32_t) * kNumSymbols * numInBatch, stream)); { constexpr uint32_t kThreads = kNumSymbols; // What is the maximum number of blocks to saturate the GPU? int maxBlocks = 0; CUDA_VERIFY(cudaOccupancyMaxActiveBlocksPerMultiprocessor( &maxBlocks, histogramBatch<InProvider, kThreads>, kThreads, 0)); maxBlocks *= getCurrentDeviceProperties().multiProcessorCount; // The y block dimension will be for each batch element uint32_t xBlocks = divUp(maxBlocks, numInBatch); auto grid = dim3(xBlocks, numInBatch); histogramBatch<InProvider, kThreads> <<<grid, kThreads, 0, stream>>>(inProvider, histogram_dev); } } template <typename SizeProvider> inline void ansCalcWeights( uint32_t numInBatch, int probBits, // we only use this for sizes (of each input batch member) SizeProvider sizeProvider, // size numInBatch * kNumSymbols const uint32_t* histogram_dev, // size numInBatch * kNumSymbols uint4* table_dev, cudaStream_t stream) { // Quantize weights and determine integer ANS division factors constexpr int kThreads = kNumSymbols; quantizeWeights<SizeProvider, kThreads><<<numInBatch, kThreads, 0, stream>>>( histogram_dev, sizeProvider, probBits, table_dev); } } // namespace dietgpu
the_stack
#define MULT0(a) {\ tmp = a[7]; \ a[7] = a[6]; \ a[6] = a[5]; \ a[5] = a[4]; \ a[4] = a[3] ^ tmp; \ a[3] = a[2] ^ tmp; \ a[2] = a[1]; \ a[1] = a[0] ^ tmp; \ a[0] = tmp; \ } #define MULT2(a,j) { \ tmp = a[(j<<3)+7]; \ a[(j*8)+7] = a[(j*8)+6]; \ a[(j*8)+6] = a[(j*8)+5]; \ a[(j*8)+5] = a[(j*8)+4]; \ a[(j*8)+4] = a[(j*8)+3] ^ tmp; \ a[(j*8)+3] = a[(j*8)+2] ^ tmp; \ a[(j*8)+2] = a[(j*8)+1]; \ a[(j*8)+1] = a[(j*8)+0] ^ tmp; \ a[j*8] = tmp; \ } #define TWEAK(a0,a1,a2,a3,j) { \ a0 = ROTL32(a0,j); \ a1 = ROTL32(a1,j); \ a2 = ROTL32(a2,j); \ a3 = ROTL32(a3,j); \ } #define STEP(c0,c1) { \ SUBCRUMB(chainv[0],chainv[1],chainv[2],chainv[3],tmp); \ SUBCRUMB(chainv[5],chainv[6],chainv[7],chainv[4],tmp); \ MIXWORD(chainv[0],chainv[4]); \ MIXWORD(chainv[1],chainv[5]); \ MIXWORD(chainv[2],chainv[6]); \ MIXWORD(chainv[3],chainv[7]); \ ADD_CONSTANT(chainv[0],chainv[4],c0,c1); \ } #define SUBCRUMB(a0,a1,a2,a3,a4) { \ a4 = a0; \ a0 |= a1; \ a2 ^= a3; \ a1 = ~a1;\ a0 ^= a3; \ a3 &= a4; \ a1 ^= a3; \ a3 ^= a2; \ a2 &= a0; \ a0 = ~a0;\ a2 ^= a1; \ a1 |= a3; \ a4 ^= a1; \ a3 ^= a2; \ a2 &= a1; \ a1 ^= a0; \ a0 = a4; \ } #define MIXWORD(a0,a4) { \ a4 ^= a0; \ a0 = ROTL32(a0,2); \ a0 ^= a4; \ a4 = ROTL32(a4,14); \ a4 ^= a0; \ a0 = ROTL32(a0,10); \ a0 ^= a4; \ a4 = ROTL32(a4,1); \ } #define ADD_CONSTANT(a0,b0,c0,c1) { \ a0 ^= c0; \ b0 ^= c1; \ } __device__ __constant__ uint32_t c_CNS[80] = { 0x303994a6,0xe0337818,0xc0e65299,0x441ba90d, 0x6cc33a12,0x7f34d442,0xdc56983e,0x9389217f, 0x1e00108f,0xe5a8bce6,0x7800423d,0x5274baf4, 0x8f5b7882,0x26889ba7,0x96e1db12,0x9a226e9d, 0xb6de10ed,0x01685f3d,0x70f47aae,0x05a17cf4, 0x0707a3d4,0xbd09caca,0x1c1e8f51,0xf4272b28, 0x707a3d45,0x144ae5cc,0xaeb28562,0xfaa7ae2b, 0xbaca1589,0x2e48f1c1,0x40a46f3e,0xb923c704, 0xfc20d9d2,0xe25e72c1,0x34552e25,0xe623bb72, 0x7ad8818f,0x5c58a4a4,0x8438764a,0x1e38e2e7, 0xbb6de032,0x78e38b9d,0xedb780c8,0x27586719, 0xd9847356,0x36eda57f,0xa2c78434,0x703aace7, 0xb213afa5,0xe028c9bf,0xc84ebe95,0x44756f91, 0x4e608a22,0x7e8fce32,0x56d858fe,0x956548be, 0x343b138f,0xfe191be2,0xd0ec4e3d,0x3cb226e5, 0x2ceb4882,0x5944a28e,0xb3ad2208,0xa1c4c355, 0xf0d2e9e3,0x5090d577,0xac11d7fa,0x2d1925ab, 0x1bcb66f2,0xb46496ac,0x6f2d9bc9,0xd1925ab0, 0x78602649,0x29131ab6,0x8edae952,0x0fc053c3, 0x3b6ba548,0x3f014f0c,0xedae9520,0xfc053c31 }; // Precalculated chaining values __device__ __constant__ uint32_t c_IV[40] = { 0x8bb0a761, 0xc2e4aa8b, 0x2d539bc9, 0x381408f8, 0x478f6633, 0x255a46ff, 0x581c37f7, 0x601c2e8e, 0x266c5f9d, 0xc34715d8, 0x8900670e, 0x51a540be, 0xe4ce69fb, 0x5089f4d4, 0x3cc0a506, 0x609bcb02, 0xa4e3cd82, 0xd24fd6ca, 0xc0f196dc, 0xcf41eafe, 0x0ff2e673, 0x303804f2, 0xa7b3cd48, 0x677addd4, 0x66e66a8a, 0x2303208f, 0x486dafb4, 0xc0d37dc6, 0x634d15af, 0xe5af6747, 0x10af7e38, 0xee7e6428, 0x01262e5d, 0xc92c2e64, 0x82fee966, 0xcea738d3, 0x867de2b0, 0xe0714818, 0xda6e831f, 0xa7062529 }; /***************************************************/ __device__ __forceinline__ static void rnd512(uint32_t *statebuffer, uint32_t *statechainv) { uint32_t t[40]; uint32_t chainv[8]; uint32_t tmp; int i,j; #pragma unroll for(i=0;i<8;i++) { t[i] = 0; #pragma unroll 5 for(j=0;j<5;j++) t[i] ^= statechainv[i+8*j]; } MULT0(t); #pragma unroll for(j=0;j<5;j++) { #pragma unroll for(i=0;i<8;i++) statechainv[i+8*j] ^= t[i]; } #pragma unroll for(j=0;j<5;j++) { #pragma unroll for(i=0;i<8;i++) t[i+8*j] = statechainv[i+8*j]; } MULT0(statechainv); #pragma unroll 4 for(j=1;j<5;j++) { MULT2(statechainv, j); } #pragma unroll for(j=0;j<5;j++) { #pragma unroll for(i=0;i<8;i++) statechainv[8*j+i] ^= t[8*((j+1)%5)+i]; } #pragma unroll for(j=0;j<5;j++) { #pragma unroll for(i=0;i<8;i++) t[i+8*j] = statechainv[i+8*j]; } MULT0(statechainv); #pragma unroll 4 for(j=1;j<5;j++) { MULT2(statechainv, j); } #pragma unroll for(j=0;j<5;j++) { #pragma unroll for(i=0;i<8;i++) statechainv[8*j+i] ^= t[8*((j+4)%5)+i]; } #pragma unroll for(j=0;j<5;j++) { #pragma unroll 8 for(i=0;i<8;i++) statechainv[i+8*j] ^= statebuffer[i]; MULT0(statebuffer); } #pragma unroll for(i=0;i<8;i++) { chainv[i] = statechainv[i]; } #pragma unroll 1 for(i=0;i<8;i++) { STEP(c_CNS[(2*i)],c_CNS[(2*i)+1]); } #pragma unroll for(i=0;i<8;i++) { statechainv[i] = chainv[i]; chainv[i] = statechainv[i+8]; } TWEAK(chainv[4],chainv[5],chainv[6],chainv[7],1); #pragma unroll 1 for(i=0;i<8;i++) { STEP(c_CNS[(2*i)+16],c_CNS[(2*i)+16+1]); } #pragma unroll for(i=0;i<8;i++) { statechainv[i+8] = chainv[i]; chainv[i] = statechainv[i+16]; } TWEAK(chainv[4],chainv[5],chainv[6],chainv[7],2); #pragma unroll 1 for(i=0;i<8;i++) { STEP(c_CNS[(2*i)+32],c_CNS[(2*i)+32+1]); } #pragma unroll for(i=0;i<8;i++) { statechainv[i+16] = chainv[i]; chainv[i] = statechainv[i+24]; } TWEAK(chainv[4],chainv[5],chainv[6],chainv[7],3); #pragma unroll 1 for(i=0;i<8;i++) { STEP(c_CNS[(2*i)+48],c_CNS[(2*i)+48+1]); } #pragma unroll for(i=0;i<8;i++) { statechainv[i+24] = chainv[i]; chainv[i] = statechainv[i+32]; } TWEAK(chainv[4],chainv[5],chainv[6],chainv[7],4); #pragma unroll 1 for(i=0;i<8;i++) { STEP(c_CNS[(2*i)+64],c_CNS[(2*i)+64+1]); } #pragma unroll for(i=0;i<8;i++) { statechainv[i+32] = chainv[i]; } } __device__ __forceinline__ static void rnd512_first(uint32_t state[40], uint32_t buffer[8]) { uint32_t chainv[8]; uint32_t tmp; int i, j; for (j = 0; j<5; j++) { state[8 * j] ^= buffer[0]; #pragma unroll 7 for (i = 1; i<8; i++) state[i + 8 * j] ^= buffer[i]; MULT0(buffer); } #pragma unroll for (i = 0; i<8; i++) chainv[i] = state[i]; #pragma unroll 1 for (i = 0; i<8; i++) { STEP(c_CNS[(2 * i)], c_CNS[(2 * i) + 1]); } #pragma unroll for (i = 0; i<8; i++) { state[i] = chainv[i]; chainv[i] = state[i + 8]; } TWEAK(chainv[4], chainv[5], chainv[6], chainv[7], 1); #pragma unroll 1 for (i = 0; i<8; i++) { STEP(c_CNS[(2 * i) + 16], c_CNS[(2 * i) + 16 + 1]); } #pragma unroll for (i = 0; i<8; i++) { state[i + 8] = chainv[i]; chainv[i] = state[i + 16]; } TWEAK(chainv[4], chainv[5], chainv[6], chainv[7], 2); #pragma unroll 1 for (i = 0; i<8; i++) { STEP(c_CNS[(2 * i) + 32], c_CNS[(2 * i) + 32 + 1]); } #pragma unroll for (i = 0; i<8; i++) { state[i + 16] = chainv[i]; chainv[i] = state[i + 24]; } TWEAK(chainv[4], chainv[5], chainv[6], chainv[7], 3); #pragma unroll 1 for (i = 0; i<8; i++) { STEP(c_CNS[(2 * i) + 48], c_CNS[(2 * i) + 48 + 1]); } #pragma unroll for (i = 0; i<8; i++) { state[i + 24] = chainv[i]; chainv[i] = state[i + 32]; } TWEAK(chainv[4], chainv[5], chainv[6], chainv[7], 4); #pragma unroll 1 for (i = 0; i<8; i++) { STEP(c_CNS[(2 * i) + 64], c_CNS[(2 * i) + 64 + 1]); } #pragma unroll for (i = 0; i<8; i++) state[i + 32] = chainv[i]; } /***************************************************/ __device__ __forceinline__ static void rnd512_nullhash(uint32_t *state) { uint32_t t[40]; uint32_t chainv[8]; uint32_t tmp; int i, j; #pragma unroll for (i = 0; i<8; i++) { t[i] = state[i + 8 * 0]; #pragma unroll 4 for (j = 1; j<5; j++) t[i] ^= state[i + 8 * j]; } MULT0(t); #pragma unroll for (j = 0; j<5; j++) { #pragma unroll for (i = 0; i<8; i++) state[i + 8 * j] ^= t[i]; } #pragma unroll for (j = 0; j<5; j++) { #pragma unroll for (i = 0; i<8; i++) t[i + 8 * j] = state[i + 8 * j]; } MULT0(state); #pragma unroll 4 for(j=1; j<5; j++) { MULT2(state, j); } #pragma unroll for (j = 0; j<5; j++) { #pragma unroll for (i = 0; i<8; i++) state[8 * j + i] ^= t[8 * ((j + 1) % 5) + i]; } #pragma unroll for (j = 0; j<5; j++) { #pragma unroll 8 for (i = 0; i<8; i++) t[i + 8 * j] = state[i + 8 * j]; } MULT0(state); #pragma unroll 4 for(j=1; j<5; j++) { MULT2(state, j); } #pragma unroll for (j = 0; j<5; j++) { #pragma unroll for (i = 0; i<8; i++) state[8 * j + i] ^= t[8 * ((j + 4) % 5) + i]; } #pragma unroll for (i = 0; i<8; i++) chainv[i] = state[i]; #pragma unroll 1 for (i = 0; i<8; i++) { STEP(c_CNS[(2 * i)], c_CNS[(2 * i) + 1]); } #pragma unroll for (i = 0; i<8; i++) { state[i] = chainv[i]; chainv[i] = state[i + 8]; } TWEAK(chainv[4], chainv[5], chainv[6], chainv[7], 1); #pragma unroll 1 for (i = 0; i<8; i++) { STEP(c_CNS[(2 * i) + 16], c_CNS[(2 * i) + 16 + 1]); } #pragma unroll for (i = 0; i<8; i++) { state[i + 8] = chainv[i]; chainv[i] = state[i + 16]; } TWEAK(chainv[4], chainv[5], chainv[6], chainv[7], 2); #pragma unroll 1 for (i = 0; i<8; i++) { STEP(c_CNS[(2 * i) + 32], c_CNS[(2 * i) + 32 + 1]); } #pragma unroll for (i = 0; i<8; i++) { state[i + 16] = chainv[i]; chainv[i] = state[i + 24]; } TWEAK(chainv[4], chainv[5], chainv[6], chainv[7], 3); #pragma unroll 1 for (i = 0; i<8; i++) { STEP(c_CNS[(2 * i) + 48], c_CNS[(2 * i) + 48 + 1]); } #pragma unroll for (i = 0; i<8; i++) { state[i + 24] = chainv[i]; chainv[i] = state[i + 32]; } TWEAK(chainv[4], chainv[5], chainv[6], chainv[7], 4); #pragma unroll 1 for (i = 0; i<8; i++) { STEP(c_CNS[(2 * i) + 64], c_CNS[(2 * i) + 64 + 1]); } #pragma unroll for (i = 0; i<8; i++) { state[i + 32] = chainv[i]; } } __device__ __forceinline__ static void Update512(uint32_t *statebuffer, uint32_t *statechainv, const uint32_t *data) { #pragma unroll for (int i = 0; i < 8; i++) statebuffer[i] = cuda_swab32(data[i]); rnd512_first(statechainv, statebuffer); #pragma unroll for (int i = 0; i < 8; i++) statebuffer[i] = cuda_swab32(data[i + 8]); rnd512(statebuffer, statechainv); } /***************************************************/ __device__ __forceinline__ static void finalization512(uint32_t *statebuffer, uint32_t *statechainv, uint32_t *b) { int i,j; statebuffer[0] = 0x80000000; #pragma unroll 7 for(int i=1;i<8;i++) statebuffer[i] = 0; rnd512(statebuffer, statechainv); /*---- blank round with m=0 ----*/ rnd512_nullhash(statechainv); #pragma unroll for(i=0;i<8;i++) { b[i] = statechainv[i]; #pragma unroll 4 for(j=1;j<5;j++) { b[i] ^= statechainv[i+8*j]; } b[i] = cuda_swab32((b[i])); } rnd512_nullhash(statechainv); #pragma unroll for(i=0;i<8;i++) { b[8 + i] = statechainv[i]; #pragma unroll 4 for(j=1;j<5;j++) { b[8+i] ^= statechainv[i+8*j]; } b[8 + i] = cuda_swab32((b[8 + i])); } } #define ROUND_EVEN { \ xg = (x0 + xg); \ x0 = ROTL32(x0, 7); \ xh = (x1 + xh); \ x1 = ROTL32(x1, 7); \ xi = (x2 + xi); \ x2 = ROTL32(x2, 7); \ xj = (x3 + xj); \ x3 = ROTL32(x3, 7); \ xk = (x4 + xk); \ x4 = ROTL32(x4, 7); \ xl = (x5 + xl); \ x5 = ROTL32(x5, 7); \ xm = (x6 + xm); \ x6 = ROTL32(x6, 7); \ xn = (x7 + xn); \ x7 = ROTL32(x7, 7); \ xo = (x8 + xo); \ x8 = ROTL32(x8, 7); \ xp = (x9 + xp); \ x9 = ROTL32(x9, 7); \ xq = (xa + xq); \ xa = ROTL32(xa, 7); \ xr = (xb + xr); \ xb = ROTL32(xb, 7); \ xs = (xc + xs); \ xc = ROTL32(xc, 7); \ xt = (xd + xt); \ xd = ROTL32(xd, 7); \ xu = (xe + xu); \ xe = ROTL32(xe, 7); \ xv = (xf + xv); \ xf = ROTL32(xf, 7); \ x8 ^= xg; \ x9 ^= xh; \ xa ^= xi; \ xb ^= xj; \ xc ^= xk; \ xd ^= xl; \ xe ^= xm; \ xf ^= xn; \ x0 ^= xo; \ x1 ^= xp; \ x2 ^= xq; \ x3 ^= xr; \ x4 ^= xs; \ x5 ^= xt; \ x6 ^= xu; \ x7 ^= xv; \ xi = (x8 + xi); \ x8 = ROTL32(x8, 11); \ xj = (x9 + xj); \ x9 = ROTL32(x9, 11); \ xg = (xa + xg); \ xa = ROTL32(xa, 11); \ xh = (xb + xh); \ xb = ROTL32(xb, 11); \ xm = (xc + xm); \ xc = ROTL32(xc, 11); \ xn = (xd + xn); \ xd = ROTL32(xd, 11); \ xk = (xe + xk); \ xe = ROTL32(xe, 11); \ xl = (xf + xl); \ xf = ROTL32(xf, 11); \ xq = (x0 + xq); \ x0 = ROTL32(x0, 11); \ xr = (x1 + xr); \ x1 = ROTL32(x1, 11); \ xo = (x2 + xo); \ x2 = ROTL32(x2, 11); \ xp = (x3 + xp); \ x3 = ROTL32(x3, 11); \ xu = (x4 + xu); \ x4 = ROTL32(x4, 11); \ xv = (x5 + xv); \ x5 = ROTL32(x5, 11); \ xs = (x6 + xs); \ x6 = ROTL32(x6, 11); \ xt = (x7 + xt); \ x7 = ROTL32(x7, 11); \ xc ^= xi; \ xd ^= xj; \ xe ^= xg; \ xf ^= xh; \ x8 ^= xm; \ x9 ^= xn; \ xa ^= xk; \ xb ^= xl; \ x4 ^= xq; \ x5 ^= xr; \ x6 ^= xo; \ x7 ^= xp; \ x0 ^= xu; \ x1 ^= xv; \ x2 ^= xs; \ x3 ^= xt; \ } #define ROUND_ODD { \ xj = (xc + xj); \ xc = ROTL32(xc, 7); \ xi = (xd + xi); \ xd = ROTL32(xd, 7); \ xh = (xe + xh); \ xe = ROTL32(xe, 7); \ xg = (xf + xg); \ xf = ROTL32(xf, 7); \ xn = (x8 + xn); \ x8 = ROTL32(x8, 7); \ xm = (x9 + xm); \ x9 = ROTL32(x9, 7); \ xl = (xa + xl); \ xa = ROTL32(xa, 7); \ xk = (xb + xk); \ xb = ROTL32(xb, 7); \ xr = (x4 + xr); \ x4 = ROTL32(x4, 7); \ xq = (x5 + xq); \ x5 = ROTL32(x5, 7); \ xp = (x6 + xp); \ x6 = ROTL32(x6, 7); \ xo = (x7 + xo); \ x7 = ROTL32(x7, 7); \ xv = (x0 + xv); \ x0 = ROTL32(x0, 7); \ xu = (x1 + xu); \ x1 = ROTL32(x1, 7); \ xt = (x2 + xt); \ x2 = ROTL32(x2, 7); \ xs = (x3 + xs); \ x3 = ROTL32(x3, 7); \ x4 ^= xj; \ x5 ^= xi; \ x6 ^= xh; \ x7 ^= xg; \ x0 ^= xn; \ x1 ^= xm; \ x2 ^= xl; \ x3 ^= xk; \ xc ^= xr; \ xd ^= xq; \ xe ^= xp; \ xf ^= xo; \ x8 ^= xv; \ x9 ^= xu; \ xa ^= xt; \ xb ^= xs; \ xh = (x4 + xh); \ x4 = ROTL32(x4, 11); \ xg = (x5 + xg); \ x5 = ROTL32(x5, 11); \ xj = (x6 + xj); \ x6 = ROTL32(x6, 11); \ xi = (x7 + xi); \ x7 = ROTL32(x7, 11); \ xl = (x0 + xl); \ x0 = ROTL32(x0, 11); \ xk = (x1 + xk); \ x1 = ROTL32(x1, 11); \ xn = (x2 + xn); \ x2 = ROTL32(x2, 11); \ xm = (x3 + xm); \ x3 = ROTL32(x3, 11); \ xp = (xc + xp); \ xc = ROTL32(xc, 11); \ xo = (xd + xo); \ xd = ROTL32(xd, 11); \ xr = (xe + xr); \ xe = ROTL32(xe, 11); \ xq = (xf + xq); \ xf = ROTL32(xf, 11); \ xt = (x8 + xt); \ x8 = ROTL32(x8, 11); \ xs = (x9 + xs); \ x9 = ROTL32(x9, 11); \ xv = (xa + xv); \ xa = ROTL32(xa, 11); \ xu = (xb + xu); \ xb = ROTL32(xb, 11); \ x0 ^= xh; \ x1 ^= xg; \ x2 ^= xj; \ x3 ^= xi; \ x4 ^= xl; \ x5 ^= xk; \ x6 ^= xn; \ x7 ^= xm; \ x8 ^= xp; \ x9 ^= xo; \ xa ^= xr; \ xb ^= xq; \ xc ^= xt; \ xd ^= xs; \ xe ^= xv; \ xf ^= xu; \ } #define SIXTEEN_ROUNDS \ for (int j = 0; j < 8; j ++) { \ ROUND_EVEN; \ ROUND_ODD; \ } __global__ #if __CUDA_ARCH__ > 500 __launch_bounds__(256, 4) #endif void x11_luffaCubehash512_gpu_hash_64(uint32_t threads, uint32_t *g_hash) { const uint32_t thread = (blockDim.x * blockIdx.x + threadIdx.x); if (thread < threads) { uint32_t statechainv[40] = { 0x8bb0a761, 0xc2e4aa8b, 0x2d539bc9, 0x381408f8, 0x478f6633, 0x255a46ff, 0x581c37f7, 0x601c2e8e, 0x266c5f9d, 0xc34715d8, 0x8900670e, 0x51a540be, 0xe4ce69fb, 0x5089f4d4, 0x3cc0a506, 0x609bcb02, 0xa4e3cd82, 0xd24fd6ca, 0xc0f196dc, 0xcf41eafe, 0x0ff2e673, 0x303804f2, 0xa7b3cd48, 0x677addd4, 0x66e66a8a, 0x2303208f, 0x486dafb4, 0xc0d37dc6, 0x634d15af, 0xe5af6747, 0x10af7e38, 0xee7e6428, 0x01262e5d, 0xc92c2e64, 0x82fee966, 0xcea738d3, 0x867de2b0, 0xe0714818, 0xda6e831f, 0xa7062529 }; uint32_t statebuffer[8]; uint32_t *const Hash = &g_hash[thread * 16U]; Update512(statebuffer, statechainv, Hash); finalization512(statebuffer, statechainv, Hash); //Cubehash uint32_t x0 = 0x2AEA2A61, x1 = 0x50F494D4, x2 = 0x2D538B8B, x3 = 0x4167D83E; uint32_t x4 = 0x3FEE2313, x5 = 0xC701CF8C, x6 = 0xCC39968E, x7 = 0x50AC5695; uint32_t x8 = 0x4D42C787, x9 = 0xA647A8B3, xa = 0x97CF0BEF, xb = 0x825B4537; uint32_t xc = 0xEEF864D2, xd = 0xF22090C4, xe = 0xD0E5CD33, xf = 0xA23911AE; uint32_t xg = 0xFCD398D9, xh = 0x148FE485, xi = 0x1B017BEF, xj = 0xB6444532; uint32_t xk = 0x6A536159, xl = 0x2FF5781C, xm = 0x91FA7934, xn = 0x0DBADEA9; uint32_t xo = 0xD65C8A2B, xp = 0xA5A70E75, xq = 0xB1C62456, xr = 0xBC796576; uint32_t xs = 0x1921C8F7, xt = 0xE7989AF1, xu = 0x7795D246, xv = 0xD43E3B44; x0 ^= Hash[0]; x1 ^= Hash[1]; x2 ^= Hash[2]; x3 ^= Hash[3]; x4 ^= Hash[4]; x5 ^= Hash[5]; x6 ^= Hash[6]; x7 ^= Hash[7]; SIXTEEN_ROUNDS; x0 ^= Hash[8]; x1 ^= Hash[9]; x2 ^= Hash[10]; x3 ^= Hash[11]; x4 ^= Hash[12]; x5 ^= Hash[13]; x6 ^= Hash[14]; x7 ^= Hash[15]; SIXTEEN_ROUNDS; x0 ^= 0x80; SIXTEEN_ROUNDS; xv ^= 1; for (int i = 3; i < 13; i++) { SIXTEEN_ROUNDS; } Hash[0] = x0; Hash[1] = x1; Hash[2] = x2; Hash[3] = x3; Hash[4] = x4; Hash[5] = x5; Hash[6] = x6; Hash[7] = x7; Hash[8] = x8; Hash[9] = x9; Hash[10] = xa; Hash[11] = xb; Hash[12] = xc; Hash[13] = xd; Hash[14] = xe; Hash[15] = xf; } } __host__ void x11_luffaCubehash512_cpu_hash_64(int thr_id, uint32_t threads, uint32_t *d_hash, int order) { const uint32_t threadsperblock = 256; dim3 grid((threads + threadsperblock-1)/threadsperblock); dim3 block(threadsperblock); x11_luffaCubehash512_gpu_hash_64 <<<grid, block>>> (threads, d_hash); MyStreamSynchronize(NULL, order, thr_id); } // Setup __host__ void x11_luffaCubehash512_cpu_init(int thr_id, uint32_t threads) {}
the_stack
template <typename scalar_t> __device__ scalar_t deform_conv2d_im2col_bilinear( const scalar_t *bottom_data, const int data_width, const int height, const int width, scalar_t h, scalar_t w) { int h_low = floor(h); int w_low = floor(w); int h_high = h_low + 1; int w_high = w_low + 1; scalar_t lh = h - h_low; scalar_t lw = w - w_low; scalar_t hh = 1 - lh, hw = 1 - lw; scalar_t v1 = 0; if (h_low >= 0 && w_low >= 0) v1 = bottom_data[h_low * data_width + w_low]; scalar_t v2 = 0; if (h_low >= 0 && w_high <= width - 1) v2 = bottom_data[h_low * data_width + w_high]; scalar_t v3 = 0; if (h_high <= height - 1 && w_low >= 0) v3 = bottom_data[h_high * data_width + w_low]; scalar_t v4 = 0; if (h_high <= height - 1 && w_high <= width - 1) v4 = bottom_data[h_high * data_width + w_high]; scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw; scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4); return val; } template <typename scalar_t> __global__ void deform_conv2d_im2col_gpu_kernel( const int n, const scalar_t *data_im, const scalar_t *data_offset, const int height, const int width, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int channel_per_deformable_group, const int batch_size, const int num_channels, const int deformable_group, const int height_col, const int width_col, scalar_t *data_col) { CUDA_KERNEL_LOOP(index, n) { // index index of output matrix const int w_col = index % width_col; const int h_col = (index / width_col) % height_col; const int b_col = (index / width_col / height_col) % batch_size; const int c_im = (index / width_col / height_col) / batch_size; const int c_col = c_im * kernel_h * kernel_w; // compute deformable group index const int deformable_group_index = c_im / channel_per_deformable_group; const int h_in = h_col * stride_h - pad_h; const int w_in = w_col * stride_w - pad_w; scalar_t *data_col_ptr = data_col + ((c_col * batch_size + b_col) * height_col + h_col) * width_col + w_col; //const float* data_im_ptr = data_im + ((b_col * num_channels + c_im) * height + h_in) * width + w_in; const scalar_t *data_im_ptr = data_im + (b_col * num_channels + c_im) * height * width; const scalar_t *data_offset_ptr = data_offset + (b_col * deformable_group + deformable_group_index) * 2 * kernel_h * kernel_w * height_col * width_col; for (int i = 0; i < kernel_h; ++i) for (int j = 0; j < kernel_w; ++j) { const int data_offset_h_ptr = ((2 * (i * kernel_w + j)) * height_col + h_col) * width_col + w_col; const int data_offset_w_ptr = ((2 * (i * kernel_w + j) + 1) * height_col + h_col) * width_col + w_col; const scalar_t offset_h = data_offset_ptr[data_offset_h_ptr]; const scalar_t offset_w = data_offset_ptr[data_offset_w_ptr]; scalar_t val = static_cast<scalar_t>(0); const scalar_t h_im = h_in + i * dilation_h + offset_h; const scalar_t w_im = w_in + j * dilation_w + offset_w; if (h_im > -1 && w_im > -1 && h_im < height && w_im < width){ val = deform_conv2d_im2col_bilinear(data_im_ptr, width, height, width, h_im, w_im); } *data_col_ptr = val; data_col_ptr += batch_size * height_col * width_col; } } } void deform_conv2d_im2col_cuda( at::Tensor data_im, at::Tensor data_offset, const int batch_size, const int channels, const int height_im, const int width_im, const int height_col, const int width_col, const int kernel_h, const int kenerl_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int deformable_group, at::Tensor data_col) { // num_axes should be smaller than block size const int channel_per_deformable_group = channels / deformable_group; const int num_kernels = channels * batch_size * height_col * width_col; AT_DISPATCH_FLOATING_TYPES_AND_HALF( data_im.scalar_type(), "deform_conv2d_im2col_gpu_kernel", ([&] { const scalar_t *data_im_ = data_im.data<scalar_t>(); const scalar_t *data_offset_ = data_offset.data<scalar_t>(); scalar_t *data_col_ = data_col.data<scalar_t>(); deform_conv2d_im2col_gpu_kernel<<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS>>>( num_kernels, data_im_, data_offset_, height_im, width_im, kernel_h, kenerl_w, pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, channel_per_deformable_group, batch_size, channels, deformable_group, height_col, width_col, data_col_); })); cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) { printf("error in deform_conv2d_im2col_cuda: %s\n", cudaGetErrorString(err)); } } int deform_conv2d_forward_cuda( at::Tensor input, at::Tensor weight, at::Tensor bias, at::Tensor offset, at::Tensor output, const int kernel_h,const int kernel_w, const int stride_h, const int stride_w, const int pad_h, const int pad_w, const int dilation_h,const int dilation_w, const int group, const int deformable_group,const int in_step, const bool with_bias) { AT_CHECK(input.is_contiguous(), "input tensor has to be contiguous"); AT_CHECK(weight.is_contiguous(), "weight tensor has to be contiguous"); AT_CHECK(bias.is_contiguous(), "bias tensor has to be contiguous"); AT_CHECK(offset.is_contiguous(), "offset tensor has to be contiguous"); AT_CHECK(output.is_contiguous(), "output tensor has to be contiguous"); const int batch = input.size(0); const int channels = input.size(1); const int height = input.size(2); const int width = input.size(3); const int channels_out = weight.size(0); const int channels_kernel = weight.size(1); const int kernel_h_ = weight.size(2); const int kernel_w_ = weight.size(3); if (kernel_h_ != kernel_h || kernel_w_ != kernel_w) AT_ERROR("Input shape and kernel shape wont match: (%d x %d vs %d x %d).", kernel_h_, kernel_w, kernel_h_, kernel_w_); if (channels != channels_kernel * group) AT_ERROR("Input shape and kernel channels wont match: (%d vs %d).", channels, channels_kernel * group); const int height_out = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1; const int width_out = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1; // resize output const int step=GET_STEP(batch,in_step); output = output.view({batch, channels_out, height_out, width_out}); output.zero_(); // resize temporary columns at::Tensor columns =at::zeros({channels * kernel_h * kernel_w, step * height_out * width_out},input.options()); input=input.view({batch/step,step,channels,height,width}); offset=offset.view({batch/step,step,deformable_group * 2 *kernel_h*kernel_w,height_out,width_out}); // divide into group output = output.view({batch/step, group, output.size(1) / group,step, output.size(2), output.size(3)}); weight = weight.view({group, weight.size(0) / group, weight.size(1), weight.size(2), weight.size(3)}); for (int b = 0; b < batch/step; b++) { columns.fill_(0); deform_conv2d_im2col_cuda( input[b], offset[b], step, channels, height, width, height_out, width_out, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, deformable_group, columns); columns = columns.view({group, columns.size(0) / group, columns.size(1)}); for (int g = 0; g < group; g++) { output[b][g] = output[b][g].flatten(1) .addmm_(weight[g].flatten(1), columns[g]).view_as(output[b][g]); } columns = columns.view({columns.size(0) * columns.size(1), columns.size(2)}); } weight = weight.view({weight.size(0) * weight.size(1), weight.size(2), weight.size(3), weight.size(4)}); output = output.view({output.size(0), output.size(1) * output.size(2), output.size(3), output.size(4),output.size(5)}); output = output.view({batch / step, channels_out, step, height_out, width_out}); output.transpose_(1, 2); output = output.contiguous().view({batch , channels_out, height_out, width_out}); if (with_bias) { output += bias.view({1, bias.size(0), 1, 1}); } input=input.view({batch,channels,height,width}); offset=offset.view({batch,deformable_group * 2 *kernel_h*kernel_w,height_out,width_out}); return 0; } template <typename scalar_t> __global__ void deform_conv2d_gradient_gpu_kernel( const int n,const scalar_t *grad_col, const scalar_t *data_input, const scalar_t *data_offset, scalar_t * columns, const int channels_input, const int height_input, const int width_input, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int channel_per_deformable_group, const int step, const int offset_channels,const int deformable_group, const int height_col, const int width_col, scalar_t * grad_input,scalar_t *grad_offset) { // columns = {channels * kernel_h * kernel_w,step*height_out * width_out} // grad_columns = {channels * kernel_h * kernel_w,step*height_out * width_out} // grad_output = {step,channels_out,height_out,width_out} // input = {step,channels,height,width} // offset = {step,deformable_group * 2 * kernel_h * kernel_w,height_out,width_out} // grad_offset = {step,deformable_group * 2 * kernel_h * kernel_w,height_out,width_out}); CUDA_KERNEL_LOOP(index, n)//channels*kernel_h * kernel_w * step * height_col * width_col; { int k = (index /step/ height_col / width_col)%(kernel_h*kernel_w); int i=k/kernel_w; int j=k%kernel_w; int bpos=(index%(step*height_col*width_col))/(height_col*width_col); int wpos_col = (index % (height_col*width_col)) % width_col; int hpos_col = ((index %(height_col*width_col)) / width_col) % height_col; int cpos_col = (index / step / width_col / height_col); int cpos_in=cpos_col/kernel_h/kernel_w; int offset_group_index=cpos_in/(channels_input/deformable_group); //printf("index %d bpos %d cpos_col %d hpos_col %d wpos_col %d \n",index,bpos,cpos_col,hpos_col,wpos_col); int offset_h_ptr=bpos*(deformable_group * 2 * kernel_h * kernel_w*height_col*width_col) +offset_group_index*channel_per_deformable_group*height_col*width_col +2*k*height_col*width_col+hpos_col*width_col+wpos_col; int offset_w_ptr=bpos*(deformable_group * 2 * kernel_h * kernel_w*height_col*width_col) +offset_group_index*channel_per_deformable_group*height_col*width_col +(2*k+1)*height_col*width_col+hpos_col*width_col+wpos_col; scalar_t offset_h=data_offset[offset_h_ptr]; scalar_t offset_w=data_offset[offset_w_ptr]; int hpos_in = hpos_col * stride_h -pad_h + (i) * dilation_h; int wpos_in = wpos_col * stride_w - pad_w + (j) * dilation_w; auto real_offset_h=hpos_in+offset_h; auto real_offset_w=wpos_in+offset_w; int h_low = floor(real_offset_h); int w_low = floor(real_offset_w); int h_high = h_low + 1; int w_high = w_low + 1; scalar_t dh = real_offset_h - h_low; scalar_t dw = real_offset_w - w_low; scalar_t v1 = 0; if (h_low >= 0 && h_low <= height_input -1 && w_low >= 0 && w_low <= width_input - 1 ) v1 = data_input[bpos*channels_input*height_input*width_input+cpos_in*height_input*width_input+h_low * width_input + w_low]; scalar_t v2 = 0; if (h_low >= 0 && h_low <= height_input - 1 && w_high >= 0 && w_high <= width_input - 1&& abs(dw)>EPS ) v2 = data_input[bpos*channels_input*height_input*width_input+cpos_in*height_input*width_input+h_low * width_input + w_high]; scalar_t v3 = 0; if (h_high >= 0 && h_high <= height_input - 1 && w_low >= 0 && w_low <= width_input - 1 && abs(dh)>EPS) v3 = data_input[bpos*channels_input*height_input*width_input+cpos_in*height_input*width_input+h_high * width_input + w_low]; scalar_t v4 = 0; if (h_high >= 0 && h_high <= height_input - 1 && w_high >= 0 && w_high <= width_input - 1 && abs(dh)>EPS && abs(dw)>EPS ) v4 = data_input[bpos*channels_input*height_input*width_input+cpos_in*height_input*width_input+h_high * width_input + w_high]; scalar_t w1 = (1-dh) *(1- dw), w2 =(1- dh) * dw, w3 = dh*(1- dw), w4 = dh * dw; scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4); scalar_t col=val;// auto dval=grad_col[index]; if (h_low >= 0 && h_low<= height_input - 1 && w_low >= 0 && w_low<= width_input - 1) atomicAdd(grad_input + bpos*channels_input*height_input*width_input + cpos_in*height_input*width_input+h_low * width_input + w_low, w1*dval); if (h_low >= 0 && h_low<= height_input - 1 && w_high>=0 && w_high <= width_input - 1) atomicAdd(grad_input + bpos*channels_input*height_input*width_input + cpos_in*height_input*width_input+h_low * width_input + w_high, w2*dval); if (h_high >= 0 && h_high <= height_input - 1 && w_low >= 0 && w_low<= width_input - 1) atomicAdd(grad_input + bpos*channels_input*height_input*width_input + cpos_in*height_input*width_input+h_high * width_input + w_low, w3*dval); if (h_high >= 0 && h_high <= height_input - 1 && w_high>=0 && w_high <= width_input - 1) atomicAdd(grad_input + bpos*channels_input*height_input*width_input + cpos_in*height_input*width_input+h_high * width_input + w_high,w4*dval); //grad_offset[offset_h_ptr]+=(-1*(1-dw)*v1-1*dw*v2+(1-dw)*v3+dw*v4)*dval; atomicAdd(grad_offset + offset_h_ptr,(-1*(1-dw)*v1-1*dw*v2+(1-dw)*v3+dw*v4)*dval); //grad_offset[offset_w_ptr]+=(-1*(1-dh)*v1+(1-dh)*v2-1*dh*v3+dh*v4)*dval; atomicAdd(grad_offset + offset_w_ptr,(-1*(1-dh)*v1+(1-dh)*v2-1*dh*v3+dh*v4)*dval); columns[index]=col; } } void deform_conv2d_gradient_cuda( at::Tensor grad_col,at::Tensor data_input, at::Tensor data_offset, at::Tensor columns, const int channels, const int height_input, const int width_input, const int height_col, const int width_col, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, const int step, const int deformable_group, at::Tensor grad_input, at::Tensor grad_offset) { const int num_kernels =channels*height_col * width_col * kernel_h * kernel_w * step; const int channel_per_deformable_group =2 * kernel_h * kernel_w ; AT_DISPATCH_FLOATING_TYPES_AND_HALF( grad_col.scalar_type(), "deform_conv2d_gradient_gpu_kernel", ([&] { const scalar_t *grad_col_ = grad_col.data<scalar_t>(); const scalar_t *data_input_ = data_input.data<scalar_t>(); const scalar_t *data_offset_ = data_offset.data<scalar_t>(); scalar_t *columns_ = columns.data<scalar_t>(); scalar_t *grad_input_ = grad_input.data<scalar_t>(); scalar_t *grad_offset_ = grad_offset.data<scalar_t>(); deform_conv2d_gradient_gpu_kernel<<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS>>>( num_kernels, grad_col_, data_input_, data_offset_,columns_, channels, height_input, width_input, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, channel_per_deformable_group,step, channel_per_deformable_group * deformable_group, deformable_group, height_col, width_col, grad_input_,grad_offset_); })); cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) { printf("error in deform_conv2d_gradient_cuda: %s\n", cudaGetErrorString(err)); } } int deform_conv2d_backward_cuda( at::Tensor input, at::Tensor weight, at::Tensor bias,at::Tensor offset, at::Tensor grad_input, at::Tensor grad_weight, at::Tensor grad_bias, at::Tensor grad_offset, at::Tensor grad_output, const int kernel_h,const int kernel_w,const int stride_h,const int stride_w, const int pad_h,const int pad_w,const int dilation_h,const int dilation_w, const int group,const int deformable_group, const int in_step,const bool with_bias) { AT_CHECK(input.is_contiguous(), "input tensor has to be contiguous"); AT_CHECK(weight.is_contiguous(), "weight tensor has to be contiguous"); AT_CHECK(bias.is_contiguous(), "bias tensor has to be contiguous"); AT_CHECK(offset.is_contiguous(), "offset tensor has to be contiguous"); AT_CHECK(grad_input.is_contiguous(), "grad_input tensor has to be contiguous"); AT_CHECK(grad_weight.is_contiguous(), "grad_weight tensor has to be contiguous"); AT_CHECK(grad_bias.is_contiguous(), "grad_bias tensor has to be contiguous"); AT_CHECK(grad_offset.is_contiguous(), "grad_offset tensor has to be contiguous"); AT_CHECK(grad_output.is_contiguous(), "grad_output tensor has to be contiguous"); const int batch = input.size(0); const int channels = input.size(1); const int height = input.size(2); const int width = input.size(3); const int channels_out=weight.size(0); const int channels_kernel = weight.size(1); const int kernel_h_ = weight.size(2); const int kernel_w_ = weight.size(3); if (kernel_h_ != kernel_h || kernel_w_ != kernel_w) AT_ERROR("Input shape and kernel shape wont match: (%d x %d vs %d x %d).", kernel_h_, kernel_w, kernel_h_, kernel_w_); if (channels != channels_kernel * group) AT_ERROR("Input shape and kernel channels wont match: (%d vs %d).", channels, channels_kernel * group); const int height_out = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1; const int width_out = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1; const int step=GET_STEP(batch,in_step); at::Tensor ones = at::ones({step,height_out, width_out}, input.options()); at::Tensor columns = at::zeros({channels * kernel_h * kernel_w, step*height_out * width_out},input.options()); at::Tensor grad_columns=at::zeros({channels * kernel_h * kernel_w, step*height_out * width_out},input.options()); grad_output=grad_output.view({batch/step,step,channels_out,height_out,width_out}); grad_output.transpose_(1, 2); grad_output =grad_output.view({grad_output.size(0), group, grad_output.size(1) / group, grad_output.size(2), grad_output.size(3),grad_output.size(4)}); input=input.view({batch/step,step,channels,height,width}); grad_input = grad_input.view({batch/step,step, channels, height, width}); offset=offset.view({batch/step,step,deformable_group * 2 * kernel_h * kernel_w,height_out,width_out}); grad_offset=grad_offset.view({batch/step,step,deformable_group * 2 * kernel_h * kernel_w,height_out,width_out}); for (int b = 0; b < batch/step; b++) { // divide int group grad_columns = grad_columns.view({group, grad_columns.size(0) / group, grad_columns.size(1)}); weight = weight.view({group, weight.size(0) / group, weight.size(1),weight.size(2), weight.size(3)}); for (int g = 0; g < group; g++) { grad_columns[g].addmm_(weight[g].flatten(1).transpose(0, 1),grad_output[b][g].flatten(1), 0.0f, 1.0f); } grad_columns = grad_columns.view({grad_columns.size(0) * grad_columns.size(1), grad_columns.size(2)}); weight = weight.view({weight.size(0) * weight.size(1), weight.size(2), weight.size(3), weight.size(4)}); columns.fill_(0); deform_conv2d_gradient_cuda( grad_columns,input[b],offset[b],columns, channels,height,width,height_out,width_out,kernel_h,kernel_w, pad_h,pad_w,stride_h,stride_w,dilation_h, dilation_w, step,deformable_group, grad_input[b],grad_offset[b]); columns = columns.view({group, columns.size(0) / group, columns.size(1)}); grad_weight = grad_weight.view({group, grad_weight.size(0) / group, grad_weight.size(1), grad_weight.size(2), grad_weight.size(3)}); if (with_bias) grad_bias = grad_bias.view({group, grad_bias.size(0) / group}); for (int g = 0; g < group; g++) { grad_weight[g] = grad_weight[g].flatten(1) .addmm_(grad_output[b][g].flatten(1), columns[g].transpose(0, 1),1.0f,1.0f) .view_as(grad_weight[g]); if (with_bias) { at::Tensor temp=grad_bias[g].view({-1, 1}); temp.addmm_(grad_output[b][g].flatten(1), ones.view({-1, 1}),1.0f,1.0f); grad_bias[g] =temp.view(-1); } } columns = columns.view({columns.size(0) * columns.size(1), columns.size(2)}); grad_weight = grad_weight.view({grad_weight.size(0) * grad_weight.size(1), grad_weight.size(2), grad_weight.size(3), grad_weight.size(4)}); if (with_bias) grad_bias = grad_bias.view({grad_bias.size(0) * grad_bias.size(1)}); } // batch/step group channels/group step h w grad_output = grad_output.view({grad_output.size(0) ,grad_output.size(1)*grad_output.size(2), grad_output.size(3),grad_output.size(4),grad_output.size(5)}); //grad_output=grad_output.view({batch/step,channels_kernel,step,height_out,width_out}); grad_output.transpose_(1, 2); grad_output =grad_output.view({batch,channels_out,height_out,width_out}); input=input.view({batch,channels,height,width}); grad_input = grad_input.view({batch, channels, height, width}); offset=offset.view({batch,deformable_group * 2 * kernel_h * kernel_w,height_out,width_out}); grad_offset=grad_offset.view({batch,deformable_group * 2 * kernel_h * kernel_w,height_out,width_out}); return 0; }
the_stack
#include <cstdio> #include <unistd.h> #include <sstream> #include <vector> #include <iostream> #include <cuda.h> #include <cublas_v2.h> #define CONVERT_BS 256 #define INVERSE_BS 16 void checkCUDAError (cudaError_t err, char *funcName) { if (err != cudaSuccess) { fprintf(stderr, "CUDA error in %s \n", funcName); fprintf(stderr, "CUDA error message : %s \n", cudaGetErrorString(err)); fflush(stderr); abort(); } } void checkCublasError(cublasStatus_t status, char *funcName) { if (status != CUBLAS_STATUS_SUCCESS) { fprintf(stderr, "CUBLAS error in %s \n", funcName); fprintf(stderr, "CUBLAS error message: "); switch (status) { case CUBLAS_STATUS_NOT_INITIALIZED: fprintf(stderr, "CUBLAS_STATUS_NOT_INITIALIZED\n"); break; case CUBLAS_STATUS_ALLOC_FAILED: fprintf(stderr, "CUBLAS_STATUS_ALLOC_FAILED\n"); break; case CUBLAS_STATUS_INVALID_VALUE: fprintf(stderr, "CUBLAS_STATUS_INVALID_VALUE\n"); break; case CUBLAS_STATUS_ARCH_MISMATCH: fprintf(stderr, "CUBLAS_STATUS_ARCH_MISMATCH\n"); break; case CUBLAS_STATUS_MAPPING_ERROR: fprintf(stderr, "CUBLAS_STATUS_MAPPING_ERROR\n"); break; case CUBLAS_STATUS_EXECUTION_FAILED: fprintf(stderr, "CUBLAS_STATUS_EXECUTION_FAILED\n"); break; case CUBLAS_STATUS_INTERNAL_ERROR: fprintf(stderr, "CUBLAS_STATUS_INTERNAL_ERROR\n"); break; #if (CUDA_VERSION >= 6050) case CUBLAS_STATUS_NOT_SUPPORTED: fprintf(stderr, "CUBLAS_STATUS_NOT_SUPPORTED\n"); break; case CUBLAS_STATUS_LICENSE_ERROR: fprintf(stderr, "CUBLAS_STATUS_LICENSE_ERROR\n"); break; #endif default: fprintf(stderr, "unknown\n"); } fflush(stderr); abort(); } } // Convert matrix elements from one type (Tsrc) in the source matrix to // another type (Tdest) and put them in the destination matrix // (assumed src and dest have the same dimensions) template <typename Tdest, typename Tsrc> __global__ void convert (Tdest **dest_list, Tsrc **src_list, int len) { __shared__ Tsrc *mysrc; __shared__ Tdest *mydest; if (threadIdx.x == 0) { mysrc = src_list[blockIdx.y]; mydest = dest_list[blockIdx.y]; } __syncthreads(); int i = blockIdx.x * CONVERT_BS + threadIdx.x; if (i < len) mydest[i] = (Tdest) mysrc[i]; } // Two matrix inversion functions // 1. for float matrices // useHigherPrecision = false --> single precision operations // useHigherPrecision = true --> double precision operations void cublas_inverse (cublasHandle_t handle, float *Alist_d[], float *Ainvlist_d[], float *AWorklist_d[], float *AinvWorklist_d[], int N, int rowStride, int numMats, bool useHigherPrecision) { cudaError_t err; cublasStatus_t status; // Info array tells if a matrix inversion is successful // = 0 : successful // = k : U(k,k) = 0; inversion failed int *infoArray; err = cudaMalloc((void**) &infoArray, numMats * sizeof(int)); checkCUDAError(err, "Failed to allocate memory for infoArray in cublas_inverse (cudaMalloc)"); // If double precision operations are desired... if (useHigherPrecision) { // (i) convert elements in Alist from float to double, put them in AWorklist dim3 dimBlockConvert (CONVERT_BS); dim3 dimGridConvert ((N*rowStride + (CONVERT_BS-1)) / CONVERT_BS, numMats); convert <<< dimGridConvert, dimBlockConvert >>> ((double**)AWorklist_d, Alist_d, N*rowStride); // (ii) call cublas to do matrix inversion // LU decomposition status = cublasDgetrfBatched(handle, N, (double**)AWorklist_d, rowStride, NULL, infoArray, numMats); checkCublasError(status, "Problem in LU factorization (cublasDgetrfBatched)"); // Inversion status = cublasDgetriBatched(handle, N, (double**)AWorklist_d, rowStride, NULL, (double**)AinvWorklist_d, rowStride, infoArray, numMats); checkCublasError(status, "Problem in matrix inversion (cublasDgetriBatched)"); // (iii) convert results back to single precision convert <<< dimGridConvert, dimBlockConvert >>> (Ainvlist_d, (double**)AinvWorklist_d, N*rowStride); } // else, carry out single precision operations else { // Call cublas to do matrix inversion // LU decomposition status = cublasSgetrfBatched(handle, N, Alist_d, rowStride, NULL, infoArray, numMats); checkCublasError(status, "Problem in LU factorization (cublasSgetrfBatched)"); // Inversion status = cublasSgetriBatched(handle, N, Alist_d, rowStride, NULL, Ainvlist_d, rowStride, infoArray, numMats); checkCublasError(status, "Problem in matrix inversion (cublasSgetriBatched)"); } cudaDeviceSynchronize(); // Free resources cudaFree(infoArray); } // 2. for double matrices void cublas_inverse (cublasHandle_t handle, double *Alist_d[], double *Ainvlist_d[], double *AWorklist_d[], double *AinvWorklist_d[], int N, int rowStride, int numMats, bool useHigherPrecision) { cudaError_t err; cublasStatus_t status; // Info array tells if a matrix inversion is successful // = 0 : successful // = k : U(k,k) = 0; inversion failed int *infoArray; err = cudaMalloc((void**) &infoArray, numMats * sizeof(int)); checkCUDAError(err, "Failed to allocate memory for infoArray in cublas_inverse (cudaMalloc)"); // Call cublas functions to do inversion // LU decomposition status = cublasDgetrfBatched(handle, N, Alist_d, rowStride, NULL, infoArray, numMats); checkCublasError(status, "Problem in LU factorization (cublasDgetrfBatched)"); // Inversion status = cublasDgetriBatched(handle, N, Alist_d, rowStride, NULL, Ainvlist_d, rowStride, infoArray, numMats); checkCublasError(status, "Problem in matrix inversion (cublasDgetriBatched)"); cudaDeviceSynchronize(); cudaFree(infoArray); } ////////////////////////////////////////////////////// // Test routines // ////////////////////////////////////////////////////// #ifdef CUDA_TEST_MAIN template<typename T> void test_cublas_inverse(int matSize, int numMats) { cudaError_t err; // Initialize cublas cublasHandle_t handle; cublasStatus_t status; status = cublasCreate(&handle); checkCublasError(status, "Failed to create cublas handle (cublasCreate)"); srand48((long) 12394); int N = matSize; int row_stride = (matSize+15) / 16 * 16; T **Alist, **AWorklist; T **Alist_d, **AWorklist_d; T **Clist, **CWorklist; T **Clist_d, **CWorklist_d; // Allocate arrays of pointers (one set on host, one set on device) // pointing to the starting address (on device) of each matrix and its buffer // (similar to DiracDeterminantCUDA) Alist = (T**) malloc(numMats * sizeof(T*)); err = cudaMalloc((void**) &Alist_d, numMats * sizeof(T*)); checkCUDAError(err, "Failed to allocate memory for Alist_d in test_cublas_inverse (cudaMalloc)"); AWorklist = (T**) malloc(numMats * sizeof(T*)); err = cudaMalloc((void**) &AWorklist_d, numMats * sizeof(T*)); checkCUDAError(err, "Failed to allocate memory for AWorklist_d in test_cublas_inverse (cudaMalloc)"); Clist = (T**) malloc(numMats * sizeof(T*)); err = cudaMalloc((void**) &Clist_d, numMats * sizeof(T*)); checkCUDAError(err, "Failed to allocate memory for Clist_d in test_cublas_inverse (cudaMalloc)"); CWorklist = (T**) malloc(numMats * sizeof(T*)); err = cudaMalloc((void**) &CWorklist_d, numMats * sizeof(T*)); checkCUDAError(err, "Failed to allocate memory for CWorklist_d in test_cublas_inverse (cudaMalloc)"); // Generate matrices filled with random numbers T* A = (T*) malloc(sizeof(T) * numMats * N * row_stride); for (int j=0; j<numMats; j++) for (int i=0; i<N*row_stride; i++) A[j*N*row_stride+i] = 1.0 * (drand48() - 0.5); // Allocate memory on device for each matrix for (int mat=0; mat<numMats; mat++) { err = cudaMalloc((void**) &(Alist[mat]), N * row_stride * sizeof(T)); checkCUDAError(err, "Failed to allocate memory for Alist[mat] in test_cublas_inverse (cudaMalloc)"); err = cudaMemcpyAsync(Alist[mat], &A[mat*N*row_stride], N * row_stride * sizeof(T), cudaMemcpyHostToDevice); checkCUDAError(err, "Failed to copy from A to Alist[mat] (cudaMemcpyAsync, HostToDevice)"); err = cudaMalloc((void**) &(AWorklist[mat]), 2 * N * row_stride * sizeof(T)); checkCUDAError(err, "Failed to allocate memory for AWorklist[mat] in test_cublas_inverse (cudaMalloc)"); err = cudaMalloc((void**) &(Clist[mat]), N * row_stride * sizeof(T)); checkCUDAError(err, "Failed to allocate memory for Clist[mat] in test_cublas_inverse (cudaMalloc)"); err = cudaMalloc((void**) &(CWorklist[mat]), 2 * N * row_stride * sizeof(T)); checkCUDAError(err, "Failed to allocate memory for CWorklist[mat] in test_cublas_inverse (cudaMalloc)"); } // Copy the starting address of each matrix err = cudaMemcpyAsync (Alist_d, Alist, numMats * sizeof(T*), cudaMemcpyHostToDevice); checkCUDAError(err, "Failed to copy from Alist to Alist_d (cudaMemcpyAsync, HostToDevice)"); err = cudaMemcpyAsync (AWorklist_d, AWorklist, numMats * sizeof(T*), cudaMemcpyHostToDevice); checkCUDAError(err, "Failed to copy from AWorklist to AWorklist_d (cudaMemcpyAsync, HostToDevice)"); err = cudaMemcpyAsync (Clist_d, Clist, numMats * sizeof(T*), cudaMemcpyHostToDevice); checkCUDAError(err, "Failed to copy from Clist to Clist_d (cudaMemcpyAsync, HostToDevice)"); err = cudaMemcpyAsync (CWorklist_d, CWorklist, numMats * sizeof(T*), cudaMemcpyHostToDevice); checkCUDAError(err, "Failed to copy from CWorklist to CWorklist_d (cudaMemcpyAsync, HostToDevice)"); cudaDeviceSynchronize(); clock_t start = clock(); // Call cublas functions to do inversion cublas_inverse (handle, Alist_d, Clist_d, AWorklist_d, CWorklist_d, N, row_stride, numMats, true); cudaDeviceSynchronize(); clock_t end = clock(); double t = double(end-start) / double(CLOCKS_PER_SEC) / double(numMats); double rate = 1.0 / t; fprintf (stderr, "Rate is %1.3f matrix inversions per second.\n", rate); // Copy A^(-1) back to host memory Ainv; one matrix at a time // Calculate error of A^(-1)A from unit matrix I for (int mat=0; mat<numMats; mat++) { T Ainv[N*row_stride]; err = cudaMemcpy(Ainv, Clist[mat], N * row_stride * sizeof(T), cudaMemcpyDeviceToHost); checkCUDAError(err, "Failed to copy from Clist[mat] to Ainv (cudaMemcpy, DeviceToHost)"); double error = 0.0; for (int i=0; i<N; i++) for (int j=0; j<N; j++) { double val = 0.0; for (int k=0; k<N; k++) val += Ainv[i*row_stride+k] * A[mat*N*row_stride+k*row_stride+j]; double diff = (i==j) ? (1.0f - val) : val; error += diff * diff; } fprintf (stderr, "error = %1.8e\n", sqrt(error/(double)(N*N))); } // Finalize cublas status = cublasDestroy(handle); checkCublasError(status, "Failed to destroy cublas handle (cublasDestroy)"); // Free resources on both host and device for (int mat=0; mat<numMats; mat++) { cudaFree(Alist[mat]); cudaFree(Clist[mat]); cudaFree(AWorklist[mat]); cudaFree(CWorklist[mat]); } cudaFree(Alist_d); cudaFree(Clist_d); cudaFree(AWorklist_d); cudaFree(CWorklist_d); free(Alist); free(Clist); free(AWorklist); free(CWorklist); free(A); // Reset device. Required for memory leak debugging cudaDeviceReset(); } int main(int argc, char** argv) { int matSize = 0; int numMats = 0; if (argc == 3) { matSize = atoi(argv[1]); numMats = atoi(argv[2]); } else { printf("Usage: ./cuda_inverse [matrix size] [number of matrices]\n"); exit(1); } test_cublas_inverse<double>(matSize, numMats); test_cublas_inverse<float>(matSize, numMats); return 0; } #endif
the_stack
<<<<<<< HEAD:utils/inference.cu #include "inference.cuh" template <typename T> void BERT_Attention (global_manager *handle, T* &tensor, size_t num_layer, int* attention_mask) { ======= #include "../ops/CrossEntropyLoss.cu" #include "../ops/elementwise.cu" #include "../ops/embedding.cu" #include "../ops/layernorm.cu" #include "../ops/linear.cu" #include "../ops/matmul.cu" #include "../ops/softmax.cu" #include "../utils/common.h" #include "../utils/manager.h" template <typename T> void BERT_Attention(global_manager *handle, T *&tensor, size_t num_layer, int *attention_mask = nullptr) { >>>>>>> 5c82c55b75c439d7624979abda314f36b2398cb8:cuda/utils/inference.cu dict_weights weights = handle->weights; size_t batchsize = handle->batchsize; size_t seq_length = handle->seq_length; size_t hidden_size = handle->hidden_size; size_t num_attention_heads = handle->num_attention_heads; T *query; query = handle->global_malloc_manage_float.get_new_head_point(3 * batchsize * seq_length * hidden_size); //key = handle->global_malloc_manage_float.get_new_head_point(batchsize*seq_length*hidden_size); //val = handle->global_malloc_manage_float.get_new_head_point(batchsize*seq_length*hidden_size); /* Linear<T>(handle, query, tensor, weights["attention_self_query_kernel"][num_layer], weights["attention_self_query_bias"][num_layer], batchsize*seq_length, hidden_size, hidden_size); Linear<T>(handle, key, tensor, weights["attention_self_key_kernel"][num_layer], weights["attention_self_key_bias"][num_layer], batchsize*seq_length, hidden_size, hidden_size); Linear<T>(handle, val, tensor, weights["attention_self_value_kernel"][num_layer], weights["attention_self_value_bias"][num_layer], batchsize*seq_length, hidden_size, hidden_size); //debug_tensor_gpu<T>(std::string("query"), query, 10, hidden_size, 11*batchsize); */ Batch_Linear<T>(handle, query, tensor, weights["attention_self_query_kernel"][num_layer], weights["attention_self_query_bias"][num_layer], weights["attention_self_key_kernel"][num_layer], weights["attention_self_key_bias"][num_layer], weights["attention_self_value_kernel"][num_layer], weights["attention_self_value_bias"][num_layer], batchsize * seq_length, hidden_size, hidden_size); //debug_tensor_gpu<T>(std::string("query"), query, 10, hidden_size, batchsize); T *head_query, *head_key, *head_val; head_query = handle->global_malloc_manage_float.get_new_head_point(batchsize * seq_length * hidden_size); head_key = handle->global_malloc_manage_float.get_new_head_point(batchsize * seq_length * hidden_size); head_val = handle->global_malloc_manage_float.get_new_head_point(batchsize * seq_length * hidden_size); dim3 threads(hidden_size, 1, 1); dim3 blocks(min(long(65535), batchsize *seq_length), 1, 1); FusionTranspose<<<blocks, threads, 0, handle->get_cal_stream()>>>( head_query, query, 3, batchsize, seq_length, num_attention_heads, batchsize * seq_length, batchsize * seq_length * hidden_size, true); T *probs; probs = handle->global_malloc_manage_float.get_new_head_point(batchsize * num_attention_heads * seq_length * seq_length); std::vector<size_t> a_shape = {batchsize * num_attention_heads, seq_length, hidden_size / num_attention_heads}; std::vector<size_t> b_shape = {batchsize * num_attention_heads, seq_length, hidden_size / num_attention_heads}; std::vector<size_t> c_shape = {batchsize * num_attention_heads, seq_length, seq_length}; matmul(handle->handle, head_query, a_shape, head_key, b_shape, probs, c_shape, false, true); //debug_tensor_gpu<T>(std::string("matmul key and query"), probs, 10, seq_length, 12*2*batchsize); dim3 div_threads(1024, 1, 1); dim3 div_blocks(min((long)65535, seq_length * seq_length * batchsize * num_attention_heads / 1024) + 1, 1, 1); //debug_tensor_gpu<int>(std::string("attention_mask"), attention_mask, 11, 11, batchsize); if (attention_mask == nullptr) { Attention_Mask_Add_Merge_div_only_div<<<div_blocks, div_threads, 0, handle->get_cal_stream()>>>( probs, attention_mask, 8.0, batchsize * seq_length * num_attention_heads * seq_length, batchsize, seq_length); } else { Attention_Mask_Add_Merge_div_only_Add<<<div_blocks, div_threads, 0, handle->get_cal_stream()>>>( probs, attention_mask, 8.0, batchsize * seq_length * num_attention_heads * seq_length, batchsize, seq_length); } //debug_tensor_gpu<T>(std::string("After mask_add"), probs, 11, 11*11, 12 * batchsize); HostApplySoftmax(handle, probs, batchsize * num_attention_heads * seq_length, seq_length); //debug_tensor_gpu<T>(std::string("Softmax"), probs, 10, seq_length*seq_length, batchsize); T *attention; attention = handle->global_malloc_manage_float.get_new_head_point(batchsize * hidden_size * seq_length); a_shape = {batchsize * num_attention_heads, seq_length, seq_length}; b_shape = {batchsize * num_attention_heads, seq_length, hidden_size / num_attention_heads}; c_shape = {batchsize * num_attention_heads, seq_length, hidden_size / num_attention_heads}; matmul(handle->handle, probs, a_shape, head_val, b_shape, attention, c_shape); T *hidden_states, *temp; hidden_states = handle->global_malloc_manage_float.get_new_head_point(batchsize * hidden_size * seq_length); temp = handle->global_malloc_manage_float.get_new_head_point(batchsize * hidden_size * seq_length); FusionTranspose<<<blocks, threads, 0, handle->get_cal_stream()>>>( hidden_states, attention, 1, batchsize, seq_length, num_attention_heads, batchsize * seq_length, batchsize * hidden_size * seq_length, false); Linear<T>(handle, temp, hidden_states, weights["attention_output_dense_kernel"][num_layer], weights["attention_output_dense_bias"][num_layer], batchsize * seq_length, hidden_size, hidden_size, false); hidden_states = temp; T *gamma = weights["attention_output_LayerNorm_gamma"][num_layer]; T *beta = weights["attention_output_LayerNorm_beta"][num_layer]; HostApplyLayerNorm<T, T>(handle, tensor, tensor, batchsize * seq_length, hidden_size, 1e-12, gamma, beta, hidden_states); } template <typename T> void BERT_Intermediate(global_manager *handle, T *tensor, T *intermediate, size_t num_layer) { dict_weights weights = handle->weights; size_t batchsize = handle->batchsize; size_t seq_length = handle->seq_length; size_t hidden_size = handle->hidden_size; size_t intermediate_size = handle->intermediate_size; Linear<T>(handle, intermediate, tensor, weights["intermediate_dense_kernel"][num_layer], weights["intermediate_dense_bias"][num_layer], batchsize * seq_length, hidden_size, intermediate_size); dim3 threads(1024, 1, 1); dim3 blocks(min((long)65535, intermediate_size * seq_length * batchsize / 1024) + 1, 1, 1); BertGelu<<<blocks, threads, 0, handle->get_cal_stream()>>>( intermediate, intermediate_size * seq_length * batchsize); } template <typename T> void BERT_Output(global_manager *handle, T *tensor, T *intermediate, size_t num_layer) { dict_weights weights = handle->weights; size_t batchsize = handle->batchsize; size_t seq_length = handle->seq_length; size_t hidden_size = handle->hidden_size; size_t intermediate_size = handle->intermediate_size; //dump_tensor<float>(std::string("transpose_output_"+std::to_string(num_layer)), hidden_states, batchsize, seq_length, handle->hidden_size); T *temp; temp = handle->global_malloc_manage_float.get_new_head_point(batchsize * seq_length * intermediate_size); Linear<T>(handle, temp, intermediate, weights["output_dense_kernel"][num_layer], weights["output_dense_bias"][num_layer], batchsize * seq_length, intermediate_size, hidden_size); //dim3 threads(1024, 1, 1); //dim3 blocks(seq_length*batchsize*hidden_size / 1024 + 1, 1, 1); //BertAdd<<<blocks, threads>>>(tensor, temp, batchsize*seq_length*hidden_size); T *gamma = weights["output_LayerNorm_gamma"][num_layer]; T *beta = weights["output_LayerNorm_beta"][num_layer]; HostApplyLayerNorm<T, T>(handle, tensor, tensor, batchsize * seq_length, hidden_size, 1e-12, gamma, beta, temp); } template <typename T> void BERT_Layer(global_manager *handle, T *&tensor, size_t num_layer, <<<<<<< HEAD:utils/inference.cu int* attention_mask) { ======= int *attention_mask = nullptr) { >>>>>>> 5c82c55b75c439d7624979abda314f36b2398cb8:cuda/utils/inference.cu handle->global_malloc_manage_float.record_layer_start(); BERT_Attention<T>(handle, tensor, num_layer, attention_mask); //ebug_tensor_gpu<T>(std::string("bert_attention_output"), tensor, 10, handle->hidden_size, handle->batchsize); T *intermediate; intermediate = handle->global_malloc_manage_float.get_new_head_point( handle->batchsize * handle->seq_length * handle->intermediate_size); BERT_Intermediate<T>(handle, tensor, intermediate, num_layer); //debug_tensor_gpu<T>(std::string("bert_intermediate_output"), intermediate, 10, handle->intermediate_size, handle->batchsize); BERT_Output<T>(handle, tensor, intermediate, num_layer); cudaStreamSynchronize(handle->get_cal_stream()); handle->global_malloc_manage_float.reuse_layer_mem(); } template <typename T> void BERT_Pooler(global_manager *handle, T *&tensor, T *&pooled_output) { size_t batchsize = handle->batchsize; size_t seq_length = handle->seq_length; size_t hidden_size = handle->hidden_size; T *first_token; first_token = handle->global_malloc_manage_float.get_new_head_point(batchsize * hidden_size); for (int i = 0; i < batchsize; i++) { checkCudaErrors(cudaMemcpyAsync(first_token + i * hidden_size, tensor + i * hidden_size * seq_length, hidden_size * sizeof(T), cudaMemcpyDeviceToDevice, handle->get_cal_stream())); } std::vector<std::string> keys = {"pooler_dense_kernel"}; T *kernel = look_up_tts(handle->tts, keys)->gpu_mem; keys = {"pooler_dense_bias"}; T *bias = look_up_tts(handle->tts, keys)->gpu_mem; Linear<T>(handle, pooled_output, first_token, kernel, bias, batchsize, hidden_size, hidden_size, false); dim3 threads(1024, 1, 1); dim3 blocks(min((long)65535, hidden_size * batchsize / 1024) + 1, 1, 1); BertTanh<<<blocks, threads, 0, handle->get_cal_stream()>>>( pooled_output, hidden_size * batchsize); } template <typename T> <<<<<<< HEAD:utils/inference.cu void BERT_Inference (global_manager *handle, T* &tensor, T* &pooled_output, int* words, int* token_types, size_t batchsize, size_t seq_length, int* attention_mask) { ======= void BERT_Inference(global_manager *handle, T *&tensor, T *&pooled_output, int *words, int *token_types, size_t batchsize, size_t seq_length, int *attention_mask = nullptr) { >>>>>>> 5c82c55b75c439d7624979abda314f36b2398cb8:cuda/utils/inference.cu handle->set_scale(batchsize, seq_length); tensor = handle->global_malloc_manage_float.get_new_head_point( batchsize * seq_length * handle->hidden_size); pooled_output = handle->global_malloc_manage_float.get_new_head_point( batchsize * handle->hidden_size); HostApplyEmbeddings<T>(handle, tensor, words, token_types, attention_mask); for (int i = 0; i < 1; i++) { //handle->num_hidden_layers BERT_Layer<T>(handle, tensor, i, attention_mask); } BERT_Pooler<T>(handle, tensor, pooled_output); //dump_tensor<T>(std::string("pooler_output"), tensor, batchsize, handle->hidden_size); } <<<<<<< HEAD:utils/inference.cu Retval BERT_Inference (global_manager * handle, int* words, int* token_types, int batchsize, int seq_length, int* attention_mask) { ======= extern "C" Retval BERT_Inference(global_manager *handle, int *words, int *token_types, int batchsize, int seq_length, int *attention_mask = nullptr) { >>>>>>> 5c82c55b75c439d7624979abda314f36b2398cb8:cuda/utils/inference.cu Retval ret; handle->set_scale(batchsize, seq_length); handle->reset(); //std::cout<<"INFO: BERT_Inference for Batchsize=" // <<batchsize<<" and Seq_Length="<<seq_length<<std::endl; ret.tensor = handle->global_malloc_manage_float.get_new_head_point( batchsize * seq_length * handle->hidden_size); ret.pooled_output = handle->global_malloc_manage_float.get_new_head_point( batchsize * handle->hidden_size); HostApplyEmbeddings<float>(handle, ret.tensor, words, token_types, attention_mask); //dump_tensor<float>(std::string("embedding_out"), ret.tensor, batchsize, seq_length, handle->hidden_size); for (int i = 0; i < handle->num_hidden_layers; i++) { //handle->num_hidden_layers BERT_Layer<float>(handle, ret.tensor, i, attention_mask); //dump_tensor<float>(std::string("layer_output_"+std::to_string(i)), ret.tensor, batchsize, seq_length, handle->hidden_size); } BERT_Pooler<float>(handle, ret.tensor, ret.pooled_output); debug_tensor_gpu<float>(std::string("pooler_output"), ret.pooled_output, 10, handle->hidden_size); return ret; } template <typename T, typename U> T *classify_inference(global_manager *handle, U *classes, T *pooled_output, size_t num_classes) { size_t batchsize = handle->batchsize; size_t hidden_size = handle->hidden_size; T *linear_output; linear_output = handle->global_malloc_manage_float.get_new_head_point(batchsize * num_classes); std::vector<std::string> keys = {"classifier_weight"}; T *weights = look_up_tts(handle->tts, keys)->gpu_mem; keys = {"classifier_bias"}; T *bias = look_up_tts(handle->tts, keys)->gpu_mem; Linear<T>(handle, linear_output, pooled_output, weights, bias, batchsize, hidden_size, num_classes, false); T *tmp_linear_output; tmp_linear_output = handle->global_malloc_manage_float.get_new_head_point(batchsize * num_classes); checkCudaErrors(cudaMemcpyAsync(tmp_linear_output, linear_output, batchsize * num_classes * sizeof(T), cudaMemcpyDeviceToDevice)); U *calsses_gpu; calsses_gpu = handle->global_malloc_manage_int.get_new_head_point(batchsize); checkCudaErrors(cudaMemcpyAsync(calsses_gpu, classes, batchsize * sizeof(int), cudaMemcpyHostToDevice)); T *crossEntropyLoss; crossEntropyLoss = handle->global_malloc_manage_float.get_new_head_point(batchsize + 1); debug_tensor_gpu<float>(std::string("linear_output"), linear_output, 2, 2, batchsize); HostApplyCrossEntropyLoss<T, U>(handle, crossEntropyLoss, linear_output, calsses_gpu, batchsize, num_classes); debug_tensor_gpu<float>(std::string("CrossEntropyLoss_output"), crossEntropyLoss, batchsize + 1, batchsize + 1); T *grad_CrossEntropyLoss_input; grad_CrossEntropyLoss_input = handle->global_malloc_manage_float.get_new_head_point(batchsize * num_classes); T *dout_gpu; dout_gpu = handle->global_malloc_manage_float.get_new_head_point(batchsize); T *dout = (T *)malloc(batchsize * sizeof(T)); for (int i = 0; i < batchsize; i++) dout[i] = 1.0; checkCudaErrors(cudaMemcpyAsync(dout_gpu, dout, batchsize * sizeof(T), cudaMemcpyHostToDevice)); HostApplyCrossEntropyLossGradient<T, U>(handle, dout_gpu, tmp_linear_output, batchsize, num_classes, calsses_gpu, grad_CrossEntropyLoss_input); T *grad_Linear_input; grad_Linear_input = handle->global_malloc_manage_float.get_new_head_point(batchsize * hidden_size); T *grad_weights; grad_weights = handle->global_malloc_manage_float.get_new_head_point(hidden_size * num_classes); T *grad_bias; grad_bias = handle->global_malloc_manage_float.get_new_head_point(batchsize * num_classes); HostApplyLinearGradient<T>(handle, grad_CrossEntropyLoss_input, pooled_output, weights, bias, batchsize, hidden_size, num_classes, grad_Linear_input, grad_weights, grad_bias); // debug_tensor_gpu<float>(std::string("grad_Linear_input"), grad_Linear_input, hidden_size, hidden_size); free(dout); return crossEntropyLoss; } template float* classify_inference<float>(global_manager * handle, float* pooled_output, size_t num_classes);
the_stack
#include "ew_op_gpu.h" #include "gpu_hmma.h" #include <stdio.h> typedef unsigned long long uint64; template <uint UNROLL, uint BLOCKS, uint BSIZE, typename T, typename V2, typename MASKT> __global__ void __launch_bounds__(1024,BLOCKS) bst_masked_softmax( const uint2* __restrict__ Lut, const MASKT* __restrict__ Mask, const bhalf* __restrict__ X, T* Y, uint blocks, uint szLut, uint szMask, uint szHead, uint szBatch, float scale, uint shfl_init, uint max_lut, uint use_mask) { __shared__ float Max[32]; __shared__ float Sum[32]; uint64* LutMask64 = (uint64*)&Sum[32]; uint* LutMask32 = (uint*)&Sum[32]; uint* LutOffset = BSIZE == 64 ? (uint*)&LutMask64[max_lut] : &LutMask32[max_lut]; uint tid = threadIdx.x; uint idx_Q = blockIdx.x / BSIZE; // Q dim uint idx_q = blockIdx.x % BSIZE; // Q dim uint idx_B = blockIdx.y; // batch dim uint idx_H = blockIdx.z; // head dim // each head can optionally have its own lut Lut += idx_H * szLut; Mask += idx_H * szMask + idx_q * blocks; uint2 lut_head = Lut[idx_Q]; if (tid < 32) { // Allows non-power of 2 threads to work Max[tid] = -FLT_MAX; Sum[tid] = 0.0f; } // prefetch the lut data into shared uint lut_offset = lut_head.x; uint lut_size = lut_head.y; Lut += lut_offset; #pragma unroll 1 for (uint i = tid; i < max_lut; i += blockDim.x) { if (BSIZE == 64) { uint64 mask = 0; if (i < lut_size) { uint2 entry = Lut[i]; uint blk_id = entry.x; LutOffset[i] = blk_id * BSIZE*BSIZE; mask = use_mask ? __ldg(Mask + blk_id) : 0xffffffffffffffff; } LutMask64[i] = mask; } else { uint mask = 0; if (i < lut_size) { uint2 entry = Lut[i]; uint blk_id = entry.x; LutOffset[i] = blk_id * BSIZE*BSIZE; mask = use_mask ? (uint)__ldg(Mask + blk_id) : 0xffffffff; } LutMask32[i] = mask; } } __syncthreads(); // trim warps that we know are out of lut range if ((tid & (1024-32))*2*UNROLL < lut_size*BSIZE) { uint lut_idx = (tid & (1024 - BSIZE/2))*2*UNROLL/BSIZE; uint tidx = (tid % (BSIZE/2))*2; uint offset = idx_B*szBatch + idx_H*szHead + idx_q*BSIZE + tidx + LutOffset[lut_idx]; X += offset; asm("mov.b64 %0, %0;" : "+l"(X) : ); bhalf2 xval[UNROLL]; #pragma unroll for (uint i = 0; i < UNROLL; i++) { ew_set(xval[i], 0xff80ff80); //-inf, -inf if (lut_idx + i < lut_size) xval[i] = __ldg((const bhalf2*)(X + i*BSIZE*BSIZE)); } // split the 64 bit mask by half warp uint tid16 = BSIZE == 64 ? (tid & 16)/16 : 0; uint bit0 = 1 << (tidx - tid16*32); uint bit1 = bit0 << 1; uint inf = 0xff80; #pragma unroll for (int i = 0; i < UNROLL; i++) { uint mask = LutMask32[(lut_idx + i)*(BSIZE == 64 ? 2 : 1) + tid16]; asm("{ \n\t" ".reg .pred p0, p1; \n\t" "setp.eq.u32 p0, %2, 0; \n\t" // if ((mask & bit0) == 0) "setp.eq.u32 p1, %3, 0; \n\t" // if ((mask & bit1) == 0) "@p0 prmt.b32 %0, %0, %1, 0x3254;\n\t" // set -inf to lo bits "@p1 prmt.b32 %0, %0, %1, 0x5410;\n\t" // set -inf to hi bits "}" : "+r"(xval[i].x) : "r"(inf), "r"(mask & bit0), "r"(mask & bit1)); } // reduce within thread float Xmax[UNROLL]; for (int i = 0; i < UNROLL; i++) Xmax[i] = ew_max(to_float(xval[i])); float xmax = Xmax[0]; for (int i = 1; i < UNROLL; i++) xmax = fmaxf(Xmax[i], xmax); // reduce within warp for (int i = 16; i > 0; i >>= 1) xmax = fmaxf(xmax, shfl_xor(xmax, i)); if (blockDim.x > 32) { // first thread of each warp store to shared if ((tid & 31) == 0) Max[tid/32] = xmax; __syncthreads(); if (tid < 32) { // first warp loads all prior reductions xmax = Max[tid]; // reduce within this last warp #pragma unroll 1 for (uint i = shfl_init; i > 0; i >>= 1) xmax = fmaxf(xmax, shfl_xor(xmax, i)); // final reduction to shared Max[tid] = xmax; } __syncthreads(); xmax = Max[0]; } // subtract xmax and compute exponent float exp_sum = 0; for (int i = 0; i < UNROLL; i++) { // use fast approx math: e**x == 2**(x * log2(e)) // log2(e) is included in scale factor float2 Xval = ew_ex2(ew_mul(ew_sub(to_float(xval[i]), xmax), scale)); exp_sum += ew_sum(Xval); xval[i] = to_bhalf(Xval); } // reduce within warp for (int i = 16; i > 0; i >>= 1) exp_sum += shfl_xor(exp_sum, i); if (blockDim.x > 32) { // first thread of each warp store to shared if ((tid & 31) == 0) Sum[tid/32] = exp_sum; __syncthreads(); if (tid < 32) { // first warp loads all prior reductions exp_sum = Sum[tid]; // reduce within this last warp #pragma unroll 1 for (uint i = shfl_init; i > 0; i >>= 1) exp_sum += shfl_xor(exp_sum, i); // final reduction to shared Sum[tid] = exp_sum; } __syncthreads(); exp_sum = Sum[0]; } float rcp_exp_sum = ew_rcp(exp_sum); Y += offset; asm("mov.b64 %0, %0;" : "+l"(Y) : ); #pragma unroll for (int i = 0; i < UNROLL; i++) { float2 y2 = ew_mul(to_float(xval[i]), rcp_exp_sum); store((V2*)Y, y2, i*BSIZE*BSIZE/2, lut_idx + i < lut_size); } } } template <uint UNROLL, uint BLOCKS, uint BSIZE, typename T, typename V2> __global__ void __launch_bounds__(1024,BLOCKS) bst_masked_softmax_grad( const uint2* __restrict__ Lut, const T* __restrict__ DY, const T* __restrict__ Y, T* DX, uint szLut, uint szHead, uint szBatch, float scale, uint shfl_init) { __shared__ float Sum[32]; uint* LutOffset = (uint*)&Sum[32]; uint tid = threadIdx.x; uint idx_Q = blockIdx.x / BSIZE; uint idx_q = blockIdx.x % BSIZE; uint idx_B = blockIdx.y; // batch dim uint idx_H = blockIdx.z; // head dim // each head can optionally have its own lut Lut += idx_H * szLut; uint2 lut_head = Lut[idx_Q]; if (tid < 32) Sum[tid] = 0.0f; // prefetch the lut data into shared uint lut_offset = lut_head.x; uint lut_size = lut_head.y; Lut += lut_offset; #pragma unroll 1 for (uint i = tid; i < lut_size; i += blockDim.x) LutOffset[i] = Lut[i].x * BSIZE*BSIZE; __syncthreads(); // trim warps that we know are out of lut range if ((tid & (1024-32))*2*UNROLL < lut_size*BSIZE) { uint lut_idx = (tid & (1024 - BSIZE/2))*2*UNROLL/BSIZE; uint tidx = (tid % (BSIZE/2))*2; uint offset = idx_B*szBatch + idx_H*szHead + idx_q*BSIZE + tidx + LutOffset[lut_idx]; DY += offset; Y += offset; asm("mov.b64 %0, %0;" : "+l"(DY) : ); asm("mov.b64 %0, %0;" : "+l"(Y) : ); V2 dy[UNROLL], y[UNROLL]; #pragma unroll for (uint i = 0; i < UNROLL; i++) { ew_set(dy[i], 0); ew_set( y[i], 0); if (lut_idx + i < lut_size) { dy[i] = __ldg((const V2*)(DY + i*BSIZE*BSIZE)); y[i] = __ldg((const V2*)( Y + i*BSIZE*BSIZE)); } } // compute dy * y and start reduction float sum_dyy = 0.0f; for (int i = 0; i < UNROLL; i++) sum_dyy += ew_sum(ew_mul(to_float(dy[i]), to_float(y[i]))); // reduce within warp for (int i = 16; i > 0; i >>= 1) sum_dyy += shfl_xor(sum_dyy, i); if (blockDim.x > 32) { // first thread of each warp store to shared if ((tid & 31) == 0) Sum[tid/32] = sum_dyy; __syncthreads(); if (tid < 32) { // first warp loads all prior reductions sum_dyy = Sum[tid]; // reduce within this last warp #pragma unroll 1 for (uint i = shfl_init; i > 0; i >>= 1) sum_dyy += shfl_xor(sum_dyy, i); // final reduction to shared Sum[tid] = sum_dyy; } __syncthreads(); sum_dyy = Sum[0]; } DX += offset; //asm("mov.b64 %0, %0;" : "+l"(DX) : ); #pragma unroll for (uint i = 0; i < UNROLL; i++) { // dx = (dy - sum_dyy) * y * scale float2 dx2 = ew_mul(ew_mul(ew_sub(to_float(dy[i]), sum_dyy), to_float(y[i])), scale); store((V2*)DX, dx2, i*BSIZE*BSIZE/2, lut_idx + i < lut_size); // asm ( // "{ \n\t" // ".reg .pred p; \n\t" // ".reg .s64 DX, offset; \n\t" // "setp.lt.u32 p, %3, %4; \n\t" // "mov.b64 offset, {%1, 0}; \n\t" // "add.s64 DX, %0, offset; \n\t" // "@p st.global.wb.u32 [DX], %2; \n\t" // "}" :: "l"(DX), "r"(i*BSIZE*BSIZE*2), "r"(dx.x), "r"(lut_idx + i), "r"(lut_size)); } } } #define LOG2e 1.4426950408889634f typedef unsigned char uchar; template <typename T, typename V> bool BlocksparseMaskedSoftmax(CUstream stream, const uint2* lut, const char* mask, const bhalf* x, T* y, uint block_size, uint blocks, uint batch_dim, uint head_dim, uint ctx_blks, uint lut_heads, uint lut_dim, uint max_lut, uint mask_heads, float scale) { uint szLut = lut_heads > 1 ? lut_dim : 0; uint szMask = mask_heads > 1 ? blocks * block_size : 0; uint gridQ = ctx_blks * block_size; uint szHead = blocks * block_size * block_size; uint szBatch = head_dim * szHead; uint maxK = max_lut * block_size; //cuMemsetD16Async((CUdeviceptr)c, 0, szBatch*batch_dim, stream); // combine scaling with fast exp(x) compute scale *= LOG2e; dim3 grid(gridQ, batch_dim, head_dim); uint unroll, threads; if (maxK > 1024*16) { unroll = 16; threads = CEIL_DIV(maxK, 32*16*2) * 32; } else if (maxK > 1024* 8) { unroll = 8; threads = CEIL_DIV(maxK, 32* 8*2) * 32; } else { unroll = 4; threads = CEIL_DIV(maxK, 32* 4*2) * 32; } uint bshift = block_size == 64 ? 5 : block_size == 32 ? 4 : block_size == 16 ? 3 : 2; uint shfl_init = THREAD_POW2(threads) / 64; uint lut_max = (threads * unroll) >> bshift; uint shared = lut_max * 8; if (block_size == 64) { shared = lut_max * 12; if (unroll == 16) bst_masked_softmax<16,1,64,T,V,uint64><<<grid,threads,shared,stream>>>(lut, (const uint64*)mask, x, y, blocks, szLut, szMask, szHead, szBatch, scale, shfl_init, lut_max, mask != NULL); else if (unroll == 8) bst_masked_softmax< 8,2,64,T,V,uint64><<<grid,threads,shared,stream>>>(lut, (const uint64*)mask, x, y, blocks, szLut, szMask, szHead, szBatch, scale, shfl_init, lut_max, mask != NULL); else // (unroll == 4) bst_masked_softmax< 4,2,64,T,V,uint64><<<grid,threads,shared,stream>>>(lut, (const uint64*)mask, x, y, blocks, szLut, szMask, szHead, szBatch, scale, shfl_init, lut_max, mask != NULL); } else if (block_size == 32) { if (unroll == 16) bst_masked_softmax<16,1,32,T,V, uint><<<grid,threads,shared,stream>>>(lut, (const uint*)mask, x, y, blocks, szLut, szMask, szHead, szBatch, scale, shfl_init, lut_max, mask != NULL); else if (unroll == 8) bst_masked_softmax< 8,2,32,T,V, uint><<<grid,threads,shared,stream>>>(lut, (const uint*)mask, x, y, blocks, szLut, szMask, szHead, szBatch, scale, shfl_init, lut_max, mask != NULL); else // (unroll == 4) bst_masked_softmax< 4,2,32,T,V, uint><<<grid,threads,shared,stream>>>(lut, (const uint*)mask, x, y, blocks, szLut, szMask, szHead, szBatch, scale, shfl_init, lut_max, mask != NULL); } else if (block_size == 16) { if (unroll == 16) bst_masked_softmax<16,1,16,T,V,ushort><<<grid,threads,shared,stream>>>(lut, (const ushort*)mask, x, y, blocks, szLut, szMask, szHead, szBatch, scale, shfl_init, lut_max, mask != NULL); else if (unroll == 8) bst_masked_softmax< 8,2,16,T,V,ushort><<<grid,threads,shared,stream>>>(lut, (const ushort*)mask, x, y, blocks, szLut, szMask, szHead, szBatch, scale, shfl_init, lut_max, mask != NULL); else // (unroll == 4) bst_masked_softmax< 4,2,16,T,V,ushort><<<grid,threads,shared,stream>>>(lut, (const ushort*)mask, x, y, blocks, szLut, szMask, szHead, szBatch, scale, shfl_init, lut_max, mask != NULL); } else { if (unroll == 16) bst_masked_softmax<16,1, 8,T,V, uchar><<<grid,threads,shared,stream>>>(lut, (const uchar*)mask, x, y, blocks, szLut, szMask, szHead, szBatch, scale, shfl_init, lut_max, mask != NULL); else if (unroll == 8) bst_masked_softmax< 8,2, 8,T,V, uchar><<<grid,threads,shared,stream>>>(lut, (const uchar*)mask, x, y, blocks, szLut, szMask, szHead, szBatch, scale, shfl_init, lut_max, mask != NULL); else // (unroll == 4) bst_masked_softmax< 4,2, 8,T,V, uchar><<<grid,threads,shared,stream>>>(lut, (const uchar*)mask, x, y, blocks, szLut, szMask, szHead, szBatch, scale, shfl_init, lut_max, mask != NULL); } return true; } template bool BlocksparseMaskedSoftmax<ehalf,ehalf2>(CUstream stream, const uint2* lut, const char* mask, const bhalf* x, ehalf* y, uint block_size, uint blocks, uint batch_dim, uint head_dim, uint ctx_blks, uint lut_heads, uint lut_dim, uint max_lut, uint mask_heads, float scale); template bool BlocksparseMaskedSoftmax<bhalf,bhalf2>(CUstream stream, const uint2* lut, const char* mask, const bhalf* x, bhalf* y, uint block_size, uint blocks, uint batch_dim, uint head_dim, uint ctx_blks, uint lut_heads, uint lut_dim, uint max_lut, uint mask_heads, float scale); template <typename T, typename V> bool BlocksparseMaskedSoftmaxGrad(CUstream stream, const uint2* lut, const T* dy, const T* y, T* dx, uint block_size, uint blocks, uint batch_dim, uint head_dim, uint ctx_blks, uint lut_heads, uint lut_dim, uint max_lut, float scale) { uint szLut = lut_heads > 1 ? lut_dim : 0; uint gridQ = ctx_blks * block_size; uint szHead = blocks * block_size * block_size; uint szBatch = head_dim * szHead; uint maxK = max_lut * block_size; //cuMemsetD16Async((CUdeviceptr)c, 0, szBatch*batch_dim, stream); dim3 grid(gridQ, batch_dim, head_dim); uint unroll, threads; if (maxK > 1024*16) { unroll = 16; threads = CEIL_DIV(maxK, 32*16*2) * 32; } else if (maxK > 1024* 8) { unroll = 8; threads = CEIL_DIV(maxK, 32* 8*2) * 32; } else { unroll = 4; threads = CEIL_DIV(maxK, 32* 4*2) * 32; } uint bshift = block_size == 64 ? 5 : block_size == 32 ? 4 : block_size == 16 ? 3 : 2; uint shfl_init = THREAD_POW2(threads) / 64; uint lut_max = (threads * unroll) >> bshift; uint shared = lut_max * 4; if (unroll == 16) { if (block_size == 64) bst_masked_softmax_grad<16,1,64,T,V><<<grid,threads,shared,stream>>>(lut, dy, y, dx, szLut, szHead, szBatch, scale, shfl_init); else if (block_size == 32) bst_masked_softmax_grad<16,1,32,T,V><<<grid,threads,shared,stream>>>(lut, dy, y, dx, szLut, szHead, szBatch, scale, shfl_init); else if (block_size == 16) bst_masked_softmax_grad<16,1,16,T,V><<<grid,threads,shared,stream>>>(lut, dy, y, dx, szLut, szHead, szBatch, scale, shfl_init); else bst_masked_softmax_grad<16,1, 8,T,V><<<grid,threads,shared,stream>>>(lut, dy, y, dx, szLut, szHead, szBatch, scale, shfl_init); } else if (unroll == 8) { if (block_size == 64) bst_masked_softmax_grad< 8,2,64,T,V><<<grid,threads,shared,stream>>>(lut, dy, y, dx, szLut, szHead, szBatch, scale, shfl_init); else if (block_size == 32) bst_masked_softmax_grad< 8,2,32,T,V><<<grid,threads,shared,stream>>>(lut, dy, y, dx, szLut, szHead, szBatch, scale, shfl_init); else if (block_size == 16) bst_masked_softmax_grad< 8,2,16,T,V><<<grid,threads,shared,stream>>>(lut, dy, y, dx, szLut, szHead, szBatch, scale, shfl_init); else bst_masked_softmax_grad< 8,2, 8,T,V><<<grid,threads,shared,stream>>>(lut, dy, y, dx, szLut, szHead, szBatch, scale, shfl_init); } else // (unroll == 4) { if (block_size == 64) bst_masked_softmax_grad< 4,2,64,T,V><<<grid,threads,shared,stream>>>(lut, dy, y, dx, szLut, szHead, szBatch, scale, shfl_init); else if (block_size == 32) bst_masked_softmax_grad< 4,2,32,T,V><<<grid,threads,shared,stream>>>(lut, dy, y, dx, szLut, szHead, szBatch, scale, shfl_init); else if (block_size == 16) bst_masked_softmax_grad< 4,2,16,T,V><<<grid,threads,shared,stream>>>(lut, dy, y, dx, szLut, szHead, szBatch, scale, shfl_init); else bst_masked_softmax_grad< 4,2, 8,T,V><<<grid,threads,shared,stream>>>(lut, dy, y, dx, szLut, szHead, szBatch, scale, shfl_init); } return true; } template bool BlocksparseMaskedSoftmaxGrad<ehalf,ehalf2>(CUstream stream, const uint2* lut, const ehalf* dy, const ehalf* y, ehalf* dx, uint block_size, uint blocks, uint batch_dim, uint head_dim, uint ctx_blks, uint lut_heads, uint lut_dim, uint max_lut, float scale); template bool BlocksparseMaskedSoftmaxGrad<bhalf,bhalf2>(CUstream stream, const uint2* lut, const bhalf* dy, const bhalf* y, bhalf* dx, uint block_size, uint blocks, uint batch_dim, uint head_dim, uint ctx_blks, uint lut_heads, uint lut_dim, uint max_lut, float scale); template <int BSIZE, typename MASKT> __global__ void __launch_bounds__(32) bst_partial_autoregressive_mask( const int2* __restrict__ Lut, const MASKT* __restrict__ MaskI, MASKT* MaskO, uint blocks, uint szLut, int autoregress_at_k) { uint tid = threadIdx.x; uint bid = blockIdx.x; // grid id (each cuda block being assigned to 32 mask blocks) uint qid = blockIdx.y; // q dim (row) within block uint hid = blockIdx.z; // head dim uint block = bid*32 + tid; if (block < blocks) { uint l = hid*szLut + block; uint m = hid*blocks*BSIZE + qid*blocks + block; int2 entry = Lut[l]; MASKT mask = MaskI[m]; int K = entry.y*BSIZE; // entry.y: block index for keys int Q = entry.x*BSIZE; // entry.x: block index for queries int q = Q + qid; // full query index // shift amount for the bidirectional to autoregressive transition int shift_a = BSIZE - min(max(autoregress_at_k - K, 0), BSIZE); // shift amount for the normal autoregressive property (lower triagular) int shift_b = min(max(BSIZE-1 + K - q, 0), BSIZE); // final shift is min value of these int shift_c = min(shift_a, shift_b); // apply the unsigned right shift to a pattern of ones to turn the mask off where needed // a shift of zero means the mask is unchanged // a shift of BSIZE means the mask is turned off for this row/block // somewhere in between means it's partially off. mask &= (MASKT)-1 >> shift_c; MaskO[m] = mask; } } bool BstPartialAutoregressiveMask(CUstream stream, const int2* lut, const char* maskI, char* maskO, uint block_size, uint blocks, uint lut_heads, uint lut_dim, int autoregress_at_k) { dim3 grid(CEIL_DIV(blocks,32), block_size, lut_heads); if (block_size == 64) bst_partial_autoregressive_mask<64,uint64><<<grid,32,0,stream>>>(lut, (const uint64*)maskI, (uint64*)maskO, blocks, lut_dim, autoregress_at_k); else if (block_size == 32) bst_partial_autoregressive_mask<32, uint><<<grid,32,0,stream>>>(lut, (const uint*)maskI, ( uint*)maskO, blocks, lut_dim, autoregress_at_k); else if (block_size == 16) bst_partial_autoregressive_mask<16,ushort><<<grid,32,0,stream>>>(lut, (const ushort*)maskI, (ushort*)maskO, blocks, lut_dim, autoregress_at_k); else bst_partial_autoregressive_mask< 8, uchar><<<grid,32,0,stream>>>(lut, (const uchar*)maskI, ( uchar*)maskO, blocks, lut_dim, autoregress_at_k); return true; } #endif // GOOGLE_CUDA
the_stack
#include "Morphology.h" #include <iostream> using namespace std; #include "ErrorCode.h" // 宏:MOR_USE_INTERMEDIA // 开关宏,如果使能该宏,则 CLASS 内部提供开运算和闭运算的中间变量,免除返回申 // 请释放的开销,但这样做会由于中间图像尺寸较大而是的 Cache 作用被削弱,因此, // 未必会得到好性能。关闭该宏,则每次调用开闭运算,都会临时申请中间变量。 #define MOR_USE_INTERMEDIA // 宏:DEF_BLOCK_X 和 DEF_BLOCK_Y // 定义了默认的线程块尺寸 #define DEF_BLOCK_X 32 #define DEF_BLOCK_Y 8 // 宏:MOR_IMI_WIDTH 和 MOR_IMI_HEIGHT // 定义了中间图像的尺寸。 #define MOR_IMI_WIDTH 4000 #define MOR_IMI_HEIGHT 4000 // static变量:_defTpl // 当用户未定义有效的模板时,使用此默认模板,默认为 3 x 3 static Template *_defTpl = NULL; // Host 函数:_initDefTemplate(初始化默认的模板指针) // 函数初始化默认模板指针 _defTpl,如果原来模板不为空,则直接返回,否则初始化 // 为 3 x 3 的默认模板 static __host__ Template* // 返回值:返回默认模板指针 _defTpl _initDefTemplate(); // Kernel 函数:_erosion(实现腐蚀算法操作) static __global__ void // Kernel 函数无返回值 _erosion( ImageCuda inimg, // 输入图像 ImageCuda outimg, // 输出图像 Template tpl // 模板 ); // Kernel 函数:_dilation(实现膨胀算法操作) static __global__ void // Kernel 函数无返回值 _dilation( ImageCuda inimg, // 输入图像 ImageCuda outimg, // 输出图像 Template tpl // 模板 ); // Host 函数:_preOp(在算法操作前进行预处理) // 在进行腐蚀,膨胀操作前,先进行预处理,包括:(1)对输入和输出图像 // 进行数据准备,包括申请当前Device存储空间;(2)对模板进行处理,包 // 申请当前Device存储空间 static __host__ int // 返回值:函数是否正确执行,若正确执行,返回 // NO_ERROR _preOp( Image *inimg, // 输入图像 Image *outimg, // 输出图像 Template *tp // 模板 ); // Host 函数:_adjustRoiSize(调整 ROI 子图的大小) // 调整 ROI 子图的大小,使输入和输出的子图大小统一 static __host__ void // 无返回值 _adjustRoiSize( ImageCuda *inimg, // 输入图像 ImageCuda *outimg // 输出图像 ); // Host 函数:_getBlockSize(获取 Block 和 Grid 的尺寸) // 根据默认的 Block 尺寸,使用最普通的线程划分方法获取 Grid 的尺寸 static __host__ int // 返回值:函数是否正确执行,若正确执行,返回 // NO_ERROR _getBlockSize( int width, // 需要处理的宽度 int height, // 需要处理的高度 dim3 *gridsize, // 计算获得的 Grid 的尺寸 dim3 *blocksize // 计算获得的 Block 的尺寸 ); // Host 函数:_initDefTemplate(初始化默认的模板指针) static __host__ Template* _initDefTemplate() { // 如果 _defTpl 不为空,说明已经初始化了,则直接返回 if (_defTpl != NULL) return _defTpl; // 如果 _defTpl 为空,则初始化为 3 x 3 的模板 TemplateBasicOp::newTemplate(&_defTpl); TemplateBasicOp::makeAtHost(_defTpl, 9); // 分别处理每一个点 for (int i = 0; i < 9; i++) { // 分别计算每一个点的横坐标和纵坐标 _defTpl->tplData[2 * i] = i % 3 - 1; _defTpl->tplData[2 * i + 1] = i / 3 - 1; } return _defTpl; } // Kernel 函数:_erosion(实现腐蚀算法操作) static __global__ void _erosion(ImageCuda inimg, ImageCuda outimg, Template tpl) { // dstc 和 dstr 分别表示线程处理的像素点的坐标的 x 和 y 分量 (其中, // c 表示 column, r 表示 row)。由于采用并行度缩减策略 ,令一个线程 // 处理 4 个输出像素,这四个像素位于同一行的相邻 4 行上,因此,对于 // dstr 需要进行乘 4 的计算 int dstc = (blockIdx.x * blockDim.x + threadIdx.x) * 4; int dstr = (blockIdx.y * blockDim.y + threadIdx.y)/* * 1*/; // 检查第一个像素点是否越界,如果越界,则不进行处理,一方面节省计算 // 资源,另一方面防止由于段错误导致程序崩溃 if (dstc >= inimg.imgMeta.width || dstr >= inimg.imgMeta.height) return; // 用来保存临时像素点的坐标的 x 和 y 分量 int dx, dy; // 用来记录当前模板所在的位置的指针 int *curtplptr = tpl.tplData; // 用来记录当前输入图像所在位置的指针 unsigned char *curinptr; // 用来保存输出像素在模板范围内的最小像素的值,由于采用并行度缩减策略,一 // 个像素处理 4 个输出像素,所以这里定义一个大小为 4 的数组,因为是存放 // 最小值,所以先初始化为最大值 0xff union { unsigned char pixel[4]; unsigned int data; } _min; _min.pixel[0] = _min.pixel[1] = _min.pixel[2] = _min.pixel[3] = 0xff; // 存放临时像素点的像素值 unsigned char pixel; // 扫描模板范围内的每个输入图像的像素点 for (int i = 0; i < tpl.count; i++) { // 计算当前模板位置所在像素的 x 和 y 分量,模板使用相邻的两个下标的 // 数组表示一个点,所以使当前模板位置的指针作加一操作 dx = dstc + *(curtplptr++); dy = dstr + *(curtplptr++); // 先判断当前像素的 y 分量是否越界,如果越界,则跳过,扫描下一个模板点 // 如果没有越界,则分别处理当前行的相邻的 4 个像素 if (dy >= 0 && dy < inimg.imgMeta.height) { // 根据 dx 和 dy 获取第一个像素的位置 curinptr = inimg.imgMeta.imgData + dx + dy * inimg.pitchBytes; // 检测此像素的 x 分量是否越界 if (dx >= 0 && dx < inimg.imgMeta.width) { // 和 min[0] 比较,如果比 min[0] 小,则将当前像素赋值给 min[0] pixel = *curinptr; pixel < _min.pixel[0] ? (_min.pixel[0] = pixel) : '\0'; } // 处理当前行的剩下的 3 个像素 for (int j = 1; j < 4; j++) { // 获取当前列的下一列的像素的位置 curinptr++; // 使 dx 加一,得到当前要处理的像素的 x 分量 dx++; // 检测 dy 是否越界 if (dx >= 0 && dx < inimg.imgMeta.width) { // 和 min[j] 比较,如果比 min[j] 小,则将当前像素赋值给 // min[j] pixel = *curinptr; pixel < _min.pixel[j] ? (_min.pixel[j] = pixel) : '\0'; } } } } // 定义输出图像位置的指针 unsigned int *outptr; // 获取对应的第一个输出图像的位置 outptr = (unsigned int *)(outimg.imgMeta.imgData + dstr * outimg.pitchBytes + dstc); // 将计算得到的 min[0] 赋值给输出图像 *outptr = _min.data; } // 成员方法:erode __host__ int Morphology::erode(Image *inimg, Image *outimg) { int errcode; // 局部变量,错误码 dim3 gridsize; dim3 blocksize; // 检查输入图像,输出图像,以及模板是否为空 if (inimg == NULL || outimg == NULL || tpl == NULL) return NULL_POINTER; // 对输入图像,输出图像和模板进行预处理 errcode = _preOp(inimg, outimg, tpl); if (errcode != NO_ERROR) return errcode; // 提取输入图像的 ROI 子图像 ImageCuda insubimgCud; errcode = ImageBasicOp::roiSubImage(inimg, &insubimgCud); if (errcode != NO_ERROR) return errcode; // 提取输出图像的 ROI 子图像 ImageCuda outsubimgCud; errcode = ImageBasicOp::roiSubImage(outimg, &outsubimgCud); if (errcode != NO_ERROR) return errcode; // 调整输入和输出图像的 ROI 子图,使大小统一 _adjustRoiSize(&insubimgCud, &outsubimgCud); // 计算调用 Kernel 函数的线程块的尺寸和线程块的数量 errcode = _getBlockSize(outsubimgCud.imgMeta.width, outsubimgCud.imgMeta.height, &gridsize, &blocksize); if (errcode != NO_ERROR) return errcode; // 调用 Kernel 函数进行腐蚀操作 _erosion<<<gridsize, blocksize>>>(insubimgCud, outsubimgCud, *tpl); if (cudaGetLastError() != cudaSuccess) return CUDA_ERROR; return NO_ERROR; } // Kernel 函数:_dilation(实现膨胀算法操作) static __global__ void _dilation(ImageCuda inimg, ImageCuda outimg, Template tpl) { // dstc 和 dstr 分别表示线程处理的像素点的坐标的 x 和 y 分量 (其中, // c 表示 column, r 表示 row)。由于采用并行度缩减策略 ,令一个线程 // 处理 4 个输出像素,这四个像素位于同一行的相邻 4 行上,因此,对于 // dstr 需要进行乘 4 的计算 int dstc = (blockIdx.x * blockDim.x + threadIdx.x) * 4; int dstr = (blockIdx.y * blockDim.y + threadIdx.y)/* * 1*/; // 检查第一个像素点是否越界,如果越界,则不进行处理,一方面节省计算 // 资源,另一方面防止由于段错误导致程序崩溃 if (dstc >= inimg.imgMeta.width || dstr >= inimg.imgMeta.height) return; // 用来保存临时像素点的坐标的 x 和 y 分量 int dx, dy; // 用来记录当前模板所在的位置的指针 int *curtplptr = tpl.tplData; // 用来记录当前输入图像所在位置的指针 unsigned char *curinptr; // 用来保存输出像素在模板范围内的最大像素的值,由于采用并行度缩减策略,一 // 个像素处理 4 个输出像素,所以这里定义一个大小为 4 的数组,因为是存放 // 最大值,所以先初始化为最小值 0x00 union { unsigned char pixel[4]; unsigned int data; } _max; _max.pixel[0] = _max.pixel[1] = _max.pixel[2] = _max.pixel[3] = 0x00; // 存放临时像素点的像素值 unsigned char pixel; // 扫描模板范围内的每个输入图像的像素点 for (int i = 0; i < tpl.count; i++) { // 计算当前模板位置所在像素的 x 和 y 分量,模板使用相邻的两个下标的 // 数组表示一个点,所以使当前模板位置的指针作加一操作 dx = dstc + *(curtplptr++); dy = dstr + *(curtplptr++); // 先判断当前像素的 y 分量是否越界,如果越界,则跳过,扫描下一个模板点 // 如果没有越界,则分别处理当前行的相邻的 4 个像素 if (dy >= 0 && dy < inimg.imgMeta.height) { // 根据 dx 和 dy 获取第一个像素的位置 curinptr = inimg.imgMeta.imgData + dx + dy * inimg.pitchBytes; // 检测此像素的 y 分量是否越界 if (dx >= 0 && dx < inimg.imgMeta.width) { // 和 max[0] 比较,如果比 max[0] 大,则将当前像素赋值给 max[0] pixel = *curinptr; pixel > _max.pixel[0] ? (_max.pixel[0] = pixel) : '\0'; } // 处理当前列的剩下的 3 个像素 for (int j = 1; j < 4; j++) { // 获取当前列的下一列的像素的位置 curinptr++; // 使 dx 加一,得到当前要处理的像素的 x 分量 dx++; // 检测 dy 是否越界 if (dx >= 0 && dx < inimg.imgMeta.width) { // 和 max[j] 比较,如果比 max[j] 大,则将当前像素值赋值给 // max[j] pixel = *curinptr; pixel > _max.pixel[j] ? (_max.pixel[j] = pixel) : '\0'; } } } } // 定义输出图像位置的指针 unsigned int *outptr; // 获取对应的第一个输出图像的位置 outptr = (unsigned int *)(outimg.imgMeta.imgData + dstr * outimg.pitchBytes + dstc); // 将计算得到的 max[0] 赋值给输出图像 *outptr = _max.data; } // 成员方法:dilate __host__ int Morphology::dilate(Image *inimg, Image *outimg) { int errcode; // 局部变量,错误码 dim3 gridsize; dim3 blocksize; // 检查输入图像,输出图像,以及模板是否为空 if (inimg == NULL || outimg == NULL || tpl == NULL) return NULL_POINTER; // 对输入图像,输出图像和模板进行预处理 errcode = _preOp(inimg, outimg, tpl); if (errcode != NO_ERROR) return errcode; // 提取输入图像的 ROI 子图像 ImageCuda insubimgCud; errcode = ImageBasicOp::roiSubImage(inimg, &insubimgCud); if (errcode != NO_ERROR) return errcode; // 提取输出图像的 ROI 子图像 ImageCuda outsubimgCud; errcode = ImageBasicOp::roiSubImage(outimg, &outsubimgCud); if (errcode != NO_ERROR) return errcode; // 调整输入和输出图像的 ROI 子图,使大小统一 _adjustRoiSize(&insubimgCud, &outsubimgCud); // 计算调用 Kernel 函数的线程块的尺寸和线程块的数量 errcode = _getBlockSize(outsubimgCud.imgMeta.width, outsubimgCud.imgMeta.height, &gridsize, &blocksize); if (errcode != NO_ERROR) return errcode; // 调用 Kernel 函数进行膨胀操作 _dilation<<<gridsize, blocksize>>>(insubimgCud, outsubimgCud, *tpl); if (cudaGetLastError() != cudaSuccess) return CUDA_ERROR; return NO_ERROR; } // Host 函数:_preOp(在算法操作前进行预处理) static __host__ int _preOp(Image *inimg, Image *outimg, Template *tp) { int errcode; // 局部变量,错误码 // 将输入图像拷贝到 Device 内存中 errcode = ImageBasicOp::copyToCurrentDevice(inimg); if (errcode != NO_ERROR) return errcode; // 将输出图像拷贝到 Device 内存中 errcode = ImageBasicOp::copyToCurrentDevice(outimg); if (errcode != NO_ERROR) { // 计算 roi 子图的宽和高 int roiwidth = inimg->roiX2 - inimg->roiX1; int roiheight = inimg->roiY2 - inimg->roiY1; // 如果输出图像无数据,则会创建一个和输出图像子图像尺寸相同的图像 errcode = ImageBasicOp::makeAtCurrentDevice(outimg, roiwidth, roiheight); // 如果创建图像依然操作失败,则返回错误 if (errcode != NO_ERROR) return errcode; } // 将模板拷贝到 Device 内存中 errcode = TemplateBasicOp::copyToCurrentDevice(tp); if (errcode != NO_ERROR) return errcode; return NO_ERROR; } // Host 函数:_adjustRoiSize(调整输入和输出图像的 ROI 的大小) inline static __host__ void _adjustRoiSize(ImageCuda *inimg, ImageCuda *outimg) { if (inimg->imgMeta.width > outimg->imgMeta.width) inimg->imgMeta.width = outimg->imgMeta.width; else outimg->imgMeta.width = inimg->imgMeta.width; if (inimg->imgMeta.height > outimg->imgMeta.height) inimg->imgMeta.height = outimg->imgMeta.height; else outimg->imgMeta.height = inimg->imgMeta.height; } // Host 函数:_getBlockSize(获取 Block 和 Grid 的尺寸) inline static __host__ int _getBlockSize(int width, int height, dim3 *gridsize, dim3 *blocksize) { // 检测 girdsize 和 blocksize 是否是空指针 if (gridsize == NULL || blocksize == NULL) return NULL_POINTER; // blocksize 使用默认的尺寸 blocksize->x = DEF_BLOCK_X; blocksize->y = DEF_BLOCK_Y; // 使用最普通的方法划分 Grid gridsize->x = (width + blocksize->x * 4 - 1) / (blocksize->x * 4); gridsize->y = (height + blocksize->y * 1 - 1) / (blocksize->y * 1); return NO_ERROR; } // 构造函数:Morphology __host__ Morphology::Morphology(Template *tp) { // 设置类成员中的模板参数。 setTemplate(tp); #ifdef MOR_USE_INTERMEDIA // 初始化中间图像。如果中间图像没有申请成功,则置为 NULL。 int errcode; errcode = ImageBasicOp::newImage(&intermedImg); if (errcode != NO_ERROR) { intermedImg = NULL; return; } // 为中间图像申请内存空间。如果中间图像没有申请成功,则置为 NULL。 errcode = ImageBasicOp::makeAtCurrentDevice( intermedImg, MOR_IMI_WIDTH, MOR_IMI_HEIGHT); if (errcode != NO_ERROR) { ImageBasicOp::deleteImage(intermedImg); intermedImg = NULL; return; } #else intermedImg = NULL; #endif } // 析构函数:~Morphology __host__ Morphology::~Morphology() { // 如果中间图像已经申请,则需要释放掉中间图像。 if (intermedImg != NULL) ImageBasicOp::deleteImage(intermedImg); } // 成员方法:getTemplate __host__ Template* Morphology::getTemplate() const { // 如果模板指针和默认模板指针相同,则返回空 if (this->tpl == _defTpl) return NULL; // 否则返回设置的模板指针 return this->tpl; } // 成员方法:setTemplate __host__ int Morphology::setTemplate(Template *tp) { // 如果 tp 为空,则只用默认的模板指针 if (tp == NULL) { this->tpl = _initDefTemplate(); } // 否则将 tp 赋值给 tpl else { this->tpl = tp; } return NO_ERROR; } // 成员方法:open(开运算) __host__ int Morphology::open(Image *inimg, Image *outimg) { int errcode; // 局部变量,错误码 Image *imiimg; // 局部变量,用来存储腐蚀操作的返回结果,再对此图像 // 进行膨胀操作 ImageCuda *imiimgCud; // 只在使用 CLASS 提供的中间图像时使用 size_t pitchold; // 只在使用 CLASS 提供的中间图像时使用,用于记录原始 // 原始参数。 // 检查输入图像,输出图像,以及模板是否为空 if (inimg == NULL || outimg == NULL || tpl == NULL) return NULL_POINTER; // 若无法使用 CLASS 自身提供的中间图像,则需要自行申请中间图像,这样的图像 // 在处理完毕后需要释放掉,因此通过一个 bool 变量标识目前使用的是否是一个临 // 时申请的中间图像。 bool useprivimiimg = false; if (intermedImg == NULL) { // 如果 CLASS 的中间图像为 NULL,则说明其在 CLASS 构造时没有成功申请空 // 间,因此只能使用临时申请的中间图像。 useprivimiimg = true; errcode = ImageBasicOp::newImage(&imiimg); if (errcode != NO_ERROR) return errcode; } else { // 计算当前计算所需要的中间图像尺寸,即两个图像 ROI 区域取较小者。 int roiw1 = inimg->roiX2 - inimg->roiX1; int roih1 = inimg->roiY2 - inimg->roiY1; int roiw2 = outimg->roiX2 - outimg->roiX1; int roih2 = outimg->roiY2 - outimg->roiY1; if (roiw2 == 0) roiw2 = roiw1; if (roih2 == 0) roih2 = roih1; int roiw = (roiw1 <= roiw2) ? roiw1 : roiw2; int roih = (roih1 <= roih2) ? roih1 : roih2; // 根据当前计算所需要的中间图像尺寸,来决定是否使用 CLASS 提供的中间图 // 像。 if (roiw <= intermedImg->width && roih <= intermedImg->height) { // 如果 CLASS 提供的图像图像可以满足尺寸要求,则直接使用 CLASS 提供 // 的中间图像。 useprivimiimg = false; // 这里需要调整一下 CLASS 提供图像的 ROI 尺寸,以防止上次计算对 ROI // 尺寸的影响,而得到不正确的图像结果。考虑到 cache 问题,由于较大的 // 中间图像会导致 cache 局部性的问题,这里我们强行更改了 pitch 以保 // 证具有更好的局部性。 // 首先,将 CLASS 提供的中间图像的元数据复制出来一份。 imiimg = intermedImg; imiimgCud = IMAGE_CUDA(imiimg); pitchold = imiimgCud->pitchBytes; // 然后强行修改 CLASS 的尺寸参数(由于判断了尺寸的合适性,因此,修 // 改参数的操作是安全的。 imiimg->width = roiw; imiimg->height = roih; imiimgCud->pitchBytes = roiw; imiimg->roiX1 = imiimg->roiY1 = 0; imiimg->roiX2 = roiw; imiimg->roiY2 = roih; } else { // 如果尺寸不满足要求,只能使用临时申请的中间图像。 useprivimiimg = true; errcode = ImageBasicOp::newImage(&imiimg); if (errcode != NO_ERROR) return errcode; } } do { // 先对输入图像进行腐蚀操作,结果临时存在中间图像中 errcode = erode(inimg, imiimg); if (errcode != NO_ERROR) break; // 再将腐蚀操作得到的中间图像进行膨胀操作,结果放在 outimg 中 errcode = dilate(imiimg, outimg); if (errcode != NO_ERROR) break; } while (0); // 释放中间图像的资源 if (useprivimiimg) { ImageBasicOp::deleteImage(imiimg); } else { // 还原 CLASS 中间图像回原来的参数。 imiimg->width = MOR_IMI_WIDTH; imiimg->height = MOR_IMI_HEIGHT; imiimgCud->pitchBytes = pitchold; imiimg->roiX1 = imiimg->roiY1 = 0; imiimg->roiX2 = MOR_IMI_WIDTH; imiimg->roiY2 = MOR_IMI_HEIGHT; } return errcode; } // 成员方法:close __host__ int Morphology::close(Image *inimg, Image *outimg) { int errcode; // 局部变量,错误码 Image *imiimg; // 局部变量,用来存储腐蚀操作的返回结果,再对此图像 // 进行膨胀操作 ImageCuda *imiimgCud; // 只在使用 CLASS 提供的中间图像时使用 size_t pitchold; // 只在使用 CLASS 提供的中间图像时使用,用于记录原始 // 原始参数。 // 检查输入图像,输出图像,以及模板是否为空 if (inimg == NULL || outimg == NULL || tpl == NULL) return NULL_POINTER; // 若无法使用 CLASS 自身提供的中间图像,则需要自行申请中间图像,这样的图像 // 在处理完毕后需要释放掉,因此通过一个 bool 变量标识目前使用的是否是一个临 // 时申请的中间图像。 bool useprivimiimg = false; if (intermedImg == NULL) { // 如果 CLASS 的中间图像为 NULL,则说明其在 CLASS 构造时没有成功申请空 // 间,因此只能使用临时申请的中间图像。 useprivimiimg = true; errcode = ImageBasicOp::newImage(&imiimg); if (errcode != NO_ERROR) return errcode; } else { // 计算当前计算所需要的中间图像尺寸,即两个图像 ROI 区域取较小者。 int roiw1 = inimg->roiX2 - inimg->roiX1; int roih1 = inimg->roiY2 - inimg->roiY1; int roiw2 = outimg->roiX2 - outimg->roiX1; int roih2 = outimg->roiY2 - outimg->roiY1; if (roiw2 == 0) roiw2 = roiw1; if (roih2 == 0) roih2 = roih1; int roiw = (roiw1 <= roiw2) ? roiw1 : roiw2; int roih = (roih1 <= roih2) ? roih1 : roih2; // 根据当前计算所需要的中间图像尺寸,来决定是否使用 CLASS 提供的中间图 // 像。 if (roiw <= intermedImg->width && roih <= intermedImg->height) { // 如果 CLASS 提供的图像图像可以满足尺寸要求,则直接使用 CLASS 提供 // 的中间图像。 useprivimiimg = false; // 这里需要调整一下 CLASS 提供图像的 ROI 尺寸,以防止上次计算对 ROI // 尺寸的影响,而得到不正确的图像结果。考虑到 cache 问题,由于较大的 // 中间图像会导致 cache 局部性的问题,这里我们强行更改了 pitch 以保 // 证具有更好的局部性。 // 首先,将 CLASS 提供的中间图像的元数据复制出来一份。 imiimg = intermedImg; imiimgCud = IMAGE_CUDA(imiimg); pitchold = imiimgCud->pitchBytes; // 然后强行修改 CLASS 的尺寸参数(由于判断了尺寸的合适性,因此,修 // 改参数的操作是安全的。 imiimg->width = roiw; imiimg->height = roih; imiimgCud->pitchBytes = roiw; imiimg->roiX1 = imiimg->roiY1 = 0; imiimg->roiX2 = roiw; imiimg->roiY2 = roih; } else { // 如果尺寸不满足要求,只能使用临时申请的中间图像。 useprivimiimg = true; errcode = ImageBasicOp::newImage(&imiimg); if (errcode != NO_ERROR) return errcode; } } do { // 先对输入图像进行膨胀操作,结果临时存在中间图像中 errcode = dilate(inimg, imiimg); if (errcode != NO_ERROR) break; // 再将腐蚀操作得到的中间图像进行膨胀操作,结果放在 outimg 中 errcode = erode(imiimg, outimg); if (errcode != NO_ERROR) break; } while (0); // 释放中间图像的资源 if (useprivimiimg) { ImageBasicOp::deleteImage(imiimg); } else { // 还原 CLASS 中间图像回原来的参数。 imiimg->width = MOR_IMI_WIDTH; imiimg->height = MOR_IMI_HEIGHT; imiimgCud->pitchBytes = pitchold; imiimg->roiX1 = imiimg->roiY1 = 0; imiimg->roiX2 = MOR_IMI_WIDTH; imiimg->roiY2 = MOR_IMI_HEIGHT; } return errcode; }
the_stack
namespace sketch { using hrc = std::chrono::high_resolution_clock; #ifdef __CUDACC__ using exception::CudaError; #endif template<typename T, typename=std::enable_if_t<std::is_arithmetic<T>::value>> #ifdef __CUDACC__ __host__ __device__ #endif INLINE uint64_t nchoose2(T x) { return (uint64_t(x) * uint64_t(x - 1)) / 2; } enum DeviceStorageFmt: int { DEFAULT_6_BIT_HLL, PACKED_4_BIT_HLL, WIDE_8_BIT_HLL, BBMH }; template<typename T> #ifdef __CUDACC__ __host__ __device__ #endif INLINE void increment_maxes(T *arr, unsigned x1, unsigned x2) { #if __CUDA_ARCH__ x1 = __vmaxu4(x1, x2); #else // Manual unsigned x3 = std::max(x1>>24, x2>>24); x3 <<= 8; x3 |= std::max((x1 >> 16) & 0xFFu, (x2 >> 16) & 0xFFu); x3 <<= 8; x3 |= std::max((x1 >> 8) & 0xFFu, (x2 >> 8) & 0xFFu); x1 = (x3 << 8) | std::max(x1 & 0xFFu, x2 & 0xFFu); #endif ++arr[x1&0xFFu]; ++arr[(x1>>8)&0xFFu]; ++arr[(x1>>16)&0xFFu]; ++arr[x1>>24]; } template<typename T> #ifdef __CUDACC__ __host__ __device__ #endif INLINE void increment_maxes_packed16(T *arr, const unsigned x1, const unsigned x2) { #if __CUDA_ARCH__ static constexpr unsigned mask = 0x0F0F0F0Fu; unsigned tmp1 = x1 & mask, tmp2 = x2 & mask; tmp1 = __vmaxu4(tmp1, tmp2); ++arr[tmp1&0xFu]; ++arr[(tmp1>>8)&0xFu]; ++arr[(tmp1>>16)&0xFu]; ++arr[tmp1>>24]; tmp1 = __vmaxu4((x1>>4)&mask, (x2>>4)&mask); ++arr[tmp1&0xFu]; ++arr[(tmp1>>8)&0xFu]; ++arr[(tmp1>>16)&0xFu]; ++arr[tmp1>>24]; #else using std::max; // Manual ++arr[max(x1>>28, x2>>28)]; ++arr[max((x1>>24)&0xFu, (x2>>24)&0xFu)]; ++arr[max((x1>>20)&0xFu, (x2>>20)&0xFu)]; ++arr[max((x1>>16)&0xFu, (x2>>16)&0xFu)]; ++arr[max((x1>>12)&0xFu, (x2>>12)&0xFu)]; ++arr[max((x1>>8)&0xFu, (x2>>8)&0xFu)]; ++arr[max((x1>>4)&0xFu, (x2>>4)&0xFu)]; ++arr[max(x1&0xFu, x2&0xFu)]; #endif } #ifdef __CUDACC__ template<typename T, typename T2, typename T3, typename=typename std::enable_if< std::is_integral<T>::value && std::is_integral<T2>::value && std::is_integral<T3>::value >::type> __device__ __host__ static inline T ij2ind(T i, T2 j, T3 n) { #define ARRAY_ACCESS(row, column) (((row) * (n * 2 - row - 1)) / 2 + column - (row + 1)) const auto i1 = min(i, j), j1 = min(j, i); return ARRAY_ACCESS(i1, j1); #undef ARRAY_ACCESS } __host__ __device__ INLINE void set_lut_portion(uint32_t i, uint32_t jstart, uint32_t jend, uint32_t n, uint64_t *lut) { SK_UNROLL_8 for(;jstart < jend; ++jstart) { lut[ij2ind(i, jstart, n)] = (uint64_t(i) << 32) | jstart; } } #endif // __CUDACC__ template<typename T> #ifdef __CUDACC__ __host__ __device__ #endif INLINE double origest(const T &p, unsigned l2) { const auto m = 1u << l2; const double alpha = m == 16 ? .573 : m == 32 ? .697 : m == 64 ? .709: .7213 / (1. + 1.079 / m); double s = p[0]; SK_UNROLL_8 for(auto i = 1u; i < 64 - l2 + 1; ++i) { #if __CUDA_ARCH__ s += ldexpf(p[i], -i); // 64 - p because we can't have more than that many leading 0s. This is just a speed thing. #else s += std::ldexp(p[i], -i); #endif } return alpha * m * m / s; } using namespace ::sketch::hll; template<typename Alloc> auto sum_union_hlls(unsigned p, const std::vector<const uint8_t *SK_RESTRICT, Alloc> &re) { size_t maxnz = 64 - p + 1, nvals = maxnz + 1; size_t nsets = re.size();//, nschoose2 = ((nsets - 1) * nsets) / 2; size_t m = 1ull << p; std::vector<uint32_t> ret(nvals * nsets * m); for(size_t i = 0; i < nsets; ++i) { auto p1 = re[i]; OMP_PRAGMA("omp parallel for") for(size_t j = i + 1; j < nsets; ++j) { auto p2 = re[j]; auto rp = ret.data() + i * nsets * m; std::array<uint32_t, 64> z{0}; for(size_t subi = 0; subi < m; subi += 8) { increment_maxes(z.data(), *reinterpret_cast<const unsigned *>(&p1[subi]), *reinterpret_cast<const unsigned *>(&p2[subi])); increment_maxes(z.data(), *reinterpret_cast<const unsigned *>(&p1[subi+4]), *reinterpret_cast<const unsigned *>(&p2[subi+4])); } std::memcpy(ret.data() + (i * nsets * m) + j * m, z.data(), m); } } return std::make_pair(std::move(ret), nvals); } #ifdef __CUDACC__ __global__ void calc_sizes_1024(const uint8_t *p, unsigned l2, size_t nhlls, uint32_t *sizes) { if(blockIdx.x >= nhlls) return; extern __shared__ int shared[]; uint8_t *registers = (uint8_t *)shared; auto hllid = blockIdx.x; int nreg = 1 << l2; int nper = (nreg + (nhlls - 1)) / nhlls; auto hp = p + (hllid << l2); auto gid = blockIdx.x * blockDim.x + threadIdx.x; if(gid >= (nhlls - 1) * nhlls / 2) return; for(int i = threadIdx.x * nper; i < min((threadIdx.x + 1) * nper, nreg); ++i) registers[i] = hp[i]; __syncthreads(); uint32_t arr[60]{0}; hp = p + (threadIdx.x << l2); SK_UNROLL_8 for(int i = 0; i < (1L << l2); i += 4) { increment_maxes(arr, *(unsigned *)&hp[i], *(unsigned *)&registers[i]); } sizes[gid] = origest(arr, l2); } #if 0 __host__ INLINE uint3 calculate_indices(uint32_t block_id, uint32_t nhlls, uint16_t nblock_per_cmp) { // Think it through: is there any reason why you have to work in rows at all? const int cmp_ind = block_id / nblock_per_cmp; const auto ij = ind2ij(cmp_id, nhlls); // ind2ij is WRONG, needs to be written. // Is there a simple function for this? //if(cmp_ind : return uint3(ij.x, ij.y, cmp_ind); } #endif __global__ void calc_sizes_row(const uint8_t *SK_RESTRICT p, unsigned l2, unsigned nhlls, unsigned nrows, unsigned starting_rownum, unsigned mem_per_block, uint32_t *SK_RESTRICT register_sums, uint32_t *SK_RESTRICT sizes, uint16_t nblock_per_cmp) { extern __shared__ int shared[]; auto sptr = reinterpret_cast<uint32_t *>(&shared[0]); const int block_id = blockIdx.x + blockIdx.y * gridDim.x; const int cmp_ind = block_id / nblock_per_cmp + starting_rownum; // TODO: back-calculate indices for chunk // Generalize to not be limited to row sizes but arbitrary chunks // Dispatch // ??? // PROFIT #if 0 const uint3 = calculate_indices(block_id, nhlls, nblock_per_cmp); #endif auto ncmp = nrows * nhlls; if(cmp_ind > ncmp) return; auto nblocks = ncmp * nblock_per_cmp; const int global_tid = block_id * blockDim.x + threadIdx.x; auto tid = threadIdx.x; const int nl2s = 64 - l2 + 1; for(int i = tid * (nl2s) / blockDim.x; i < min((tid + 1) * nl2s / blockDim.x, nl2s); ++i) sptr[i] = 0; auto bid = blockIdx.x; auto gid = bid * blockDim.x + tid; const uint32_t nreg = size_t(1) << l2; uint32_t arr[60]{0}; #if 0 int lhi, rhi; get_indices(nhlls, nblock_per_cmp, block_id, &lhi, &rhi); int total_workers = blockDim.x * nblock_per_cmp; #pragma unroll 8 for(int i = nreg * tid / total_workers; i < min(nreg, (nreg * (tid + 1) / total_workers)); i += 4) { increment_maxes(arr, *reinterpret_cast<unsigned *>(&hp[i]), *reinterpret_cast<unsigned *>(&registers[i])); } __syncthreads(); for(int i = tid * (nl2s) / blockDim.x; i < min((tid + 1) * nl2s / blockDim.x, nl2s); ++i) atomicAdd(register_sums + (nl2s * , sptr[i]); #endif } __host__ std::vector<uint32_t> all_pairsu(const uint8_t *SK_RESTRICT p, unsigned l2, size_t nhlls, size_t &SK_RESTRICT rets) { size_t nc2 = nchoose2(nhlls); uint32_t *sizes; size_t nb = sizeof(uint32_t) * nc2; size_t m = 1ull << l2; cudaError_t ce; //size_t nblocks = 1; std::fprintf(stderr, "About to launch kernel\n"); auto t = hrc::now(); size_t tpb = nhlls/2 + (nhlls&1); std::vector<uint32_t> ret(nc2); PREC_REQ(l2 > 5, "l2 must be 6 or greater"); if(tpb > 1024) { const size_t mem_per_block = sizeof(uint32_t) * (64 - l2 + 1); const int nrows = 1; // This can/should be changed eventually const int nblock_per_cmp = 4; // Can/should be changed later size_t ncmp_per_loop = nhlls * nrows; size_t nblocks = nblock_per_cmp * ncmp_per_loop; auto ydim = (nblocks + 65535 - 1) / 65535; dim3 griddims(nblocks < 65535 ? nblocks: 65535, ydim); if((ce = cudaMalloc((void **)&sizes, ncmp_per_loop * sizeof(uint32_t)))) throw CudaError(ce, "Failed to malloc for row"); #if USE_THRUST thrust::device_vector<uint32_t> tv((64 - l2 + 1) * ncmp_per_loop); uint32_t *register_sums(raw_pointer_cast(tv.data())); #else uint32_t *register_sums; if((ce = cudaMalloc((void **)&register_sums, ncmp_per_loop * mem_per_block))) throw CudaError(ce, "Failed to malloc for row"); #endif // This means work per block before updating will be mem_per_block / nblocks //calc_sizes_large<<<nblocks,1024,mem_per_block>>>(p, l2, nhlls, nblocks, mem_per_block, sizes); throw std::runtime_error("Current implementation is limited to 1024 by 1024 comparisons. TODO: fix this with a reimplementation"); } else { if((ce = cudaMalloc((void **)&sizes, nb))) throw CudaError(ce, "Failed to malloc"); calc_sizes_1024<<<nhlls,(nhlls+1)/2,m>>>(p, l2, nhlls, sizes); if((ce = cudaDeviceSynchronize())) throw CudaError(ce, "Failed to synchronize"); if((ce = cudaMemcpy(ret.data(), sizes, nb, cudaMemcpyHostToDevice))) throw CudaError(ce, "Failed to copy device to host"); } if((ce = cudaDeviceSynchronize())) throw CudaError(ce, "Failed to synchronize"); if((ce = cudaGetLastError())) throw CudaError(ce, ""); auto t2 = hrc::now(); rets = (t2 - t).count(); std::fprintf(stderr, "Time: %zu\n", rets); std::fprintf(stderr, "Finished kernel\n"); //thrust::copy(sizes, sizes + ret.size(), ret.begin()); cudaFree(sizes); return ret; } #endif #ifdef __CUDACC__ template<typename FT> void __global__ original_hll_kernel(const uint8_t *const dmem, FT *drmem, size_t nelem, size_t rowind, size_t round_nrows, int tpb, int nblocks, int p, size_t entrysize, float alpha) { // int nblocks = (nelem_ * numrows_ * entrysize_ + tpb - 1) / tpb; // This means one per 256 bytes. extern __shared__ shared[]; //uint32_t ls[64]{0}; // Number of integers: r. (meaning one never accesses a higher number) //const auto r = 64 - p + 1; if(threadIdx.x < 64) { shared[threadIdx.x] = 0; } __syncthreads(); const int tid = threadIdx.x; int blockid = blockIdx.x; int rhsnum = blockid % (entrysize / tpb); // Tells us which in (nr * nelem) counting order we're using. int rhsidx = rhsnum % nelem; int lhsidx = rhsnum / nelem + rowind; int bytes_per_thread = entrysize / tpb; auto offset_within = (tid * bytes_per_thread); auto lhscmpptr = dmem + (entrysize * lhsidx) /* start of the entry */ + offset_within; auto rhscmpptr = dmem + (entrysize * rhsidx) + offset_within; // This has been recently cudaMemset'd, so we can do local accumulations and follow them up with global updates SK_UNROLL_4 for(unsigned i = 0; i < bytes_per_thread / 4; ++i) { auto v = __vmaxu4((const uint32_t *)&lhscmpptr[i], (const uint32_t *) rhscmpptr[i]); atomicAdd(&shared[v&0xFF], 1); atomicAdd(&shared[(v>>8)&0xFF], 1); atomicAdd(&shared[(v>>16)&0xFF], 1); atomicAdd(&shared[(v>>24)&0xFF], 1); } if(tid < 64 - p + 1) { if(shared[tid]) { auto v = ::ldexpf(shared[tid], -tid) atomicAdd(drmem + rhsnum, v); } } cudaDeviceSynchronize(); auto gid = threadIdx.x + (blockIdx.x * blockDim.x); if(gid < nelem * round_nrows) { drmem[gid] = alpha * nelem * nelem / drmem[gid];; } } struct GPUDistanceProcessor { protected: uint8_t *dmem_; // device memory (for sketches) void *cmem_; // host memory (for returning values) void *drmem_; // device memory (for holding return values) size_t nelem_; size_t entrysize_; size_t numrows_; uint32_t use_float_:1, use_gz_:1; void *fp_ = nullptr; DeviceStorageFmt storage_ = DEFAULT_6_BIT_HLL; public: auto nelem() const {return nelem_;} auto entrysize() const {return entrysize_;} bool flush_to_file() const { return nelem_ == numrows_; } uint32_t elemsz() const {return use_float_ ? 4: 8;} void perform_flush(size_t nrows=0) { if(nrows == 0) nrows = numrows_; assert(fp_); if(use_gz_) { if(gzwrite(static_cast<gzFile>(fp_), cmem_, nrows * nelem_ * elemsz()) != nelem_ * nrows * elemsz()) throw ZlibError("Failed to write to file\n"); } else { if(std::fwrite(cmem_, elemsz(), nelem_ * nrows, static_cast<std::FILE *>(fp_)) != nelem_ * nrows) throw std::runtime_error("Failed to write to file\n"); } } void open_fp(const char *fp) { if(use_gz_) { if(fp_) gzclose(static_cast<gzFile>(fp_)); fp_ = gzopen(fp, "wb"); } else { if(fp_) std::fclose(static_cast<std::FILE *>(fp_)); fp_ = std::fopen(fp, "w"); } } GPUDistanceProcessor(const GPUDistanceProcessor &) = delete; GPUDistanceProcessor(GPUDistanceProcessor &&o) { std::memset(this, 0, sizeof(*this)); std::swap_ranges(reinterpret_cast<uint8_t *>(this), reinterpret_cast<uint8_t *>(this) + sizeof(*this), reinterpret_cast<uint8_t *>(&o)); } GPUDistanceProcessor() { std::memset(this, 0, sizeof(*this)); } void device_alloc() { size_t nb = entrysize_ * nelem_; cudaError_t ce; if(dmem_ && (ce = cudaFree(dmem_))) throw CudaError(ce, "Failed to free"); if(drmem_ && (ce = cudaFree(drmem_))) throw CudaError(ce, "Failed to free"); if((ce = cudaMalloc((void **)&dmem_, nb))) throw CudaError(ce, "Failed to alloc"); if((ce = cudaMalloc((void **)&drmem_, nelem_ * elemsz() * numrows_))) throw CudaError(ce, "Failed to alloc"); //std::fprintf(stderr, "cudaMalloc'd\nnb: %zu. dmem: %p", nb, (void *)dmem_); } GPUDistanceProcessor(size_t nelem, size_t entrysize, size_t numrows=0, bool use_float=true, bool use_gz=false): nelem_(nelem), entrysize_(entrysize), use_float_(use_float), use_gz_(use_gz) { drmem_ = nullptr; cmem_ = nullptr; dmem_ = nullptr; fp_ = nullptr; numrows_ = numrows == 0 ? nelem_: numrows; // Defaults to full matrix in memory device_alloc(); if((cmem_ = std::malloc((elemsz()) * nelem_ * numrows_)) == nullptr) throw std::bad_alloc(); std::fprintf(stderr, "just malloc'd cmem (%p). first byte: %d\n", (void *)cmem_, ((uint8_t *)cmem_)[0]); #if 0 cudaError_t ce; if((ce = cudaMalloc((void **)&dmem_, nelem * entrysize))) throw CudaError(ce, "Failed to cudamalloc"); #endif } virtual void *row_start(size_t rownum) const { // Override this if you want to skip over the re-computed values return static_cast<void *>(static_cast<uint8_t *>(cmem_) + (nelem_ * elemsz())); } virtual void *sketch_data(size_t index) const { // Override this if you want to skip over the re-computed values //std::fprintf(stderr, "sketch ptr for index %zu is %p + %zu (%p)\n", index, (void *)dmem_, (void *)(static_cast<uint8_t *>(dmem_) + entrysize_ * index)); return static_cast<void *>(static_cast<uint8_t *>(dmem_) + entrysize_ * index); } void process_sketches() { switch(storage_) { case DEFAULT_6_BIT_HLL: process([this](void *drmem, size_t row_index, size_t round_nrows, int tpb, int nblocks){ auto dmem = dmem_; auto n = nelem_; auto p = ilog2(entrysize_); // p is log2 of size in bytes, which means that log2 of remainder is at most 64 - p + 1 auto r = 64 - p + 1; cudaError_t ce; auto alpha = entrysize_ == 16 ? .673: entrysize_ == 32 ? .697: entrysize_ == 64 ? .709: .7213 / (1. + 1.079 / entrysize_); if((ce = cudaMemset(drmem_, 0, round_nrows * elemsz()))) throw CudaError(ce, "Failed to cudaMemset."); if(use_float_) { original_hll_kernel<<<nblocks, tpb, r * sizeof(uint32_t)>>>(dmem, static_cast<float *>(drmem_), n, row_index, round_nrows, tpb, nblocks, p, entrysize_, alpha); } else { original_hll_kernel<<<nblocks, tpb, r * sizeof(uint32_t)>>>(dmem, static_cast<double *>(drmem_), n, row_index, round_nrows, tpb, nblocks, p, entrysize_, alpha); } // 6 bit kernel }); break; case PACKED_4_BIT_HLL: process([dmem=dmem_,n=nelem_,esz=entrysize_](void *drmem, size_t row_index, size_t round_nrows, int tpb, int nblocks){ // 4 bit kernel }); break; case WIDE_8_BIT_HLL: process([dmem=dmem_,n=nelem_,esz=entrysize_](void *drmem, size_t row_index, size_t round_nrows, int tpb, int nblocks){ // 8 bit kernel }); break; case BBMH: process([dmem=dmem_,n=nelem_,esz=entrysize_](void *drmem, size_t row_index, size_t round_nrows, int tpb, int nblocks){ // b-bit kernel }); break; default: { char buf[64]; std::sprintf(buf, "Failed to process; unknown storage type: %d\n", storage_); throw std::runtime_error(buf); } } } template<typename F> void process(const F &f) { // Default, unpacked 8-bit HLLs if(entrysize_ < 1024) throw std::runtime_error("entrysize must be at least 1024. (4 for intrinsics, 256 for threads per block"); assert(entrysize_ % 256 == 0); size_t rind = 0; // Row index constexpr int tpb = 256; int nblocks = (nelem_ * numrows_ * entrysize_ + tpb - 1) / tpb; // This means one per 256 bytes. // TODO: std::thread copy_and_flush; cudaError_t ce; for(size_t tranche = 0, ntranches = (nelem_ - 1 + numrows_) / numrows_; tranche < ntranches; ++tranche) { size_t round_nrows = std::min(numrows_, nelem_ - numrows_); f(static_cast<uint8_t *>(drmem_) + (nelem_ * elemsz() * rind) /* local destination */, rind, round_nrows, tpb, nblocks); #if 0 original_hll_compare<<<nblocks, tpb, 64 * sizeof(uint32_t)>>>( dmem_, /* data = */ drmem_ + (nelem_ * elemsz() * rind), /* local destination */ rind, // round index round_nrows ); #elif 0 packed_hll_compare<<<nblocks, tpb, 64 * sizeof(uint32_t)>>>( dmem_, /* data = */ drmem_ + (nelem_ * elemsz() * rind), /* local destination */ rind, // round index round_nrows ); #endif cudaDeviceSynchronize(); // Ensure computations have completed if(copy_and_flush.joinable()) copy_and_flush.join(); // Ensure that flushing to disk is completed. // At this point, the CPU buffer is available for loading. // TODO: double the memory on the device and compute the next portion // while transferring size_t nb = nelem_ * elemsz() * round_nrows; std::fprintf(stderr, "drmem %p. nb: %zu. round nr: %zu\n", (void *)drmem_, nb, round_nrows); std::fprintf(stderr, "cmem %p\n", (void *)cmem_); if((ce = cudaMemcpy(cmem_/* + (nelem_ * elemsz() * rind)*/, drmem_, nb, cudaMemcpyDeviceToHost))) throw CudaError(ce, "Couldn't copy back to computer\n"); copy_and_flush = std::thread([&](){ this->perform_flush(round_nrows); }); rind += numrows_; } if(copy_and_flush.joinable()) copy_and_flush.join(); } ~GPUDistanceProcessor() { cudaError_t ce; if((ce = cudaFree(dmem_))) { CudaError exception(ce, "Error called in GPUDistanceProcessor. (This will actually cause the program to fail"); std::fprintf(stderr, "not throwing an error to avoid terminating the program. Message: %s\n", exception.what()); } if((ce = cudaFree(drmem_))) { CudaError exception(ce, "Error called in GPUDistanceProcessor. (This will actually cause the program to fail"); std::fprintf(stderr, "not throwing an error to avoid terminating the program. Message: %s\n", exception.what()); } std::free(cmem_); } }; template<typename It> void copy_hlls(GPUDistanceProcessor &gp, It hllstart, It hllend, bool direct=true) { //using HllType = std::add_lvalue_reference_t<std::decay_t<decltype(*hllstart)>>; assert(std::distance(hllstart, hllend) == gp.nelem()); size_t nbper = hllstart->size(); assert(gp.entrysize() == nbper); auto tmp(std::make_unique<uint8_t []>(std::distance(hllstart, hllend) * nbper)); auto dist = std::distance(hllstart, hllend); cudaError_t ce; if(!direct) { OMP_PRAGMA("omp parallel for") for(size_t i = 0; i < dist; ++i) { It it = hllstart; std::advance(it, i); // Usually addition, but different if a weird iterator size_t offset = i * nbper; std::memcpy(tmp.get() + offset, it->data(), nbper); } } else { for(size_t i = 0; i < dist; ++i) { It it = hllstart; std::advance(it, i); // Usually addition, but different if a weird iterator //std::fprintf(stderr, "Index %zu\nCopying %zu bytes to %p from %p\n", i, nbper, (void *)gp.sketch_data(i), (void *)it->data()); if((ce = cudaMemcpy(gp.sketch_data(i), it->data(), nbper, cudaMemcpyHostToDevice))) throw CudaError(ce, "Failed to copy to device"); } } } template<typename It> GPUDistanceProcessor setup_hlls(const char *fn, It hs, It he, int nr, bool direct=true) { GPUDistanceProcessor ret(std::distance(hs, he), hs->size(), nr); ret.open_fp(fn); copy_hlls(ret, hs, he, direct); return ret; } #endif /* #ifdef __CUDACC__ */ } // sketch #endif
the_stack
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <hip/hip_runtime.h> // parameters for device execution #define BLOCK_SIZE 64 #define GRID_SIZE 1500 // parameters for LIBOR calculation #define NN 80 #define NMAT 40 #define L2_SIZE 3280 //NN*(NMAT+1) #define NOPT 15 #define NPATH 96000 #define __fdividef fdividef #define __expf expf /* Monte Carlo LIBOR path calculation */ __device__ void path_calc(float *L, const float *z, const float *lambda, const float delta, const int Nmat, const int N) { int i, n; float sqez, lam, con1, v, vrat; for(n=0; n<Nmat; n++) { sqez = sqrtf(delta)*z[n]; v = 0.f; for (i=n+1; i<N; i++) { lam = lambda[i-n-1]; con1 = delta*lam; v += __fdividef(con1*L[i],1.f+delta*L[i]); vrat = __expf(con1*v + lam*(sqez-0.5f*con1)); L[i] = L[i]*vrat; } } } /* forward path calculation storing data for subsequent reverse path calculation */ __device__ void path_calc_b1(float *L, const float *z, float *L2, const float *lambda, const float delta, const int Nmat, const int N ) { int i, n; float sqez, lam, con1, v, vrat; for (i=0; i<N; i++) L2[i] = L[i]; for(n=0; n<Nmat; n++) { sqez = sqrtf(delta)*z[n]; v = 0.f; for (i=n+1; i<N; i++) { lam = lambda[i-n-1]; con1 = delta*lam; v += __fdividef(con1*L[i],1.f+delta*L[i]); vrat = __expf(con1*v + lam*(sqez-0.5f*con1)); L[i] = L[i]*vrat; // store these values for reverse path // L2[i+(n+1)*N] = L[i]; } } } /* reverse path calculation of deltas using stored data */ __device__ void path_calc_b2(float *L_b, const float *z, const float *L2, const float *lambda, const float delta, const int Nmat, const int N) { int i, n; float faci, v1; for (n=Nmat-1; n>=0; n--) { v1 = 0.f; for (i=N-1; i>n; i--) { v1 += lambda[i-n-1]*L2[i+(n+1)*N]*L_b[i]; faci = __fdividef(delta,1.f+delta*L2[i+n*N]); L_b[i] = L_b[i]*__fdividef(L2[i+(n+1)*N],L2[i+n*N]) + v1*lambda[i-n-1]*faci*faci; } } } /* calculate the portfolio value v, and its sensitivity to L */ /* hand-coded reverse mode sensitivity */ __device__ float portfolio_b(float *L, float *L_b, const float *lambda, const int *maturities, const float *swaprates, const float delta, const int Nmat, const int N, const int Nopt) { int m, n; float b, s, swapval,v; float B[NMAT], S[NMAT], B_b[NMAT], S_b[NMAT]; b = 1.f; s = 0.f; for (m=0; m<N-Nmat; m++) { n = m + Nmat; b = __fdividef(b,1.f+delta*L[n]); s = s + delta*b; B[m] = b; S[m] = s; } v = 0.f; for (m=0; m<NMAT; m++) { B_b[m] = 0.f; S_b[m] = 0.f; } for (n=0; n<Nopt; n++){ m = maturities[n] - 1; swapval = B[m] + swaprates[n]*S[m] - 1.f; if (swapval<0) { v += -100.f*swapval; S_b[m] += -100.f*swaprates[n]; B_b[m] += -100.f; } } for (m=N-Nmat-1; m>=0; m--) { n = m + Nmat; B_b[m] += delta*S_b[m]; L_b[n] = -B_b[m]*B[m]*__fdividef(delta,1.f+delta*L[n]); if (m>0) { S_b[m-1] += S_b[m]; B_b[m-1] += __fdividef(B_b[m],1.f+delta*L[n]); } } // apply discount // b = 1.f; for (n=0; n<Nmat; n++) b = b/(1.f+delta*L[n]); v = b*v; for (n=0; n<Nmat; n++){ L_b[n] = -v*delta/(1.f+delta*L[n]); } for (n=Nmat; n<N; n++){ L_b[n] = b*L_b[n]; } return v; } /* calculate the portfolio value v */ __device__ float portfolio(float *L, const float *lambda, const int *maturities, const float *swaprates, const float delta, const int Nmat, const int N, const int Nopt) { int n, m, i; float v, b, s, swapval, B[40], S[40]; b = 1.f; s = 0.f; for(n=Nmat; n<N; n++) { b = b/(1.f+delta*L[n]); s = s + delta*b; B[n-Nmat] = b; S[n-Nmat] = s; } v = 0.f; for(i=0; i<Nopt; i++){ m = maturities[i] - 1; swapval = B[m] + swaprates[i]*S[m] - 1.f; if(swapval<0) v += -100.f*swapval; } // apply discount // b = 1.f; for (n=0; n<Nmat; n++) b = b/(1.f+delta*L[n]); v = b*v; return v; } __global__ void Pathcalc_Portfolio_KernelGPU(float *d_v, float *d_Lb, const float *lambda, const int *maturities, const float *swaprates, const float delta, const int Nmat, const int N, const int Nopt) { const int tid = blockDim.x * blockIdx.x + threadIdx.x; const int threadN = blockDim.x * gridDim.x; int i,path; float L[NN], L2[L2_SIZE], z[NN]; float *L_b = L; /* Monte Carlo LIBOR path calculation*/ for(path = tid; path < NPATH; path += threadN){ // initialise the data for current thread for (i=0; i<N; i++) { // for real application, z should be randomly generated z[i] = 0.3f; L[i] = 0.05f; } path_calc_b1(L, z, L2, lambda, delta, Nmat, N); d_v[path] = portfolio_b(L, L_b, lambda, maturities, swaprates, delta, Nmat, N, Nopt); path_calc_b2(L_b, z, L2, lambda, delta, Nmat, N); d_Lb[path] = L_b[NN-1]; } } __global__ void Pathcalc_Portfolio_KernelGPU2(float *d_v, const float *lambda, const int *maturities, const float *swaprates, const float delta, const int Nmat, const int N, const int Nopt) { const int tid = blockDim.x * blockIdx.x + threadIdx.x; const int threadN = blockDim.x * gridDim.x; int i, path; float L[NN], z[NN]; /* Monte Carlo LIBOR path calculation*/ for(path = tid; path < NPATH; path += threadN){ // initialise the data for current thread for (i=0; i<N; i++) { // for real application, z should be randomly generated z[i] = 0.3f; L[i] = 0.05f; } path_calc(L, z, lambda, delta, Nmat, N); d_v[path] = portfolio(L, lambda, maturities, swaprates, delta, Nmat, N, Nopt); } } int main(int argc, char **argv){ // 'h_' prefix - CPU (host) memory space float *h_v, *h_Lb, h_lambda[NN], h_delta=0.25f; int h_N=NN, h_Nmat=NMAT, h_Nopt=NOPT, i; int h_maturities[] = {4,4,4,8,8,8,20,20,20,28,28,28,40,40,40}; float h_swaprates[] = {.045f,.05f,.055f,.045f,.05f,.055f,.045f,.05f, .055f,.045f,.05f,.055f,.045f,.05f,.055f }; double v, Lb; // 'd_' prefix - GPU (device) memory space float *d_v; float *d_Lb; float *d_swaprates; float *d_lambda; int *d_maturities; for (i=0; i<NN; i++) h_lambda[i] = 0.2f; h_v = (float *)malloc(sizeof(float)*NPATH); h_Lb = (float *)malloc(sizeof(float)*NPATH); hipMalloc((void**)&d_maturities, sizeof(h_maturities)); hipMalloc((void**)&d_swaprates, sizeof(h_swaprates)); hipMalloc((void**)&d_lambda, sizeof(h_lambda)); hipMalloc((void **)&d_v, sizeof(float)*NPATH); hipMalloc((void **)&d_Lb, sizeof(float)*NPATH); // Execute GPU kernel -- no Greeks dim3 dimBlock(BLOCK_SIZE); dim3 dimGrid(GRID_SIZE); hipMemcpy(d_maturities, h_maturities, sizeof(h_maturities), hipMemcpyHostToDevice); hipMemcpy(d_swaprates, h_swaprates, sizeof(h_swaprates), hipMemcpyHostToDevice); hipMemcpy(d_lambda, h_lambda, sizeof(h_lambda), hipMemcpyHostToDevice); // Launch the device computation threads for (int i = 0; i < 100; i++) hipLaunchKernelGGL(Pathcalc_Portfolio_KernelGPU2, dim3(dimGrid), dim3(dimBlock), 0, 0, d_v, d_lambda, d_maturities, d_swaprates, h_delta, h_Nmat, h_N, h_Nopt); // Read back GPU results and compute average hipMemcpy(h_v, d_v, sizeof(float)*NPATH, hipMemcpyDeviceToHost); v = 0.0; for (i=0; i<NPATH; i++) v += h_v[i]; v = v / NPATH; if (fabs(v - 224.323) > 1e-3) printf("Expected: 224.323 Actual %15.3f\n", v); // Execute GPU kernel -- Greeks // Launch the device computation threads for (int i = 0; i < 100; i++) hipLaunchKernelGGL(Pathcalc_Portfolio_KernelGPU, dim3(dimGrid), dim3(dimBlock), 0, 0, d_v, d_Lb, d_lambda, d_maturities, d_swaprates, h_delta, h_Nmat, h_N, h_Nopt); // Read back GPU results and compute average hipMemcpy(h_v, d_v, sizeof(float)*NPATH, hipMemcpyDeviceToHost); hipMemcpy(h_Lb, d_Lb, sizeof(float)*NPATH, hipMemcpyDeviceToHost); v = 0.0; for (i=0; i<NPATH; i++) v += h_v[i]; v = v / NPATH; Lb = 0.0; for (i=0; i<NPATH; i++) Lb += h_Lb[i]; Lb = Lb / NPATH; if (fabs(v - 224.323) > 1e-3) printf("Expected: 224.323 Actual %15.3f\n", v); if (fabs(Lb - 21.348) > 1e-3) printf("Expected: 21.348 Actual %15.3f\n", Lb); // Release GPU memory hipFree(d_v); hipFree(d_Lb); hipFree(d_maturities); hipFree(d_swaprates); hipFree(d_lambda); // Release CPU memory free(h_v); free(h_Lb); return 0; }
the_stack
#ifndef INCLUDE_GGNN_CACHE_CUDA_SIMPLE_KNN_SYM_CACHE_CUH_ #define INCLUDE_GGNN_CACHE_CUDA_SIMPLE_KNN_SYM_CACHE_CUH_ #include <cuda.h> #include <cuda_runtime.h> #include <cub/cub.cuh> #include <limits> #include "ggnn/utils/cuda_knn_utils.cuh" template <DistanceMeasure measure, typename ValueT, typename KeyT, int KQuery, int D, int BLOCK_DIM_X, int VISITED_SIZE = 256, int PRIOQ_SIZE = 128, int BEST_SIZE = 32, typename BaseT = ValueT, typename BAddrT = KeyT, bool DIST_STATS = false, bool OVERFLOW_STATS = false> struct SimpleKNNSymCache { static constexpr KeyT EMPTY_KEY = (KeyT)-1; static constexpr ValueT EMPTY_DIST = std::numeric_limits<ValueT>::infinity(); // TODO(fabi): change to constant? static constexpr float EPS = 0.1f; private: static constexpr int CACHE_SIZE = BEST_SIZE + PRIOQ_SIZE + VISITED_SIZE; static constexpr int SORTED_SIZE = BEST_SIZE + PRIOQ_SIZE; static constexpr int DIST_ITEMS_PER_THREAD = (D - 1) / BLOCK_DIM_X + 1; static constexpr int BEST_ITEMS_PER_THREAD = (BEST_SIZE - 1) / BLOCK_DIM_X + 1; static constexpr int PRIOQ_ITEMS_PER_THREAD = (PRIOQ_SIZE - 1) / BLOCK_DIM_X + 1; static constexpr int CACHE_ITEMS_PER_THREAD = (CACHE_SIZE - 1) / BLOCK_DIM_X + 1; static constexpr int SORTED_ITEMS_PER_THREAD = (SORTED_SIZE - 1) / BLOCK_DIM_X + 1; static constexpr int BEST_END = BEST_SIZE - 1; struct DistQueryAndHalf { ValueT dist_query; ValueT dist_half; __device__ __forceinline__ DistQueryAndHalf(const ValueT dist_query, const ValueT dist_half) : dist_query(dist_query), dist_half(dist_half) {} __device__ __forceinline__ DistQueryAndHalf() {} }; struct DistanceAndNorm { ValueT r_dist; ValueT r_norm; __device__ __forceinline__ DistanceAndNorm(const ValueT dist, const ValueT norm) : r_dist(dist), r_norm(norm) {} __device__ __forceinline__ DistanceAndNorm() {} struct Sum { __host__ __device__ __forceinline__ DistanceAndNorm operator()(const DistanceAndNorm& a, const DistanceAndNorm& b) const { return DistanceAndNorm(a.r_dist + b.r_dist, a.r_norm + b.r_norm); } }; }; typedef cub::BlockReduce<ValueT, BLOCK_DIM_X> DistReduce; typedef cub::BlockReduce<DistQueryAndHalf, BLOCK_DIM_X> DistQueryAndHalfReduce; union CacheTempStorage { struct { typename DistReduce::TempStorage dist_reduce; typename DistQueryAndHalfReduce::TempStorage dist_query_half_reduce; }; }; union SyncTempStorage { KeyT cache; DistQueryAndHalf dist; bool flag; __device__ __forceinline__ SyncTempStorage() {} }; public: KeyT* s_cache; ValueT* s_dists; int& s_prioQ_head; int& s_visited_head; int& s_overflow_counter; CacheTempStorage& s_storage; SyncTempStorage& s_sync; ValueT criteria_dist; ValueT xi; const BaseT* d_base; BaseT r_query[DIST_ITEMS_PER_THREAD]; ValueT r_half[DIST_ITEMS_PER_THREAD]; // only valid in thread 0 ValueT query_norm; ValueT half_norm; //# threadIdx.x == 0 stats registers only int dist_calc_counter; __device__ __forceinline__ void initSharedStorage() { __shared__ KeyT s_cache_tmp[CACHE_SIZE]; __shared__ ValueT s_dists_tmp[SORTED_SIZE]; s_cache = reinterpret_cast<KeyT*>(s_cache_tmp); s_dists = reinterpret_cast<ValueT*>(s_dists_tmp); } __device__ __forceinline__ CacheTempStorage& CachePrivateTmpStorage() { __shared__ CacheTempStorage cache_tmp_storage; return cache_tmp_storage; } __device__ __forceinline__ SyncTempStorage& SyncPrivateTmpStorage() { __shared__ SyncTempStorage s_sync_tmp; return s_sync_tmp; } __device__ __forceinline__ int& PrioQRingPrivateTmpStorage() { __shared__ int s_prioQ_head_tmp; return s_prioQ_head_tmp; } __device__ __forceinline__ int& CacheRingPrivateTmpStorage() { __shared__ int s_visited_head_tmp; return s_visited_head_tmp; } __device__ __forceinline__ int& OverflowPrivateTmpStorage() { __shared__ int s_overflow_tmp; return s_overflow_tmp; } __device__ __forceinline__ void init() { for (int i = threadIdx.x; i < CACHE_SIZE; i += BLOCK_DIM_X) { s_cache[i] = EMPTY_KEY; } for (int i = threadIdx.x; i < SORTED_SIZE; i += BLOCK_DIM_X) { s_dists[i] = EMPTY_DIST; } if (DIST_STATS && !threadIdx.x) dist_calc_counter = 0; if (OVERFLOW_STATS && !threadIdx.x) s_overflow_counter = 0; if (!threadIdx.x) { s_prioQ_head = 0; s_visited_head = 0; } __syncthreads(); } __device__ __forceinline__ SimpleKNNSymCache(const BaseT* d_base, const KeyT n, const ValueT xi_criteria) : s_storage(CachePrivateTmpStorage()), d_base(d_base), xi(xi_criteria), s_prioQ_head(PrioQRingPrivateTmpStorage()), s_visited_head(CacheRingPrivateTmpStorage()), s_overflow_counter(OverflowPrivateTmpStorage()), s_sync(SyncPrivateTmpStorage()) { initSharedStorage(); init(); loadQueryPos(d_base + static_cast<BAddrT>(n) * D); } __device__ __forceinline__ void loadQueryPos(const BaseT* d_query) { ValueT r_query_norm = 0.0f; for (int item = 0; item < DIST_ITEMS_PER_THREAD; ++item) { const int read_dim = item * BLOCK_DIM_X + threadIdx.x; if (read_dim < D) { r_query[item] = *(d_query + read_dim); if (measure == Cosine) r_query_norm += r_query[item] * r_query[item]; } } if (measure == Cosine) { // only needed by thread 0 query_norm = DistReduce(s_storage.dist_reduce).Sum(r_query_norm); } } __device__ __forceinline__ void init_start_point(const KeyT other_n, const KeyT* d_translation) { init(); const KeyT s = (d_translation == nullptr) ? other_n : d_translation[other_n]; DistQueryAndHalf r_norms(0.0f, 0.0f); for (int item = 0; item < DIST_ITEMS_PER_THREAD; ++item) { const int read_dim = item * BLOCK_DIM_X + threadIdx.x; if (read_dim < D) { r_half[item] = r_query[item] + (0.5f - EPS) * ((d_base[static_cast<BAddrT>(s) * D + read_dim] - r_query[item])); if (measure == Cosine) { r_norms.dist_query += r_query[item] * r_query[item]; r_norms.dist_half += r_half[item] * r_half[item]; } } } __syncthreads(); if (measure == Cosine) { DistQueryAndHalf norms = DistQueryAndHalfReduce(s_storage.dist_query_half_reduce) .Reduce(r_norms, DistSum()); if (!threadIdx.x) { query_norm = norms.dist_query; half_norm = norms.dist_half; } } const DistQueryAndHalf dists = distance_synced(other_n); criteria_dist = dists.dist_half + xi; if (!threadIdx.x) { // Add start point to best list... s_cache[0] = other_n; s_dists[0] = dists.dist_query; // ... and and prioQ. s_cache[BEST_SIZE] = other_n; s_dists[BEST_SIZE] = dists.dist_query; } } struct DistSum { __host__ __device__ __forceinline__ DistQueryAndHalf operator()(const DistQueryAndHalf& a, const DistQueryAndHalf& b) const { return DistQueryAndHalf(a.dist_query + b.dist_query, a.dist_half + b.dist_half); } }; /** * Calculates synced distance of base vector to other_id vector. * * [parallel call]: * ValueT dist = cache.distance(other_id) * * Return: * ValueT distance * * Note: distance valid in all threads. */ __device__ __forceinline__ DistQueryAndHalf distance_synced(const KeyT other_id) { DistQueryAndHalf r_diff(0.f, 0.f); ValueT r_norm_other = 0.0f; for (int item = 0; item < DIST_ITEMS_PER_THREAD; ++item) { const int read_dim = item * BLOCK_DIM_X + threadIdx.x; if (read_dim < D) { const ValueT p = d_base[static_cast<BAddrT>(other_id) * D + read_dim]; if (measure == Euclidean) { const ValueT dist_query = r_query[item] - p; r_diff.dist_query += dist_query * dist_query; const ValueT dist_half = r_half[item] - p; r_diff.dist_half += dist_half * dist_half; } else if (measure == Cosine) { const ValueT dist_query = r_query[item] * p; r_diff.dist_query += dist_query; const ValueT dist_half = r_half[item] * p; r_diff.dist_half += dist_half; r_norm_other += p * p; } } } DistQueryAndHalf aggregate = DistQueryAndHalfReduce(s_storage.dist_query_half_reduce) .Reduce(r_diff, DistSum()); if (measure == Cosine) { // need to normalize by the vectors' lengths (in high dimensions, no // vector has length 1.0f) const ValueT norm_other = DistReduce(s_storage.dist_reduce).Sum(r_norm_other); const ValueT query_norm_sqr = norm_other * query_norm; const ValueT half_norm_sqr = norm_other * half_norm; // use negative dot product, as larger values are closer to each other // otherwise, we would need to adjust each and every distance comparison // in the code if (!threadIdx.x) { if (query_norm_sqr > 0.0f) aggregate.dist_query = fabs(1.0f - aggregate.dist_query / sqrt(query_norm_sqr)); else aggregate.dist_query = 1.0f; // while this could be computed in parallel to the query distance, // the necessary shuffling and synchronization costs more. if (half_norm_sqr > 0.0f) aggregate.dist_half = fabs(1.0f - aggregate.dist_half / sqrt(half_norm_sqr)); else aggregate.dist_half = 1.0f; } } if (!threadIdx.x) { if (DIST_STATS) dist_calc_counter++; s_sync.dist = aggregate; } __syncthreads(); return s_sync.dist; } __device__ __forceinline__ bool criteria(const ValueT dist) { return (dist < (s_dists[0] + xi)); } __device__ __forceinline__ bool criteria(const DistQueryAndHalf& dist) { return ((dist.dist_query < (s_dists[0] + xi)) && (dist.dist_half < criteria_dist)); } __device__ __forceinline__ bool is_end(int tid) { const int prev_prioQ_ring = (s_prioQ_head - 1 < 0) ? PRIOQ_SIZE - 1 : s_prioQ_head - 1; return tid == BEST_END || tid == BEST_SIZE + prev_prioQ_ring; } __device__ __forceinline__ void push(const KeyT key, const ValueT dist) { __syncthreads(); // Register for insertion in best and prioq KeyT r_cache[SORTED_ITEMS_PER_THREAD]; ValueT r_dists[SORTED_ITEMS_PER_THREAD]; int r_write_item_best = -1; int r_write_item_prioQ = -1; if (!threadIdx.x) s_sync.flag = true; __syncthreads(); // Load items for insertion. for (int item = 0; item < SORTED_ITEMS_PER_THREAD && s_sync.flag; ++item) { const int idx = item * BLOCK_DIM_X + threadIdx.x; if (idx < SORTED_SIZE) { r_cache[item] = s_cache[idx]; r_dists[item] = s_dists[idx]; if (r_cache[item] == key) s_sync.flag = false; } } __syncthreads(); // TODO(fabi) return on s_sync.flag = true? for (int item = 0; item < SORTED_ITEMS_PER_THREAD && s_sync.flag; ++item) { const int idx = item * BLOCK_DIM_X + threadIdx.x; if (idx < SORTED_SIZE) { if (r_dists[item] >= dist) { // Don't move if no entry or end of best or prioq. if ((r_cache[item] != EMPTY_KEY) && !is_end(idx)) { const int idx_next = (idx + 1 == SORTED_SIZE) ? BEST_SIZE : idx + 1; s_cache[idx_next] = r_cache[item]; s_dists[idx_next] = r_dists[item]; } // Find insert points. const int idx_prev = idx - 1; const ValueT dist_prev = ((idx_prev == -1) || (idx_prev == BEST_SIZE + s_prioQ_head - 1)) ? -1.f : (idx_prev == BEST_END) ? s_dists[SORTED_SIZE - 1] : s_dists[idx_prev]; if (dist_prev < dist) { if (idx < BEST_SIZE) r_write_item_best = item; else r_write_item_prioQ = item; } } } } __syncthreads(); // Insert into best and prioq. if (r_write_item_best >= 0) { const int idx = r_write_item_best * BLOCK_DIM_X + threadIdx.x; s_cache[idx] = key; s_dists[idx] = dist; } if (r_write_item_prioQ >= 0) { const int idx = r_write_item_prioQ * BLOCK_DIM_X + threadIdx.x; s_cache[idx] = key; s_dists[idx] = dist; } } __device__ __forceinline__ KeyT pop() { __syncthreads(); if (!threadIdx.x) { const int head_idx_prioQ = BEST_SIZE + s_prioQ_head; const ValueT dist = s_dists[head_idx_prioQ]; if (dist == EMPTY_DIST) { // Pop on empty prioQ. s_sync.cache = EMPTY_KEY; } else { if (!criteria(dist)) { s_sync.cache = EMPTY_KEY; } else { const KeyT key = s_cache[head_idx_prioQ]; s_sync.cache = key; const int head_idx_visited = SORTED_SIZE + s_visited_head; s_cache[head_idx_visited] = key; s_visited_head = (s_visited_head + 1) % VISITED_SIZE; } s_cache[head_idx_prioQ] = EMPTY_KEY; s_dists[head_idx_prioQ] = EMPTY_DIST; // Move ring-buffer head forward. s_prioQ_head = (s_prioQ_head + 1) % PRIOQ_SIZE; } } __syncthreads(); return s_sync.cache; } __device__ __forceinline__ void fetch(KeyT* s_keys, const KeyT* d_translation, int len, bool debug = false) { __syncthreads(); for (int item = 0; item < CACHE_ITEMS_PER_THREAD; ++item) { const int i = item * BLOCK_DIM_X + threadIdx.x; if (i < CACHE_SIZE) { const KeyT n = s_cache[i]; for (int k = 0; n != EMPTY_KEY && k < len; k++) { if (n == s_keys[k]) { s_keys[k] = EMPTY_KEY; } } } } for (int k = 0; k < len; k++) { __syncthreads(); const KeyT other_n = s_keys[k]; if (other_n == EMPTY_KEY) continue; const KeyT other_m = (d_translation == nullptr) ? other_n : d_translation[other_n]; const DistQueryAndHalf dist = distance_synced(other_m); if (criteria(dist)) { push(other_n, dist.dist_query); __syncthreads(); } } __syncthreads(); } __device__ __forceinline__ void write_best_graph(KeyT* d_buffer, const KeyT n, int K, int offset = 1) { for (int i = threadIdx.x; i < K; i += BLOCK_DIM_X) { const KeyT idx = s_cache[i + offset]; d_buffer[n * K + i] = (idx != EMPTY_KEY) ? idx : n; } } __device__ __forceinline__ void write_best(KeyT* d_buffer, const KeyT n, int stride) { for (int i = threadIdx.x; i < KQuery; i += BLOCK_DIM_X) { const KeyT idx = s_cache[i]; d_buffer[n * stride + i] = idx; } } __device__ __forceinline__ float get_nn1_dist() { if (measure == Euclidean) { return sqrtf(s_dists[1]); } else if (measure == Cosine) { return s_dists[1]; } // TODO(fabi): restructure or error. return 0; } __device__ __forceinline__ int get_dist_stats() { return dist_calc_counter; } __device__ __forceinline__ int get_overflow_stats() { return s_overflow_counter; } /** * Prints first 'len' elements in the Cache. [parallel call]: * cash.print(8); * */ __device__ __forceinline__ void print(int len = CACHE_SIZE) { __syncthreads(); if (!threadIdx.x) printf("print \n"); if (!threadIdx.x) { printf("Cache: ring: %d KQuery: %f (+xi -> %f) \n", s_prioQ_head, s_dists[KQuery - 1], s_dists[KQuery - 1] + xi); for (int i = 0; i < len; ++i) { if (i < BEST_SIZE) { printf("%d -> %d %f \n", i, s_cache[i], s_dists[i]); } else { if (i < SORTED_SIZE) { printf("%d -> %d %f | ", i, s_cache[i], s_dists[i]); if (i - BEST_SIZE == s_prioQ_head) printf("X"); printf("\n"); } else { printf("%d -> %d | ", i, s_cache[i]); if (i - SORTED_SIZE == s_visited_head) printf("X"); printf("\n"); } } } } __syncthreads(); } }; #endif // INCLUDE_GGNN_CACHE_CUDA_SIMPLE_KNN_SYM_CACHE_CUH_
the_stack
#include "src/DeviceTensorUtils.h" #include "THCTensor.h" #include "cuda/CudaUtils.cuh" #include "cuda/DeviceTensor.cuh" #include "cuda/MemoryAccess.cuh" #include "cuda/util/CachedDeviceProperties.h" #define ENABLE_CUDA_DEBUG #include "cuda/CudaDebugUtils.cuh" #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include <glog/logging.h> using namespace facebook::cuda; namespace facebook { namespace deeplearning { namespace torch { #define LOG_TARGET VLOG(1) // LOG(INFO) template<typename T, int NumThreads, bool affine, typename ComputeT = float> __global__ void SpatialBatchNormalizationUpdateOutputInferenceUnrolled_kernel( const DeviceTensor<T, 4> input, DeviceTensor<T, 4> output, DeviceTensor<T, 1> runningMean, DeviceTensor<T, 1> runningStddev, const DeviceTensor<T, 1> weight, const DeviceTensor<T, 1> bias) { static_assert(std::is_same<ComputeT, double>::value , "type"); auto x = threadIdx.x; auto y = threadIdx.y; auto plane = blockIdx.x; auto batch = blockIdx.y; // stddev is actually 1 / stddev auto stddev = runningStddev[plane].ldg(); auto mean = runningMean[plane].ldg(); auto inp = input[batch][plane][y][x].ldg(); if (affine) { // multiply with gamma and add beta // TODO: everyone pulling this, optimize by reusing better auto beta = bias[plane].ldg(); auto gamma = weight[plane].ldg(); output[batch][plane][y][x] = gamma * (inp - mean) * (stddev) + beta; } else { output[batch][plane][y][x] = (inp - mean) * (stddev); } } template<typename T, int NumThreads, bool affine, typename ComputeT = float> __global__ void SpatialBatchNormalizationUpdateOutputInference_kernel( const DeviceTensor<T, 4> input, DeviceTensor<T, 4> output, DeviceTensor<T, 1> runningMean, DeviceTensor<T, 1> runningStddev, const DeviceTensor<T, 1> weight, const DeviceTensor<T, 1> bias) { static_assert(std::is_same<ComputeT, double>::value , "type"); auto x = threadIdx.x; auto plane = blockIdx.x; auto batch = blockIdx.y; // stddev is actually 1 / stddev auto stddev = runningStddev[plane].ldg(); auto mean = runningMean[plane].ldg(); T beta, gamma; if (affine) { beta = bias[plane].ldg(); gamma = weight[plane].ldg(); } for (auto y = threadIdx.y; y < output.getSize(2); y += blockDim.y) { auto inp = input[batch][plane][y][x].ldg(); if (affine) { // multiply with gamma and add beta // TODO: everyone pulling this, optimize by reusing better output[batch][plane][y][x] = gamma * (inp - mean) * (stddev) + beta; } else { output[batch][plane][y][x] = (inp - mean) * (stddev); } } } template<typename T, int NumThreads, bool affine, typename ComputeT = float> __global__ void SpatialBatchNormalizationUpdateOutput_kernel( const DeviceTensor<T, 4> input, DeviceTensor<T, 4> output, DeviceTensor<T, 4> centered, DeviceTensor<T, 1> std, DeviceTensor<T, 4> normalized, DeviceTensor<T, 1> runningMean, DeviceTensor<T, 1> runningStddev, const DeviceTensor<T, 1> weight, const DeviceTensor<T, 1> bias, T epsilon, T momentum) { static_assert(std::is_same<ComputeT, double>::value , "type"); // Assert powers of 2 for proper intra-warp shuffle reduction assert(blockDim.x == NumThreads); assert(blockDim.y == NumThreads); static_assert((NumThreads & (NumThreads - 1)) == 0, "NumThreads must be a power of 2 for proper warp shuffling"); auto plane = blockIdx.x; auto numBatches = input.getSize(0); auto norm = (T)0; if (threadIdx.y == 0) { norm = input.getSize(0) * input.getSize(2) * input.getSize(3); norm = (T)1 / norm; } // 1. Compute the mean across (batch, y, x), save it and update the // runningMean with momentum auto batchMeanGlobal = (T)0; for (int y = threadIdx.y; y < input.getSize(2); y += NumThreads) { auto batchMeanLocal = (T)0; for (auto batch = 0; batch < numBatches; ++batch) { for (int x = threadIdx.x; x < input.getSize(3); x += NumThreads) { auto inp = (inBounds(y, x, input)) ? input[batch][plane][y][x].ldg() : 0.0f; batchMeanLocal += inp; } } // Reduce within warp for (auto i = 0; i < getMSB(NumThreads); ++i) { batchMeanLocal += __shfl_xor(batchMeanLocal, 1 << i, NumThreads); } // thread 0 has it batchMeanGlobal += batchMeanLocal; } __shared__ T shared[NumThreads]; // thx == 0 stores into smem if (threadIdx.x == 0) { shared[threadIdx.y] = batchMeanGlobal; } __syncthreads(); // 'transpose', and reduce within warp again if (threadIdx.y == 0) { auto batchMeanLocal = shared[threadIdx.x]; // Reduce within warp again for (auto i = 0; i < getMSB(NumThreads); ++i) { batchMeanLocal += __shfl_xor(batchMeanLocal, 1 << i, NumThreads); } // We did an allreduce with xors, this should reduce contention on // shared memory. batchMeanGlobal = batchMeanLocal * norm; // Save the non momentum-altered version to share with everyone shared[threadIdx.x] = batchMeanGlobal; } __syncthreads(); // Everyone picks it up batchMeanGlobal = shared[threadIdx.x]; if (threadIdx.y == 0 && threadIdx.x == 0) { // Momentum based writeback runningMean[plane] = (1 - momentum) * runningMean[plane] + momentum * batchMeanGlobal; } // 2. Compute the stddev across (batch, y, x), // save it // update the runningStddev with momentum // save a copy // All threads have the batchMean now, compute the stddev auto batchStddevGlobal = (T)0; for (int y = threadIdx.y; y < input.getSize(2); y += NumThreads) { auto batchStddevLocal = (T)0; for (auto batch = 0; batch < numBatches; ++batch) { for (int x = threadIdx.x; x < input.getSize(3); x += NumThreads) { auto inp = 0.0f; if (inBounds(y, x, input)) { inp = input[batch][plane][y][x].ldg(); batchStddevLocal += (inp - batchMeanGlobal) * (inp - batchMeanGlobal); centered[batch][plane][y][x] = inp - batchMeanGlobal; } } } // Reduce within warp for (auto i = 0; i < getMSB(NumThreads); ++i) { batchStddevLocal += __shfl_xor(batchStddevLocal, 1 << i, NumThreads); } // thread 0 has it batchStddevGlobal += batchStddevLocal; } // thx == 0 stores into smem, reuse the same smem region, be sure to kill // WAR / WAW dependences even if they are extremely unlikely. __syncthreads(); if (threadIdx.x == 0) { shared[threadIdx.y] = batchStddevGlobal; } __syncthreads(); // 'transpose', and reduce within warp again if (threadIdx.y == 0) { auto batchStddevLocal = shared[threadIdx.x]; // Reduce within warp again for (auto i = 0; i < getMSB(NumThreads); ++i) { batchStddevLocal += __shfl_xor(batchStddevLocal, 1 << i, NumThreads); } // We did an allreduce with xors, this should reduce contention on // shared memory. batchStddevLocal *= norm; batchStddevGlobal = 1 / sqrt(batchStddevLocal + epsilon); // Save the non momentum-altered version to share with everyone shared[threadIdx.x] = batchStddevGlobal; } __syncthreads(); // Everyone picks it up batchStddevGlobal = shared[threadIdx.x]; // Momentum based writeback if (threadIdx.y == 0 && threadIdx.x == 0) { std[plane] = batchStddevGlobal; runningStddev[plane] = (1 - momentum) * runningStddev[plane] + momentum * batchStddevGlobal; } // Write normalized and update the output auto beta = bias[plane]; auto gamma = weight[plane]; for (int y = threadIdx.y; y < input.getSize(2); y += NumThreads) { for (int x = threadIdx.x; x < input.getSize(3); x += NumThreads) { if(inBounds(y, x, output)) { for (auto batch = 0; batch < numBatches; ++batch) { auto inp = input[batch][plane][y][x].ldg(); normalized[batch][plane][y][x] = (inp - batchMeanGlobal) * (batchStddevGlobal); if (affine) { // multiply with gamma and add beta output[batch][plane][y][x] = gamma * (inp - batchMeanGlobal) * (batchStddevGlobal) + beta; } else { output[batch][plane][y][x] = (inp - batchMeanGlobal) * (batchStddevGlobal); } } } } } } template<typename T, int BatchDims, int ImageDims, bool train, bool affine, typename ComputeT = float> void SpatialBatchNormalizationUpdateOutput( const DeviceTensor<T, BatchDims + ImageDims> input, DeviceTensor<T, BatchDims + ImageDims> output, DeviceTensor<T, BatchDims + ImageDims> centered, DeviceTensor<T, 1> std, DeviceTensor<T, BatchDims + ImageDims> normalized, DeviceTensor<T, 1> runningMean, DeviceTensor<T, 1> runningStddev, const DeviceTensor<T, 1> weight, const DeviceTensor<T, 1> bias, T epsilon, T momentum, cudaStream_t s) { static_assert(BatchDims == 2, "BatchDims == 2 only atm"); auto prop = getCurrentDeviceProperties(); if (!train) { if (input.getSize(3) * input.getSize(2) < prop.maxThreadsPerBlock) { dim3 blocks(input.getSize(1), input.getSize(0)); dim3 threads(input.getSize(3), input.getSize(2)); LOG_TARGET << blocks.x << " " << blocks.y << " " << blocks.z << " " << threads.x << " " << threads.y << " " << threads.z; SpatialBatchNormalizationUpdateOutputInferenceUnrolled_kernel <T, 1, affine, ComputeT> <<<blocks, threads, 0, s>>> (input, output, runningMean, runningStddev, weight, bias); } else { CHECK_GE(prop.maxThreadsPerBlock, input.getSize(3)) << "Need a rolled version across both threadIdx.x and y"; dim3 blocks(input.getSize(1), input.getSize(0)); dim3 threads(input.getSize(3), min(input.getSize(2), floor(prop.maxThreadsPerBlock, input.getSize(3))) ); LOG_TARGET << blocks.x << " " << blocks.y << " " << blocks.z << " " << threads.x << " " << threads.y << " " << threads.z; SpatialBatchNormalizationUpdateOutputInference_kernel <T, 1, affine, ComputeT> <<<blocks, threads, 0, s>>> (input, output, runningMean, runningStddev, weight, bias); } } else { dim3 blocks(input.getSize(1)); if (input.getSize(3) >= 16 && input.getSize(2) >= 16) { dim3 threads(16, 16); LOG_TARGET << blocks.x << " " << blocks.y << " " << blocks.z << " " << threads.x << " " << threads.y << " " << threads.z; SpatialBatchNormalizationUpdateOutput_kernel <T, 16, affine, ComputeT> <<<blocks, threads, 0, s>>>(input, output, centered, std, normalized, runningMean, runningStddev, weight, bias, epsilon, momentum); } else { dim3 threads(8, 8); LOG_TARGET << blocks.x << " " << blocks.y << " " << blocks.z << " " << threads.x << " " << threads.y << " " << threads.z; SpatialBatchNormalizationUpdateOutput_kernel <T, 8, affine, ComputeT> <<<blocks, threads, 0, s>>>(input, output, centered, std, normalized, runningMean, runningStddev, weight, bias, epsilon, momentum); } } } extern "C" void SpatialBatchNormalizationUpdateOutputFFI( THCState* state, THCudaTensor* input, THCudaTensor* output, THCudaTensor* centered, THCudaTensor* std, THCudaTensor* normalized, THCudaTensor* runningMean, THCudaTensor* runningStddev, THCudaTensor* weight, THCudaTensor* bias, float epsilon, float momentum, bool train, bool affine) { // The SpatialBatchNormalization lua module is designed for // 4-D only: batch, plane, y, x constexpr int BatchDims = 2; constexpr int ImageDims = 2; typedef double ComputeT; if (!train) { if (!affine) { // Collapse SpatialBatchNormalizationUpdateOutput <float, BatchDims, ImageDims, false, false, ComputeT> ( torchToDeviceTensor<float, BatchDims + ImageDims>(state, input), torchToDeviceTensor<float, BatchDims + ImageDims>(state, output), DeviceTensor<float, BatchDims + ImageDims>(), DeviceTensor<float, 1>(), DeviceTensor<float, BatchDims + ImageDims>(), torchToDeviceTensor<float, 1>(state, runningMean), torchToDeviceTensor<float, 1>(state, runningStddev), DeviceTensor<float, 1>(), DeviceTensor<float, 1>(), epsilon, momentum, THCState_getCurrentStream(state) ); } else { // Collapse SpatialBatchNormalizationUpdateOutput <float, BatchDims, ImageDims, false, true, ComputeT> ( torchToDeviceTensor<float, BatchDims + ImageDims>(state, input), torchToDeviceTensor<float, BatchDims + ImageDims>(state, output), DeviceTensor<float, BatchDims + ImageDims>(), DeviceTensor<float, 1>(), DeviceTensor<float, BatchDims + ImageDims>(), torchToDeviceTensor<float, 1>(state, runningMean), torchToDeviceTensor<float, 1>(state, runningStddev), torchToDeviceTensor<float, 1>(state, weight), torchToDeviceTensor<float, 1>(state, bias), epsilon, momentum, THCState_getCurrentStream(state) ); } } else { if (!affine) { SpatialBatchNormalizationUpdateOutput <float, BatchDims, ImageDims, true, false, ComputeT> ( torchToDeviceTensor<float, BatchDims + ImageDims>(state, input), torchToDeviceTensor<float, BatchDims + ImageDims>(state, output), torchToDeviceTensor<float, BatchDims + ImageDims>(state, centered), torchToDeviceTensor<float, 1>(state, std), torchToDeviceTensor<float, BatchDims + ImageDims>(state, normalized), torchToDeviceTensor<float, 1>(state, runningMean), torchToDeviceTensor<float, 1>(state, runningStddev), DeviceTensor<float, 1>(), DeviceTensor<float, 1>(), epsilon, momentum, THCState_getCurrentStream(state) ); } else { SpatialBatchNormalizationUpdateOutput <float, BatchDims, ImageDims, true, true, ComputeT> ( torchToDeviceTensor<float, BatchDims + ImageDims>(state, input), torchToDeviceTensor<float, BatchDims + ImageDims>(state, output), torchToDeviceTensor<float, BatchDims + ImageDims>(state, centered), torchToDeviceTensor<float, 1>(state, std), torchToDeviceTensor<float, BatchDims + ImageDims>(state, normalized), torchToDeviceTensor<float, 1>(state, runningMean), torchToDeviceTensor<float, 1>(state, runningStddev), torchToDeviceTensor<float, 1>(state, weight), torchToDeviceTensor<float, 1>(state, bias), epsilon, momentum, THCState_getCurrentStream(state) ); } } THCudaCheck(cudaGetLastError()); } template<typename T, int NumThreads, bool affine, typename ComputeT = float> __global__ void SpatialBatchNormalizationUpdateGradInput_kernel( DeviceTensor<T, 4> gradInput, const DeviceTensor<T, 4> gradOutput, DeviceTensor<T, 4> centered, DeviceTensor<T, 1> std, const DeviceTensor<T, 1> weight) { static_assert(std::is_same<ComputeT, double>::value , "type"); // Assert powers of 2 for proper intra-warp shuffle reduction assert(blockDim.x == NumThreads); assert(blockDim.y == NumThreads); static_assert((NumThreads & (NumThreads - 1)) == 0, "NumThreads must be a power of 2 for proper warp shuffling"); auto plane = blockIdx.x; auto numBatches = gradInput.getSize(0); auto norm = (T)0; if (threadIdx.y == 0) { norm = gradInput.getSize(0) * gradInput.getSize(2) * gradInput.getSize(3); norm = (T)1 / norm; } // 1. Compute means across (batch, y, x) auto gradMeanGlobal = (T)0; auto centeredGradMeanGlobal = (T)0; for (int y = threadIdx.y; y < gradInput.getSize(2); y += NumThreads) { auto gradMeanLocal = (T)0; auto centeredGradMeanLocal = (T)0; for (auto batch = 0; batch < numBatches; ++batch) { for (int x = threadIdx.x; x < gradInput.getSize(3); x += NumThreads) { auto g = (inBounds(y, x, gradOutput)) ? gradOutput[batch][plane][y][x].ldg() : 0.0f; auto c = (inBounds(y, x, centered)) ? centered[batch][plane][y][x].ldg() : 0.0f; gradMeanLocal += g; centeredGradMeanLocal += c * g; } } // Reduce within warp for (auto i = 0; i < getMSB(NumThreads); ++i) { gradMeanLocal += __shfl_xor(gradMeanLocal, 1 << i, NumThreads); centeredGradMeanLocal += __shfl_xor(centeredGradMeanLocal, 1 << i, NumThreads); } // thread 0 has it gradMeanGlobal += gradMeanLocal; centeredGradMeanGlobal += centeredGradMeanLocal; } __shared__ T shared[2][NumThreads]; // thx == 0 stores into smem if (threadIdx.x == 0) { shared[0][threadIdx.y] = gradMeanGlobal; shared[1][threadIdx.y] = centeredGradMeanGlobal; } __syncthreads(); // 'transpose', and reduce within warp again if (threadIdx.y == 0) { auto gradMeanLocal = shared[0][threadIdx.x]; auto centeredGradMeanLocal = shared[1][threadIdx.x]; // Reduce within warp again for (auto i = 0; i < getMSB(NumThreads); ++i) { gradMeanLocal += __shfl_xor(gradMeanLocal, 1 << i, NumThreads); centeredGradMeanLocal += __shfl_xor(centeredGradMeanLocal, 1 << i, NumThreads); } // We did an allreduce with xors, this should reduce contention on // shared memory. gradMeanGlobal = gradMeanLocal * norm; centeredGradMeanGlobal = centeredGradMeanLocal * norm; // Save the non momentum-altered version to share with everyone shared[0][threadIdx.x] = gradMeanGlobal; shared[1][threadIdx.x] = centeredGradMeanGlobal; } __syncthreads(); // Everyone picks it up, should be broadcast into the whole gradInput gradMeanGlobal = shared[0][threadIdx.x]; centeredGradMeanGlobal = shared[1][threadIdx.x]; auto stdVal = std[plane]; for (int y = threadIdx.y; y < gradInput.getSize(2); y += NumThreads) { for (auto batch = 0; batch < numBatches; ++batch) { for (int x = threadIdx.x; x < gradInput.getSize(3); x += NumThreads) { if (affine) { gradInput[batch][plane][y][x] = ( - centeredGradMeanGlobal * centered[batch][plane][y][x] * stdVal * stdVal + gradOutput[batch][plane][y][x] - gradMeanGlobal ) * stdVal * weight[plane]; } else { gradInput[batch][plane][y][x] = ( - centeredGradMeanGlobal * centered[batch][plane][y][x] * stdVal * stdVal + gradOutput[batch][plane][y][x] - gradMeanGlobal ) * stdVal; } } } } } template<typename T, int BatchDims, int ImageDims, bool affine, typename ComputeT = float> void SpatialBatchNormalizationUpdateGradInput( DeviceTensor<T, BatchDims + ImageDims> gradInput, const DeviceTensor<T, BatchDims + ImageDims> gradOutput, DeviceTensor<T, BatchDims + ImageDims> centered, DeviceTensor<T, 1> std, const DeviceTensor<T, 1> weight, cudaStream_t s) { static_assert(BatchDims == 2, "BatchDims == 2 only atm"); dim3 blocks(gradInput.getSize(1)); if (gradInput.getSize(3) >= 16 && gradInput.getSize(2) >= 16) { dim3 threads(16, 16); LOG_TARGET << blocks.x << " " << blocks.y << " " << blocks.z << " " << threads.x << " " << threads.y << " " << threads.z; SpatialBatchNormalizationUpdateGradInput_kernel <T, 16, affine, ComputeT> <<<blocks, threads, 0, s>>>(gradInput, gradOutput, centered, std, weight); } else { dim3 threads(8, 8); LOG_TARGET << blocks.x << " " << blocks.y << " " << blocks.z << " " << threads.x << " " << threads.y << " " << threads.z; SpatialBatchNormalizationUpdateGradInput_kernel <T, 8, affine, ComputeT> <<<blocks, threads, 0, s>>>(gradInput, gradOutput, centered, std, weight); } } extern "C" void SpatialBatchNormalizationUpdateGradInputFFI( THCState* state, THCudaTensor* gradInput, THCudaTensor* gradOutput, THCudaTensor* centered, THCudaTensor* std, THCudaTensor* weight, bool affine) { // The SpatialBatchNormalization lua module is designed for // 4-D only: batch, plane, y, x constexpr int BatchDims = 2; constexpr int ImageDims = 2; typedef double ComputeT; if (!affine) { // Collapse SpatialBatchNormalizationUpdateGradInput <float, BatchDims, ImageDims, false, ComputeT> ( torchToDeviceTensor<float, BatchDims + ImageDims>(state, gradInput), torchToDeviceTensor<float, BatchDims + ImageDims>(state, gradOutput), torchToDeviceTensor<float, BatchDims + ImageDims>(state, centered), torchToDeviceTensor<float, 1>(state, std), DeviceTensor<float, 1>(), THCState_getCurrentStream(state) ); } else { // Collapse SpatialBatchNormalizationUpdateGradInput <float, BatchDims, ImageDims, true, ComputeT> ( torchToDeviceTensor<float, BatchDims + ImageDims>(state, gradInput), torchToDeviceTensor<float, BatchDims + ImageDims>(state, gradOutput), torchToDeviceTensor<float, BatchDims + ImageDims>(state, centered), torchToDeviceTensor<float, 1>(state, std), torchToDeviceTensor<float, 1>(state, weight), THCState_getCurrentStream(state) ); } THCudaCheck(cudaGetLastError()); } template<typename T, int NumThreads, typename ComputeT = float> __global__ void SpatialBatchNormalizationAccGradParameters_kernel( const DeviceTensor<T, 4> gradOutput, const DeviceTensor<T, 4> normalized, DeviceTensor<T, 1> gradWeight, DeviceTensor<T, 1> gradBias, T scale) { static_assert(std::is_same<ComputeT, double>::value , "type"); // Assert powers of 2 for proper intra-warp shuffle reduction assert(blockDim.x == NumThreads); assert(blockDim.y == NumThreads); static_assert((NumThreads & (NumThreads - 1)) == 0, "NumThreads must be a power of 2 for proper warp shuffling"); auto plane = blockIdx.x; auto numBatches = gradOutput.getSize(0); // 1. Compute sums across (batch, y, x) auto gradMeanGlobal = (T)0; auto normalizedGradMeanGlobal = (T)0; for (int y = threadIdx.y; y < gradOutput.getSize(2); y += NumThreads) { auto gradMeanLocal = (T)0; auto normalizedGradMeanLocal = (T)0; for (auto batch = 0; batch < numBatches; ++batch) { for (int x = threadIdx.x; x < gradOutput.getSize(3); x += NumThreads) { auto g = (inBounds(y, x, gradOutput)) ? gradOutput[batch][plane][y][x].ldg() : 0.0f; auto n = (inBounds(y, x, normalized)) ? normalized[batch][plane][y][x].ldg() : 0.0f; gradMeanLocal += g; normalizedGradMeanLocal += n * g; } } // Reduce within warp for (auto i = 0; i < getMSB(NumThreads); ++i) { gradMeanLocal += __shfl_xor(gradMeanLocal, 1 << i, NumThreads); normalizedGradMeanLocal += __shfl_xor(normalizedGradMeanLocal, 1 << i, NumThreads); } // thread 0 has it gradMeanGlobal += gradMeanLocal; normalizedGradMeanGlobal += normalizedGradMeanLocal; } __shared__ T shared[2][NumThreads]; // thx == 0 stores into smem if (threadIdx.x == 0) { shared[0][threadIdx.y] = gradMeanGlobal; shared[1][threadIdx.y] = normalizedGradMeanGlobal; } __syncthreads(); // 'transpose', and reduce within warp again if (threadIdx.y == 0) { auto gradMeanLocal = shared[0][threadIdx.x]; auto normalizedGradMeanLocal = shared[1][threadIdx.x]; // Reduce within warp again for (auto i = 0; i < getMSB(NumThreads); ++i) { gradMeanLocal += __shfl_xor(gradMeanLocal, 1 << i, NumThreads); normalizedGradMeanLocal += __shfl_xor(normalizedGradMeanLocal, 1 << i, NumThreads); } // We did an allreduce with xors, this should reduce contention on // shared memory. gradMeanGlobal = gradMeanLocal; normalizedGradMeanGlobal = normalizedGradMeanLocal; // thread 0 has it if (threadIdx.x == 0) { gradBias[plane] += scale * gradMeanGlobal; gradWeight[plane] += scale * normalizedGradMeanGlobal; } } } template<typename T, int BatchDims, int ImageDims, typename ComputeT = float> void SpatialBatchNormalizationAccGradParameters( const DeviceTensor<T, BatchDims + ImageDims> gradOutput, const DeviceTensor<T, BatchDims + ImageDims> normalized, DeviceTensor<T, 1> gradWeight, DeviceTensor<T, 1> gradBias, T scale, cudaStream_t s) { static_assert(BatchDims == 2, "BatchDims == 2 only atm"); dim3 blocks(gradOutput.getSize(1)); if (gradOutput.getSize(3) >= 16 && gradOutput.getSize(2) >= 16) { dim3 threads(16, 16); LOG_TARGET << blocks.x << " " << blocks.y << " " << blocks.z << " " << threads.x << " " << threads.y << " " << threads.z; SpatialBatchNormalizationAccGradParameters_kernel<T, 16, ComputeT> <<<blocks, threads, 0, s>>>(gradOutput, normalized, gradWeight, gradBias, scale); } else { dim3 threads(8, 8); LOG_TARGET << blocks.x << " " << blocks.y << " " << blocks.z << " " << threads.x << " " << threads.y << " " << threads.z; SpatialBatchNormalizationAccGradParameters_kernel<T, 8, ComputeT> <<<blocks, threads, 0, s>>>(gradOutput, normalized, gradWeight, gradBias, scale); } } extern "C" void SpatialBatchNormalizationAccGradParametersFFI( THCState* state, THCudaTensor* gradOutput, THCudaTensor* normalized, THCudaTensor* gradWeight, THCudaTensor* gradBias, float scale) { // The SpatialBatchNormalization lua module is designed for // 4-D only: batch, plane, y, x constexpr int BatchDims = 2; constexpr int ImageDims = 2; typedef double ComputeT; // Collapse SpatialBatchNormalizationAccGradParameters <float, BatchDims, ImageDims, ComputeT> ( torchToDeviceTensor<float, BatchDims + ImageDims>(state, gradOutput), torchToDeviceTensor<float, BatchDims + ImageDims>(state, normalized), torchToDeviceTensor<float, 1>(state, gradWeight), torchToDeviceTensor<float, 1>(state, gradBias), scale, THCState_getCurrentStream(state) ); THCudaCheck(cudaGetLastError()); } }}}
the_stack
* \test Tests routines for matrix-vector operaions (BLAS level 2) using integer arithmetic. **/ // // *** System // #include <iostream> #include <vector> // // *** ViennaCL // //#define VIENNACL_DEBUG_ALL #include "viennacl/scalar.hpp" #include "viennacl/matrix.hpp" #include "viennacl/vector.hpp" #include "viennacl/linalg/prod.hpp" #include "viennacl/linalg/norm_2.hpp" #include "viennacl/linalg/direct_solve.hpp" #include "viennacl/linalg/lu.hpp" #include "viennacl/linalg/sum.hpp" // // ------------------------------------------------------------- // template<typename ScalarType> ScalarType diff(ScalarType & s1, viennacl::scalar<ScalarType> & s2) { viennacl::backend::finish(); if (s1 != s2) return 1; return 0; } template<typename ScalarType, typename VCLVectorType> ScalarType diff(std::vector<ScalarType> const & v1, VCLVectorType const & v2) { std::vector<ScalarType> v2_cpu(v2.size()); viennacl::backend::finish(); //workaround for a bug in APP SDK 2.7 on Trinity APUs (with Catalyst 12.8) viennacl::copy(v2.begin(), v2.end(), v2_cpu.begin()); for (unsigned int i=0;i<v1.size(); ++i) { if (v2_cpu[i] != v1[i]) return 1; } return 0; } template<typename NumericT, typename VCLMatrixType> NumericT diff(std::vector<std::vector<NumericT> > const & mat1, VCLMatrixType const & mat2) { std::vector<std::vector<NumericT> > mat2_cpu(mat2.size1(), std::vector<NumericT>(mat2.size2())); viennacl::backend::finish(); //workaround for a bug in APP SDK 2.7 on Trinity APUs (with Catalyst 12.8) viennacl::copy(mat2, mat2_cpu); for (unsigned int i = 0; i < mat2_cpu.size(); ++i) { for (unsigned int j = 0; j < mat2_cpu[i].size(); ++j) { if (mat2_cpu[i][j] != mat1[i][j]) return 1; } } //std::cout << ret << std::endl; return 0; } // // ------------------------------------------------------------- // template<typename NumericT, typename STLMatrixType, typename STLVectorType, typename VCLMatrixType, typename VCLVectorType1, typename VCLVectorType2> int test_prod_rank1(STLMatrixType & std_m1, STLVectorType & std_v1, STLVectorType & std_v2, VCLMatrixType & vcl_m1, VCLVectorType1 & vcl_v1, VCLVectorType2 & vcl_v2) { int retval = EXIT_SUCCESS; // sync data: std_v1 = std::vector<NumericT>(std_v1.size(), NumericT(2)); std_v2 = std::vector<NumericT>(std_v2.size(), NumericT(3)); viennacl::copy(std_v1.begin(), std_v1.end(), vcl_v1.begin()); viennacl::copy(std_v2.begin(), std_v2.end(), vcl_v2.begin()); viennacl::copy(std_m1, vcl_m1); // -------------------------------------------------------------------------- std::cout << "Rank 1 update" << std::endl; for (std::size_t i=0; i<std_m1.size(); ++i) for (std::size_t j=0; j<std_m1[i].size(); ++j) std_m1[i][j] += std_v1[i] * std_v2[j]; vcl_m1 += viennacl::linalg::outer_prod(vcl_v1, vcl_v2); if ( diff(std_m1, vcl_m1) != 0 ) { std::cout << "# Error at operation: rank 1 update" << std::endl; std::cout << " diff: " << diff(std_m1, vcl_m1) << std::endl; return EXIT_FAILURE; } // -------------------------------------------------------------------------- std::cout << "Scaled rank 1 update - CPU Scalar" << std::endl; for (std::size_t i=0; i<std_m1.size(); ++i) for (std::size_t j=0; j<std_m1[i].size(); ++j) std_m1[i][j] += NumericT(4) * std_v1[i] * std_v2[j]; vcl_m1 += NumericT(2) * viennacl::linalg::outer_prod(vcl_v1, vcl_v2); vcl_m1 += viennacl::linalg::outer_prod(vcl_v1, vcl_v2) * NumericT(2); //check proper compilation if ( diff(std_m1, vcl_m1) != 0 ) { std::cout << "# Error at operation: scaled rank 1 update - CPU Scalar" << std::endl; std::cout << " diff: " << diff(std_m1, vcl_m1) << std::endl; return EXIT_FAILURE; } // -------------------------------------------------------------------------- std::cout << "Scaled rank 1 update - GPU Scalar" << std::endl; for (std::size_t i=0; i<std_m1.size(); ++i) for (std::size_t j=0; j<std_m1[i].size(); ++j) std_m1[i][j] += NumericT(4) * std_v1[i] * std_v2[j]; vcl_m1 += viennacl::scalar<NumericT>(2) * viennacl::linalg::outer_prod(vcl_v1, vcl_v2); vcl_m1 += viennacl::linalg::outer_prod(vcl_v1, vcl_v2) * viennacl::scalar<NumericT>(2); //check proper compilation if ( diff(std_m1, vcl_m1) != 0 ) { std::cout << "# Error at operation: scaled rank 1 update - GPU Scalar" << std::endl; std::cout << " diff: " << diff(std_m1, vcl_m1) << std::endl; return EXIT_FAILURE; } //reset vcl_matrix: viennacl::copy(std_m1, vcl_m1); // -------------------------------------------------------------------------- std::cout << "Matrix-Vector product" << std::endl; for (std::size_t i=0; i<std_m1.size(); ++i) { NumericT temp = 0; for (std::size_t j=0; j<std_m1[i].size(); ++j) temp += std_m1[i][j] * std_v2[j]; std_v1[i] = temp; } std_v1 = viennacl::linalg::prod(std_m1, std_v2); vcl_v1 = viennacl::linalg::prod(vcl_m1, vcl_v2); if ( diff(std_v1, vcl_v1) != 0 ) { std::cout << "# Error at operation: matrix-vector product" << std::endl; std::cout << " diff: " << diff(std_v1, vcl_v1) << std::endl; retval = EXIT_FAILURE; } // -------------------------------------------------------------------------- std::cout << "Matrix-Vector product with scaled add" << std::endl; NumericT alpha = static_cast<NumericT>(2); NumericT beta = static_cast<NumericT>(3); viennacl::copy(std_v1.begin(), std_v1.end(), vcl_v1.begin()); viennacl::copy(std_v2.begin(), std_v2.end(), vcl_v2.begin()); for (std::size_t i=0; i<std_m1.size(); ++i) { NumericT temp = 0; for (std::size_t j=0; j<std_m1[i].size(); ++j) temp += std_m1[i][j] * std_v2[j]; std_v1[i] = alpha * temp + beta * std_v1[i]; } vcl_v1 = alpha * viennacl::linalg::prod(vcl_m1, vcl_v2) + beta * vcl_v1; if ( diff(std_v1, vcl_v1) != 0 ) { std::cout << "# Error at operation: matrix-vector product with scaled additions" << std::endl; std::cout << " diff: " << diff(std_v1, vcl_v1) << std::endl; retval = EXIT_FAILURE; } // -------------------------------------------------------------------------- viennacl::copy(std_v1.begin(), std_v1.end(), vcl_v1.begin()); viennacl::copy(std_v2.begin(), std_v2.end(), vcl_v2.begin()); std::cout << "Transposed Matrix-Vector product" << std::endl; for (std::size_t i=0; i<std_m1[0].size(); ++i) { NumericT temp = 0; for (std::size_t j=0; j<std_m1.size(); ++j) temp += std_m1[j][i] * std_v1[j]; std_v2[i] = alpha * temp; } vcl_v2 = alpha * viennacl::linalg::prod(trans(vcl_m1), vcl_v1); if ( diff(std_v2, vcl_v2) != 0 ) { std::cout << "# Error at operation: transposed matrix-vector product" << std::endl; std::cout << " diff: " << diff(std_v2, vcl_v2) << std::endl; retval = EXIT_FAILURE; } std::cout << "Transposed Matrix-Vector product with scaled add" << std::endl; for (std::size_t i=0; i<std_m1[0].size(); ++i) { NumericT temp = 0; for (std::size_t j=0; j<std_m1.size(); ++j) temp += std_m1[j][i] * std_v1[j]; std_v2[i] = alpha * temp + beta * std_v2[i]; } vcl_v2 = alpha * viennacl::linalg::prod(trans(vcl_m1), vcl_v1) + beta * vcl_v2; if ( diff(std_v2, vcl_v2) != 0 ) { std::cout << "# Error at operation: transposed matrix-vector product with scaled additions" << std::endl; std::cout << " diff: " << diff(std_v2, vcl_v2) << std::endl; retval = EXIT_FAILURE; } // -------------------------------------------------------------------------- std::cout << "Row sum with matrix" << std::endl; for (std::size_t i=0; i<std_m1.size(); ++i) { NumericT temp = 0; for (std::size_t j=0; j<std_m1[i].size(); ++j) temp += std_m1[i][j]; std_v1[i] = temp; } vcl_v1 = viennacl::linalg::row_sum(vcl_m1); if ( diff(std_v1, vcl_v1) != 0 ) { std::cout << "# Error at operation: row sum" << std::endl; std::cout << " diff: " << diff(std_v1, vcl_v1) << std::endl; retval = EXIT_FAILURE; } // -------------------------------------------------------------------------- std::cout << "Row sum with matrix expression" << std::endl; for (std::size_t i=0; i<std_m1.size(); ++i) { NumericT temp = 0; for (std::size_t j=0; j<std_m1[i].size(); ++j) temp += std_m1[i][j] + std_m1[i][j]; std_v1[i] = temp; } vcl_v1 = viennacl::linalg::row_sum(vcl_m1 + vcl_m1); if ( diff(std_v1, vcl_v1) != 0 ) { std::cout << "# Error at operation: row sum (with expression)" << std::endl; std::cout << " diff: " << diff(std_v1, vcl_v1) << std::endl; retval = EXIT_FAILURE; } // -------------------------------------------------------------------------- std::cout << "Column sum with matrix" << std::endl; for (std::size_t i=0; i<std_m1[0].size(); ++i) { NumericT temp = 0; for (std::size_t j=0; j<std_m1.size(); ++j) temp += std_m1[j][i]; std_v2[i] = temp; } vcl_v2 = viennacl::linalg::column_sum(vcl_m1); if ( diff(std_v2, vcl_v2) != 0 ) { std::cout << "# Error at operation: column sum" << std::endl; std::cout << " diff: " << diff(std_v2, vcl_v2) << std::endl; retval = EXIT_FAILURE; } // -------------------------------------------------------------------------- std::cout << "Column sum with matrix expression" << std::endl; for (std::size_t i=0; i<std_m1[0].size(); ++i) { NumericT temp = 0; for (std::size_t j=0; j<std_m1.size(); ++j) temp += std_m1[j][i] + std_m1[j][i]; std_v2[i] = temp; } vcl_v2 = viennacl::linalg::column_sum(vcl_m1 + vcl_m1); if ( diff(std_v2, vcl_v2) != 0 ) { std::cout << "# Error at operation: column sum (with expression)" << std::endl; std::cout << " diff: " << diff(std_v2, vcl_v2) << std::endl; retval = EXIT_FAILURE; } // -------------------------------------------------------------------------- return retval; } // // ------------------------------------------------------------- // template< typename NumericT, typename F> int test() { int retval = EXIT_SUCCESS; std::size_t num_rows = 141; std::size_t num_cols = 103; // -------------------------------------------------------------------------- std::vector<NumericT> std_v1(num_rows); for (std::size_t i = 0; i < std_v1.size(); ++i) std_v1[i] = NumericT(i); std::vector<NumericT> std_v2 = std::vector<NumericT>(num_cols, NumericT(3)); std::vector<std::vector<NumericT> > std_m1(std_v1.size(), std::vector<NumericT>(std_v2.size())); std::vector<std::vector<NumericT> > std_m2(std_v1.size(), std::vector<NumericT>(std_v1.size())); for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); for (std::size_t i = 0; i < std_m2.size(); ++i) for (std::size_t j = 0; j < std_m2[i].size(); ++j) std_m2[i][j] = NumericT(j - i*j + i); viennacl::vector<NumericT> vcl_v1_native(std_v1.size()); viennacl::vector<NumericT> vcl_v1_large(4 * std_v1.size()); viennacl::vector_range< viennacl::vector<NumericT> > vcl_v1_range(vcl_v1_large, viennacl::range(3, std_v1.size() + 3)); viennacl::vector_slice< viennacl::vector<NumericT> > vcl_v1_slice(vcl_v1_large, viennacl::slice(2, 3, std_v1.size())); viennacl::vector<NumericT> vcl_v2_native(std_v2.size()); viennacl::vector<NumericT> vcl_v2_large(4 * std_v2.size()); viennacl::vector_range< viennacl::vector<NumericT> > vcl_v2_range(vcl_v2_large, viennacl::range(8, std_v2.size() + 8)); viennacl::vector_slice< viennacl::vector<NumericT> > vcl_v2_slice(vcl_v2_large, viennacl::slice(6, 2, std_v2.size())); viennacl::matrix<NumericT, F> vcl_m1_native(std_m1.size(), std_m1[0].size()); viennacl::matrix<NumericT, F> vcl_m1_large(4 * std_m1.size(), 4 * std_m1[0].size()); viennacl::matrix_range< viennacl::matrix<NumericT, F> > vcl_m1_range(vcl_m1_large, viennacl::range(8, std_m1.size() + 8), viennacl::range(std_m1[0].size(), 2 * std_m1[0].size()) ); viennacl::matrix_slice< viennacl::matrix<NumericT, F> > vcl_m1_slice(vcl_m1_large, viennacl::slice(6, 2, std_m1.size()), viennacl::slice(std_m1[0].size(), 2, std_m1[0].size()) ); // // Run a bunch of tests for rank-1-updates, matrix-vector products // std::cout << "------------ Testing rank-1-updates and matrix-vector products ------------------" << std::endl; std::cout << "* m = full, v1 = full, v2 = full" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_native, vcl_v1_native, vcl_v2_native); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = full, v1 = full, v2 = range" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_native, vcl_v1_native, vcl_v2_range); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = full, v1 = full, v2 = slice" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_native, vcl_v1_native, vcl_v2_slice); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); // v1 = range std::cout << "* m = full, v1 = range, v2 = full" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_native, vcl_v1_range, vcl_v2_native); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = full, v1 = range, v2 = range" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_native, vcl_v1_range, vcl_v2_range); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = full, v1 = range, v2 = slice" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_native, vcl_v1_range, vcl_v2_slice); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); // v1 = slice std::cout << "* m = full, v1 = slice, v2 = full" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_native, vcl_v1_slice, vcl_v2_native); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = full, v1 = slice, v2 = range" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_native, vcl_v1_slice, vcl_v2_range); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = full, v1 = slice, v2 = slice" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_native, vcl_v1_slice, vcl_v2_slice); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); ///////////////////////////// matrix_range std::cout << "* m = range, v1 = full, v2 = full" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_range, vcl_v1_native, vcl_v2_native); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = range, v1 = full, v2 = range" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_range, vcl_v1_native, vcl_v2_range); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = range, v1 = full, v2 = slice" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_range, vcl_v1_native, vcl_v2_slice); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); // v1 = range std::cout << "* m = range, v1 = range, v2 = full" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_range, vcl_v1_range, vcl_v2_native); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = range, v1 = range, v2 = range" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_range, vcl_v1_range, vcl_v2_range); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = range, v1 = range, v2 = slice" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_range, vcl_v1_range, vcl_v2_slice); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); // v1 = slice std::cout << "* m = range, v1 = slice, v2 = full" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_range, vcl_v1_slice, vcl_v2_native); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = range, v1 = slice, v2 = range" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_range, vcl_v1_slice, vcl_v2_range); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = range, v1 = slice, v2 = slice" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_range, vcl_v1_slice, vcl_v2_slice); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); ///////////////////////////// matrix_slice std::cout << "* m = slice, v1 = full, v2 = full" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_slice, vcl_v1_native, vcl_v2_native); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = slice, v1 = full, v2 = range" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_slice, vcl_v1_native, vcl_v2_range); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = slice, v1 = full, v2 = slice" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_slice, vcl_v1_native, vcl_v2_slice); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); // v1 = range std::cout << "* m = slice, v1 = range, v2 = full" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_slice, vcl_v1_range, vcl_v2_native); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = slice, v1 = range, v2 = range" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_slice, vcl_v1_range, vcl_v2_range); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = slice, v1 = range, v2 = slice" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_slice, vcl_v1_range, vcl_v2_slice); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); // v1 = slice std::cout << "* m = slice, v1 = slice, v2 = full" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_slice, vcl_v1_slice, vcl_v2_native); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = slice, v1 = slice, v2 = range" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_slice, vcl_v1_slice, vcl_v2_range); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; for (std::size_t i = 0; i < std_m1.size(); ++i) for (std::size_t j = 0; j < std_m1[i].size(); ++j) std_m1[i][j] = NumericT(i+j); std::cout << "* m = slice, v1 = slice, v2 = slice" << std::endl; retval = test_prod_rank1<NumericT>(std_m1, std_v1, std_v2, vcl_m1_slice, vcl_v1_slice, vcl_v2_slice); if (retval == EXIT_FAILURE) { std::cout << " --- FAILED! ---" << std::endl; return retval; } else std::cout << " --- PASSED ---" << std::endl; return retval; } // // ------------------------------------------------------------- // int main() { std::cout << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << "## Test :: Matrix" << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << std::endl; int retval = EXIT_SUCCESS; std::cout << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << std::endl; { typedef int NumericT; std::cout << "# Testing setup:" << std::endl; std::cout << " numeric: int" << std::endl; std::cout << " layout: row-major" << std::endl; retval = test<NumericT, viennacl::row_major>(); if ( retval == EXIT_SUCCESS ) std::cout << "# Test passed" << std::endl; else return retval; } std::cout << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << std::endl; { typedef int NumericT; std::cout << "# Testing setup:" << std::endl; std::cout << " numeric: int" << std::endl; std::cout << " layout: column-major" << std::endl; retval = test<NumericT, viennacl::column_major>(); if ( retval == EXIT_SUCCESS ) std::cout << "# Test passed" << std::endl; else return retval; } std::cout << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << std::endl; { typedef long NumericT; std::cout << "# Testing setup:" << std::endl; std::cout << " numeric: long" << std::endl; std::cout << " layout: row-major" << std::endl; retval = test<NumericT, viennacl::row_major>(); if ( retval == EXIT_SUCCESS ) std::cout << "# Test passed" << std::endl; else return retval; } std::cout << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << std::endl; { typedef long NumericT; std::cout << "# Testing setup:" << std::endl; std::cout << " numeric: long" << std::endl; std::cout << " layout: column-major" << std::endl; retval = test<NumericT, viennacl::column_major>(); if ( retval == EXIT_SUCCESS ) std::cout << "# Test passed" << std::endl; else return retval; } std::cout << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << "------- Test completed --------" << std::endl; std::cout << std::endl; return retval; }
the_stack
#include <cassert> #include <cuda_bf16.h> #include <cuda_fp16.h> #include "ln.h" //////////////////////////////////////////////////////////////////////////////////////////////////// constexpr uint32_t THREADS_PER_WARP = 32; //////////////////////////////////////////////////////////////////////////////////////////////////// inline void check_cuda_(cudaError_t status, const char *file, int line) { if( status != cudaSuccess ) { fprintf(stderr, "CUDA Error: %s %s %d\n", cudaGetErrorString(status), file, line); exit(status); } } //////////////////////////////////////////////////////////////////////////////////////////////////// #define CHECK_CUDA(ans) \ { check_cuda_((ans), __FILE__, __LINE__); } //////////////////////////////////////////////////////////////////////////////////////////////////// #define DIVUP(x, y) (((x) + ((y)-1)) / (y)) //////////////////////////////////////////////////////////////////////////////////////////////////// #define REGISTER_FWD_LAUNCHER(HIDDEN_SIZE, WTYPE, ITYPE, OTYPE, CTYPE, CTAS_PER_ROW, WARPS_M, WARPS_N, BYTES_PER_LDG) \ void ln_fwd_##HIDDEN_SIZE##_##WTYPE##_##ITYPE##_##OTYPE##_##CTYPE(LaunchParams<FwdParams> &launch_params, \ const bool configure_params) { \ launch_<WTYPE, ITYPE, OTYPE, CTYPE, uint32_t, HIDDEN_SIZE, CTAS_PER_ROW, WARPS_M, WARPS_N, BYTES_PER_LDG>( \ launch_params, configure_params); \ } \ static FwdRegistrar<WTYPE, ITYPE, OTYPE, CTYPE, HIDDEN_SIZE> reg_##HIDDEN_SIZE##_##WTYPE##_##ITYPE##_##OTYPE##_##CTYPE( \ ln_fwd_##HIDDEN_SIZE##_##WTYPE##_##ITYPE##_##OTYPE##_##CTYPE) //////////////////////////////////////////////////////////////////////////////////////////////////// #define REGISTER_BWD_LAUNCHER( \ HIDDEN_SIZE, WTYPE, ITYPE, OTYPE, CTYPE, CTAS_PER_ROW, WARPS_M, WARPS_N, BYTES_PER_LDG, BYTES_PER_LDG_FINALIZE) \ void ln_bwd_##HIDDEN_SIZE##_##WTYPE##_##ITYPE##_##OTYPE##_##CTYPE(LaunchParams<BwdParams> &launch_params, \ const bool configure_params) { \ launch_<WTYPE, \ ITYPE, \ OTYPE, \ CTYPE, \ uint32_t, \ HIDDEN_SIZE, \ CTAS_PER_ROW, \ WARPS_M, \ WARPS_N, \ BYTES_PER_LDG, \ BYTES_PER_LDG_FINALIZE>(launch_params, configure_params); \ } \ static BwdRegistrar<WTYPE, ITYPE, OTYPE, CTYPE, HIDDEN_SIZE> reg_##HIDDEN_SIZE##_##WTYPE##_##ITYPE##_##OTYPE##_##CTYPE( \ ln_bwd_##HIDDEN_SIZE##_##WTYPE##_##ITYPE##_##OTYPE##_##CTYPE) //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ float2 operator+(const float2 & a, const float2 & b){ return {a.x + b.x, a.y + b.y}; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void operator+=(float2 & a, const float2 & b){ a.x += b.x; a.y += b.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T> struct Sum { inline __device__ Sum(){} inline __device__ T operator()(const T &a, const T &b){ return a + b; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T> inline __device__ T warp_shuffle_xor(const T & x, uint32_t idx){ return __shfl_xor_sync(uint32_t(-1), x, idx); } template<> inline __device__ float2 warp_shuffle_xor<float2>(const float2 & x, uint32_t idx){ return { warp_shuffle_xor(x.x, idx), warp_shuffle_xor(x.y, idx) }; } template<typename T> inline __device__ T warp_shuffle_down(const T & x, uint32_t idx){ return __shfl_down_sync(uint32_t(-1), x, idx); } template<> inline __device__ float2 warp_shuffle_down<float2>(const float2 & x, uint32_t idx){ return { warp_shuffle_down(x.x, idx), warp_shuffle_down(x.y, idx) }; } //////////////////////////////////////////////////////////////////////////////////////////////////// namespace layer_norm { //////////////////////////////////////////////////////////////////////////////////////////////////// struct uint16 { uint4 u; uint4 v; uint4 s; uint4 t; }; //////////////////////////////////////////////////////////////////////////////////////////////////// struct uint8 { uint4 u; uint4 v; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<int BYTES> struct BytesToType {}; template<> struct BytesToType<64> { using Type = uint16; static_assert(sizeof(Type) == 64); }; template<> struct BytesToType<32> { using Type = uint8; static_assert(sizeof(Type) == 32); }; template<> struct BytesToType<16> { using Type = uint4; static_assert(sizeof(Type) == 16); }; template<> struct BytesToType<8> { using Type = uint64_t; static_assert(sizeof(Type) == 8); }; template<> struct BytesToType<4> { using Type = uint32_t; static_assert(sizeof(Type) == 4); }; template<> struct BytesToType<2> { using Type = uint16_t; static_assert(sizeof(Type) == 2); }; template<> struct BytesToType<1> { using Type = uint8_t; static_assert(sizeof(Type) == 1); }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T> struct TypeToVec2 {}; template<> struct TypeToVec2<float> { using Type = float2; }; template<> struct TypeToVec2<half> { using Type = half2; }; template<> struct TypeToVec2<nv_bfloat16> { using Type = nv_bfloat162; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<int INDEX> struct Get { template<typename T, typename R> static inline __device__ R of(const T &vec); }; template<> template<typename T, typename R> inline __device__ R Get<0>::of(const T &vec) { return vec.x; } template<> template<typename T, typename R> inline __device__ R Get<1>::of(const T &vec) { return vec.y; } template<> template<typename T, typename R> inline __device__ R Get<2>::of(const T &vec) { return vec.z; } template<> template<typename T, typename R> inline __device__ R Get<3>::of(const T &vec) { return vec.w; } //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename Src, typename Dst> struct Converter{ static inline __device__ Dst convert(const Src &from) { return Dst(from); } }; template<> struct Converter<float2, half2>{ static inline __device__ half2 convert(const float2 &x) { return __float22half2_rn(x); } }; template<> struct Converter<float2, nv_bfloat162>{ static inline __device__ nv_bfloat162 convert(const float2 &x) { #if __CUDA_ARCH__ >= 800 return __float22bfloat162_rn(x); #else union { nv_bfloat162 raw; nv_bfloat16 x; nv_bfloat16 y; } tmp; tmp.x = __float2bfloat16_rn(x.x); tmp.y = __float2bfloat16_rn(x.y); return tmp.raw; #endif } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T> struct Zeros{ static inline __device__ T get() { return T(0.f); } }; template<> struct Zeros<float2>{ static inline __device__ float2 get() { return make_float2(0.f, 0.f); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename Elt_type, uint32_t NUM_ELT> struct Vec { enum { BYTES = NUM_ELT * sizeof(Elt_type) }; using Vec_type = typename BytesToType<BYTES>::Type; using Alias_type = union { Vec_type vec; Elt_type elt[NUM_ELT]; }; Alias_type data; template<typename S> inline __device__ void to(Vec<S, NUM_ELT> &other) { #pragma unroll for( int it = 0; it < NUM_ELT; it++ ) { other.data.elt[it] = S(this->data.elt[it]); } } template<typename Op> inline __device__ void assign(const Op &op) { #pragma unroll for( int it = 0; it < NUM_ELT; it++ ) { this->data.elt[it] = op(it); } } inline __device__ void load_from(const void *base_ptr, const size_t idx) { this->data.vec = static_cast<const Vec_type *>(base_ptr)[idx]; } inline __device__ void store_to(void *base_ptr, const size_t idx) { static_cast<Vec_type *>(base_ptr)[idx] = this->data.vec; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<uint32_t CTAS_PER_ROW> struct InterCTASync { template<typename Params> inline __device__ InterCTASync(Params & params, uint32_t bidm, uint32_t bidn) : phase_counter_(0) , b0_(params.barrier + bidm) // The barrier for this group of CTAs. , b1_(params.barrier + bidm + params.ctas_per_col) // The barrier for this group of CTAs. { // BARRIERS ARE ASSUMED TO BE INITIALIZED TO 0! } inline __device__ void spin_wait_(int *barrier, int step, int expected) { asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(barrier), "r"(step)); for( int found = -1; found != expected; ) { asm volatile("ld.global.acquire.gpu.b32 %0, [%1];" : "=r"(found) : "l"(barrier)); } } inline __device__ void sync(){ // ALL THREADS MUST ENTER! // We switch barrier every iteration. int *barrier = phase_counter_ & 0x1 ? b1_ : b0_; // We decrement every other iteration. bool dec = phase_counter_ & 0x2; int step = dec ? -1 : 1; int expected = dec ? 0 : CTAS_PER_ROW; // There are only 4 phases: up/down for b0/b1. phase_counter_ = (phase_counter_ + 1) & 0x3; if( threadIdx.x == 0 ) { spin_wait_(barrier, step, expected); } // CTA waits for thread 0 __syncthreads(); } int phase_counter_; int * b0_; int * b1_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T, uint32_t CTAS_PER_ROW, uint32_t WARPS_M, uint32_t WARPS_N> struct Reducer : public Reducer<T, 1, WARPS_M, WARPS_N> { using InterCTASync = InterCTASync<CTAS_PER_ROW>; using Base = Reducer<T, 1, WARPS_M, WARPS_N>; using Type = typename Base::Type; enum { SMEM_BYTES = Base::SMEM_BYTES }; enum { WS_BARRIER_BYTES = 2 * sizeof(int) }; enum { WS_DATA_BYTES = WARPS_M * CTAS_PER_ROW * sizeof(T) }; // size of the barriers + temporary result per CTA (multiply with CTAS_PER_ROW to get total) enum { WORKSPACE_BYTES_PER_GROUP = Base::WORKSPACE_BYTES_PER_GROUP + WS_BARRIER_BYTES + WS_DATA_BYTES }; template<typename Params> inline __device__ Reducer(Params & params, uint32_t bidm, uint32_t bidn, uint32_t warp_m, uint32_t warp_n, uint32_t lane, void * smem) : Base(params, bidm, bidn, warp_m, warp_n, lane, smem) , inter_cta_(params, bidm, bidn) , bidn_(bidn) // CTA id within the group. , w0_(static_cast<T*>(params.workspace) + (bidm * WARPS_M + warp_m) * CTAS_PER_ROW) , w1_(w0_ + params.ctas_per_col * WARPS_M * CTAS_PER_ROW) { } template<typename Op> inline __device__ T allreduce(T data, Op &op) { data = Base::reduce(data, op); // We switch workspace every iteration. T *workspace = inter_cta_.phase_counter_ & 0x1 ? w1_ : w0_; // Warp leaders 0 hold the CTA-local results. if( this->warp_n_ == 0 && this->lane_ == 0 ) { workspace[bidn_] = data; } inter_cta_.sync(); static_assert(CTAS_PER_ROW <= 32); T total = Zeros<T>::get(); if(this->lane_ < CTAS_PER_ROW){ total = workspace[this->lane_]; } total = Reducer<T, 1, 1, 1>::allreduce_(total, op); return total; } InterCTASync inter_cta_; T *w0_; T *w1_; int bidn_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T, uint32_t WARPS_M> struct Reducer<T, 1, WARPS_M, 1> { using Type = T; enum { SMEM_BYTES = 0 }; enum { WORKSPACE_BYTES_PER_GROUP = 0 }; enum { THREADS_PER_WARP = 32 }; template<typename Params> inline __device__ Reducer(Params & params, uint32_t bidm, uint32_t bidn, uint32_t warp_m, uint32_t warp_n, uint32_t lane, void * smem) : warp_n_(warp_n) , lane_(lane) { } template<typename Op> static inline __device__ T allreduce_(T data, Op &op) { #pragma unroll for( int it = 1; it < THREADS_PER_WARP; it *= 2 ) { data = op(data, warp_shuffle_xor(data, it)); } return data; } template<typename Op> inline __device__ T allreduce(T data, Op &op) { return allreduce_(data, op); } template<typename Op> inline __device__ T reduce(T data, Op &op){ // only lane 0 holds the result! #pragma unroll for( int it = THREADS_PER_WARP / 2; it > 0; it /= 2 ) { data = op(data, warp_shuffle_down(data, it)); } return data; } int warp_n_; int lane_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T, uint32_t WARPS_M, uint32_t WARPS_N> struct Reducer<T, 1, WARPS_M, WARPS_N> : public Reducer<T, 1, WARPS_M, 1> { using Base = Reducer<T, 1, WARPS_M, 1>; using Type = T; enum { SMEM_BYTES = Base::SMEM_BYTES + WARPS_M * WARPS_N * sizeof(T) * 2 }; enum { WORKSPACE_BYTES_PER_GROUP = 0 }; enum { THREADS_PER_WARP = 32 }; template<typename Params> inline __device__ Reducer(Params & params, uint32_t bidm, uint32_t bidn, uint32_t warp_m, uint32_t warp_n, uint32_t lane, void * smem) : Base(params, bidm, bidn, warp_m, warp_n, lane, smem) , use0_(true) { smem0_ = &static_cast<T *>(smem)[warp_m * WARPS_N]; smem1_ = smem0_ + WARPS_M * WARPS_N; } template<typename Op> inline __device__ T allreduce(T data, Op & op) { T * smem = use0_ ? smem0_ : smem1_; use0_ = !use0_; data = Base::reduce(data, op); if( this->lane_ == 0 ) { smem[this->warp_n_] = data; } __syncthreads(); T out = Zeros<T>::get(); #pragma unroll for( int it = 0; it < WARPS_N; it++ ) { out = op(out, smem[it]); } return out; } template<typename Op> inline __device__ T reduce(T data, Op &op) { T * smem = use0_ ? smem0_ : smem1_; use0_ = !use0_; // only intra-CTA group leader holds the result! data = Base::reduce(data, op); if( this->lane_ == 0 ) { smem[this->warp_n_] = data; } __syncthreads(); T out = Zeros<T>::get(); if( this->warp_n_ == 0 && this->lane_ == 0 ) { #pragma unroll for( int it = 0; it < WARPS_N; it++ ) { out = op(out, smem[it]); } } return out; } T * smem0_; T * smem1_; bool use0_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T> inline __device__ void warp_chan_upd_dynamic(T &m_a, T &m2_a, T &n_a, int num_active){ //Assume at least leftmost is valid and init: step = next_pow2(num_active) / 2 (might get NaN otherwise) int highest_bit_set = (8 * sizeof(num_active)) - __clz(num_active - 1); #pragma unroll for( int step = (1 << (highest_bit_set - 1)); step > 0; step /= 2 ) { // Exchange T n_b = warp_shuffle_down(n_a, step); T m_b = warp_shuffle_down(m_a, step); T m2_b = warp_shuffle_down(m2_a, step); // Update const T n_ab = n_a + n_b; // We can handle one of them being 0, not both. const T rn_ab = 1.f / n_ab; // Might have different n per thread, otherwise this would simplify :( const T delta = m_a - m_b; const float m2_ab = m2_a + m2_b + delta * delta * n_a * n_b * rn_ab; const float m_ab = (n_a * m_a + n_b * m_b) * rn_ab; n_a = n_ab; m_a = m_ab; m2_a = m2_ab; } // Intra-warp broadcast (only lane 0 has valid stats). m_a = __shfl_sync(uint32_t(-1), m_a, 0); m2_a = __shfl_sync(uint32_t(-1), m2_a, 0); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T, uint32_t CTAS_PER_ROW, uint32_t WARPS_M, uint32_t WARPS_N> struct Stats { // This could be done generically with the Reducer. But then we would have to exchange 3 instead of 2 fields. using InterCTASync = InterCTASync<CTAS_PER_ROW>; using BlockStats = Stats<T, 1, WARPS_M, WARPS_N>; using stats_t = typename BlockStats::stats_t; enum { SMEM_BYTES = BlockStats::SMEM_BYTES }; template<typename Params> inline __device__ Stats(Params & params, uint32_t bidm, uint32_t bidn, uint32_t warp_m, uint32_t warp_n, uint32_t lane, void * smem) : inter_cta_(params, bidm, bidn) , block_stats_(params, bidm, bidn, warp_m, warp_n, lane, smem) , bidn_(bidn) // CTA id within the group. , w0_(static_cast<stats_t*>(params.workspace) + (bidm * WARPS_M + warp_m) * CTAS_PER_ROW) , w1_(w0_ + params.ctas_per_col * WARPS_M * CTAS_PER_ROW) , warp_n_(warp_n) , lane_(lane) { } template<uint32_t N> inline __device__ stats_t compute(const T (&elts)[N], const T rn) { constexpr T ELTS_PER_ROW_PER_CTA = N * WARPS_N * THREADS_PER_WARP; // TODO rn is not really needed here.. constexpr T block_rn = 1.f / T(ELTS_PER_ROW_PER_CTA); stats_t block_stats = block_stats_.compute(elts, block_rn); stats_t *workspace = inter_cta_.phase_counter_ & 0x1 ? w1_ : w0_; if( warp_n_ == 0 && lane_ == 0 ) { workspace[bidn_] = block_stats; } // Wait for all CTAS_PER_ROW CTAS in the group to have written their result. inter_cta_.sync(); T n = Zeros<T>::get(); T m = Zeros<T>::get(); T m2 = Zeros<T>::get(); // Assume CTA group size in N less than 32, such that we can finalize with a single warp. static_assert(CTAS_PER_ROW <= 32); // Every warp does the final reduction locally. if( lane_ < CTAS_PER_ROW ) { stats_t result = workspace[lane_]; n = ELTS_PER_ROW_PER_CTA; m = layer_norm::Get<0>::of<stats_t, T>(result); m2 = layer_norm::Get<1>::of<stats_t, T>(result); } warp_chan_upd_dynamic(m, m2, n, CTAS_PER_ROW); return { m, m2 }; } InterCTASync inter_cta_; BlockStats block_stats_; stats_t *w0_; stats_t *w1_; int bidn_; int warp_n_; int lane_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T, uint32_t WARPS_M, uint32_t WARPS_N> struct Stats<T, 1, WARPS_M, WARPS_N> { using WarpStats = Stats<T, 1, WARPS_M, 1>; using stats_t = typename WarpStats::stats_t; enum { SMEM_BYTES = WARPS_M * WARPS_N * sizeof(stats_t) * 2 }; template<typename Params> inline __device__ Stats(Params & params, uint32_t bidm, uint32_t bidn, uint32_t warp_m, uint32_t warp_n, uint32_t lane, void * smem) : warp_stats_(params, bidm, bidn, warp_m, warp_n, lane, smem) , use0_(true) { smem0_ = static_cast<stats_t*>(smem) + warp_m * WARPS_N; smem1_ = smem0_ + WARPS_M * WARPS_N; } template<uint32_t N> inline __device__ stats_t compute(const T (&elts)[N], const T rn) { stats_t * smem = use0_ ? smem0_ : smem1_; use0_ = !use0_; // Compute warp local for all WARPS_N constexpr T warp_rn = 1.f / T(N * THREADS_PER_WARP); stats_t warp_stats = warp_stats_.compute(elts, warp_rn); //Each warp warp leader stores its stats const auto warp_n = warp_stats_.reducer_.warp_n_; const auto lane = warp_stats_.reducer_.lane_; if( lane == 0 ) { smem[warp_n] = warp_stats; } __syncthreads(); T n = Zeros<T>::get(); T m = Zeros<T>::get(); T m2 = Zeros<T>::get(); // Assume that there are less than 32 warps, such that we can finalize with a single warp static_assert(WARPS_N <= 32); if(lane < WARPS_N){ stats_t result = smem[lane]; n = N * THREADS_PER_WARP; m = layer_norm::Get<0>::of<stats_t, T>(result); m2 = layer_norm::Get<1>::of<stats_t, T>(result); } warp_chan_upd_dynamic(m, m2, n, WARPS_N); return { m, m2 }; } WarpStats warp_stats_; stats_t * smem0_; stats_t * smem1_; bool use0_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T, uint32_t WARPS_M> struct Stats<T, 1, WARPS_M, 1> { using stats_t = typename TypeToVec2<T>::Type; // The simple Warp reducer. using Reducer = Reducer<T, 1, WARPS_M, 1>; enum { SMEM_BYTES = 0 }; template<typename Params> inline __device__ Stats(Params & params, uint32_t bidm, uint32_t bidn, uint32_t warp_m, uint32_t warp_n, uint32_t lane, void * smem) : reducer_(params, bidm, bidn, warp_m, warp_n, lane, smem) { } template<uint32_t N> inline __device__ stats_t compute(const T (&elts)[N], const T rn) { auto sum = Sum<T>(); T m = Zeros<T>::get(); #pragma unroll for( int it = 0; it < N; it++ ) { m += elts[it]; } m = reducer_.allreduce(m, sum) * rn; T m2 = Zeros<T>::get(); #pragma unroll for( int it = 0; it < N; it++ ) { T diff = (elts[it] - m); m2 += diff * diff; } m2 = reducer_.allreduce(m2, sum); return {m, m2}; } Reducer reducer_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace layer_norm
the_stack
#include <thread> #include <unordered_map> #include <cuda_runtime.h> #include <pybind11/numpy.h> #ifndef NO_FAISS #include "faiss/gpu/GpuIndexFlat.h" #include "faiss/gpu/StandardGpuResources.h" #endif #include "graph.cuh" #include "core/solver.h" #include "model/visualization.h" #include "gpu/visualization.cuh" namespace py = pybind11; /** * @page Graph & High-dimensional Data Visualization * * Graph & high-dimensional data visualization is an instantiation of the system. * The visualization process can be seen as training 2d or 3d embeddings for a * graph, or a KNN graph built on high-dimensional vectors. * * In visualization, there is only one embedding matrix, namely the coordinates. * The coordinates are related to both head and tail partitions, * and we implement them in a way similar to knowledge graph embedding. * * Currently, our visualization solver supports LargeVis. * * Reference: * * 1) LargeVis * https://arxiv.org/pdf/1602.00370.pdf * */ namespace graphvite { template<class _KNNGraph> class KNNWorker { public: typedef _KNNGraph KNNGraph; typedef typename KNNGraph::Index Index; KNNGraph *graph; int device_id; #ifndef NO_FAISS faiss::gpu::StandardGpuResources resources; faiss::gpu::GpuIndexFlatConfig config; std::shared_ptr<faiss::gpu::GpuIndexFlatL2> index; #endif KNNWorker(KNNGraph *_graph, int _device_id) : graph(_graph), device_id(_device_id) { #ifndef NO_FAISS config.device = device_id; #endif } void build() { #ifndef NO_FAISS index = std::make_shared<faiss::gpu::GpuIndexFlatL2>(&resources, graph->dim, config); #endif } void search(Index start, Index end) { #ifndef NO_FAISS index->add(graph->num_vertex, graph->vectors.data()); // faiss returns squared l2 distances index->search(end - start, &graph->vectors[start], graph->num_neighbor + 1, &graph->distances[start], &graph->labels[start]); index->reset(); #endif } }; /** * K-nearest neighbor graphs * * Reference: * * 1) LargeVis * https://arxiv.org/pdf/1602.00370.pdf * * @tparam _Index integral type of node indexes */ template<class _Index = size_t> class KNNGraph : public Graph<_Index> { public: typedef Graph<_Index> Base; typedef KNNWorker<KNNGraph> KNNWorker; USING_GRAPH(Base); typedef _Index Index; int dim, num_neighbor; float perplexity; bool vector_normalization; int num_worker, num_thread; std::vector<float> vectors; #ifndef NO_FAISS std::vector<faiss::Index::distance_t> distances; std::vector<faiss::Index::idx_t> labels; #endif std::vector<KNNWorker *> workers; /** * @brief Construct a KNN graph * @param device_ids list of GPU ids, {} for auto * @param num_thread_per_worker number of CPU thread per GPU */ KNNGraph(std::vector<int> device_ids = {}, int num_thread_per_worker = kAuto) { if (device_ids.empty()) { CUDA_CHECK(cudaGetDeviceCount(&num_worker)); CHECK(num_worker) << "No GPU devices found"; for (int i = 0; i < num_worker; i++) device_ids.push_back(i); } else num_worker = device_ids.size(); if (num_thread_per_worker == kAuto) num_thread_per_worker = std::thread::hardware_concurrency() / num_worker; num_thread = num_thread_per_worker * num_worker; LOG_IF(WARNING, num_thread > std::thread::hardware_concurrency()) << "#CPU threads is beyond the hardware concurrency"; #ifdef NO_FAISS LOG(FATAL) << "GraphVite is not compiled with FAISS enabled"; #endif for (auto &&device_id : device_ids) workers.push_back(new KNNWorker(this, device_id)); } ~KNNGraph() { for (auto &&worker : workers) delete worker; } /** Clear the graph and free CPU memory */ void clear() override { Base::clear(); as_undirected = true; dim = 0; } inline std::string name() const override { std::stringstream ss; ss << "KNNGraph<" << pretty::type2name<Index>() << ">"; return ss.str(); } inline std::string graph_info() const override { std::stringstream ss; ss << "#vertex: " << num_vertex << ", #nearest neighbor: " << num_neighbor << std::endl; ss << "perplexity: " << perplexity << ", vector normalization: " << pretty::yes_no(vector_normalization); return ss.str(); } /** Normalize the input vectors. This function can be parallelized. */ void normalize_vector(int start, int end) { for (int i = start; i < end; i++) { double mean = 0; for (Index j = i; j < num_vertex * dim; j += dim) mean += vectors[j]; mean /= num_vertex; float max = 0; for (Index j = i; j < num_vertex * dim; j += dim) { vectors[j] -= mean; max = std::max(max, abs(vectors[j])); } for (Index j = i; j < num_vertex * dim; j += dim) vectors[j] /= (max + kEpsilon); } } /** Compute the weight for each edge. This function can be parallelized. */ void compute_weight(Index start, Index end) { #ifndef NO_FAISS for (Index i = start; i < end; i++) { vertex_edges[i].resize(num_neighbor); for (int j = 0; j < num_neighbor; j++) { int k = i * (num_neighbor + 1) + j + 1; vertex_edges[i][j] = std::make_tuple(labels[k], distances[k]); } float norm = 0, entropy; for (auto &&vertex_edge : vertex_edges[i]) { float weight = std::get<1>(vertex_edge); norm += weight; } float low = -1, high = -1, beta = 1; for (int j = 0; j < 100; j++) { norm = 0; entropy = 0; for (auto &&vertex_edge : vertex_edges[i]) { float weight = std::get<1>(vertex_edge); norm += std::exp(-beta * weight); entropy += beta * weight * std::exp(-beta * weight); } entropy = entropy / norm + log(norm); if (abs(entropy - log(perplexity)) < 1e-5) break; if (entropy > log(perplexity)) { low = beta; beta = high < 0 ? beta * 2 : (beta + high) / 2; } else { high = beta; beta = low < 0 ? beta / 2 : (beta + high) / 2; } } for (auto &&vertex_edge : vertex_edges[i]) { float &weight = std::get<1>(vertex_edge); weight = exp(-beta * weight) / norm; } vertex_weights[i] = 1; } #endif } /** Symmetrize the graph. This function can be parallelized. */ void symmetrize(Index start, Index end) { for (Index i = start; i < end; i++) for (auto &&edge_i : vertex_edges[i]) { Index j = std::get<0>(edge_i); if (i < j) for (auto &&edge_j : vertex_edges[j]) if (std::get<0>(edge_j) == i) { float weight = (std::get<1>(edge_i) + std::get<1>(edge_j)) / 2; std::get<1>(edge_i) = weight; std::get<1>(edge_j) = weight; break; } } } /** Build the KNN graph from input vectors */ void build() { #ifndef NO_FAISS num_vertex = vectors.size() / dim; num_edge = num_vertex * num_neighbor; distances.resize(num_vertex * (num_neighbor + 1)); labels.resize(num_vertex * (num_neighbor + 1)); vertex_edges.resize(num_vertex); vertex_weights.resize(num_vertex, 0); for (auto &&worker : workers) worker->build(); std::vector<std::thread> worker_threads(num_worker); std::vector<std::thread> build_threads(num_thread); if (vector_normalization) { int work_load = (dim + num_thread - 1) / num_thread; for (int i = 0; i < num_thread; i++) build_threads[i] = std::thread(&KNNGraph::normalize_vector, this, work_load * i, std::min(work_load * (i + 1), dim)); for (auto &&thread : build_threads) thread.join(); } Index work_load = (num_vertex + num_worker - 1) / num_worker; for (int i = 0; i < num_worker; i++) worker_threads[i] = std::thread(&KNNWorker::search, workers[i], work_load * i, std::min(work_load * (i + 1), num_vertex)); for (auto &&thread : worker_threads) thread.join(); work_load = (num_vertex + num_thread - 1) / num_thread; for (int i = 0; i < num_thread; i++) build_threads[i] = std::thread(&KNNGraph::compute_weight, this, work_load * i, std::min(work_load * (i + 1), num_vertex)); for (auto &&thread : build_threads) thread.join(); for (int i = 0; i < num_thread; i++) build_threads[i] = std::thread(&KNNGraph::symmetrize, this, work_load * i, std::min(work_load * (i + 1), num_vertex)); for (auto &&thread : build_threads) thread.join(); #endif } /** * @brief Build a KNN graph from a vector-list file. Store the graph in an adjacency list. * @param vector_file vector file * @param _num_neighbor number of neighbors for each node * @param _perplexity perplexity for the neighborhood of each node * @param _vector_normalization normalize the input vectors or not * @param delimiters string of delimiter characters * @param comment prefix of comment strings */ void load_file(const char *vector_file, int _num_neighbor = 200, float _perplexity = 30, bool _vector_normalization = true, const char *delimiters = " \t\r\n", const char *comment = "#") { LOG(INFO) << "loading vectors from " << vector_file; clear(); num_neighbor = _num_neighbor; perplexity = _perplexity; CHECK(perplexity <= num_neighbor) << "`perplexity` should be no larger than `#neighbor`"; vector_normalization = _vector_normalization; FILE *fin = fopen(vector_file, "r"); CHECK(fin) << "File `" << vector_file << "` doesn't exist"; fseek(fin, 0, SEEK_END); size_t fsize = ftell(fin); fseek(fin, 0, SEEK_SET); char line[kMaxLineLength]; while (fgets(line, kMaxLineLength, fin) != nullptr) { LOG_EVERY_N(INFO, 1e5) << 100.0 * ftell(fin) / fsize << "%"; char *comment_str = strstr(line, comment); if (comment_str) *comment_str = 0; int current_dim = 0; for (char *f_str = strtok(line, delimiters); f_str; f_str = strtok(nullptr, delimiters)) { float f = atof(f_str); vectors.push_back(f); current_dim++; } if (!current_dim) continue; if (!dim) dim = current_dim; CHECK(current_dim == dim) << "Incompatible #dimension. Expect " << dim << ", but " << current_dim << " is found"; } fclose(fin); LOG(INFO) << "building KNN graph"; build(); LOG(WARNING) << pretty::block(info()); } /** * @brief Build a KNN graph from a vector list. Store the graph in an adjacency list. * @param _vectors vector list * @param _num_neighbor number of neighbors for each node * @param _perplexity perplexity for the neighborhood of each node * @param _normalized_vector normalize the input vectors or not */ void load_vectors(const std::vector<std::vector<float>> &_vectors, int _num_neighbor = 200, float _perplexity = 30, bool _normalized_vector = true) { clear(); num_neighbor = _num_neighbor; perplexity = _perplexity; CHECK(perplexity <= num_neighbor) << "`perplexity` should be no larger than `#neighbor`"; vector_normalization = _normalized_vector; for (auto &&vector : _vectors) { int current_dim = vector.size(); vectors.insert(vectors.end(), vector.begin(), vector.end()); if (!dim) dim = current_dim; CHECK(current_dim == dim) << "Incompatible #dimension. Expect " << dim << ", but " << current_dim << " is found"; } build(); LOG(WARNING) << pretty::block(info()); } /** * @brief Build a KNN graph from a numpy array. Store the graph in an adjacency list. * @param _array 2D numpy array * @param _num_neighbor number of neighbors for each node * @param _perplexity perplexity for the neighborhood of each node * @param _normalized_vector normalize the input vectors or not */ void load_numpy(const py::array_t<float> &_array, int _num_neighbor = 200, float _perplexity = 30, bool _normalized_vector = true) { CHECK(_array.ndim() == 2) << "Expect a 2d array, but a " << _array.ndim() << "d array is found"; clear(); num_neighbor = _num_neighbor; perplexity = _perplexity; CHECK(perplexity <= num_neighbor) << "`perplexity` should be no larger than `#neighbor`"; vector_normalization = _normalized_vector; auto array = _array.unchecked(); num_vertex = array.shape(0); dim = array.shape(1); vectors.resize(array.size()); for (Index i = 0; i < num_vertex; i++) for (int j = 0; j < dim; j++) vectors[i * dim + j] = array(i, j); build(); LOG(WARNING) << pretty::block(info()); } }; template <size_t _dim, class _Float, class _Index> class VisualizationSolver; /** Edge sampler for visualization */ template <class _Solver> class VisualizationSampler : public SamplerMixin<_Solver> { public: typedef SamplerMixin<_Solver> Base; USING_SAMPLER_MIXIN(Base); using Base::Base; /** Return no additional attributes */ inline Attributes get_attributes(const Edge &edge) const override { return Attributes(); } }; /** Training worker for visualization */ template <class _Solver> class VisualizationWorker : public WorkerMixin<_Solver> { typedef WorkerMixin<_Solver> Base; USING_WORKER_MIXIN(Base); using Base::Base; typedef VisualizationSolver<Solver::dim, Float, Index> VisualizationSolver; /** * Call the corresponding GPU kernel for training * (LargeVis) * (SGD, Momentum, AdaGrad, RMSprop, Adam) */ bool train_dispatch() override { using namespace gpu; VisualizationSolver *solver = reinterpret_cast<VisualizationSolver *>(this->solver); switch (num_moment) { case 0: { decltype(&visualization::train<Vector, Index, LargeVis, kSGD>) train = nullptr; if (solver->model == "LargeVis") { if (optimizer.type == "SGD") train = &visualization::train<Vector, Index, LargeVis, kSGD>; } if (train) { train<<<kBlockPerGrid, kThreadPerBlock, 0, work_stream>>> (*embeddings[0], *embeddings[1], batch, negative_batch, loss, optimizer, solver->negative_weight ); return true; } break; } case 1: { decltype(&visualization::train_1_moment<Vector, Index, LargeVis, kMomentum>) train = nullptr; if (solver->model == "LargeVis") { if (optimizer.type == "Momentum") train = &visualization::train_1_moment<Vector, Index, LargeVis, kMomentum>; if (optimizer.type == "AdaGrad") train = &visualization::train_1_moment<Vector, Index, LargeVis, kAdaGrad>; if (optimizer.type == "RMSprop") train = &visualization::train_1_moment<Vector, Index, LargeVis, kRMSprop>; } if (train) { train<<<kBlockPerGrid, kThreadPerBlock, 0, work_stream>>> (*embeddings[0], *embeddings[1], (*moments[0])[0], (*moments[1])[0], batch, negative_batch, loss, optimizer, solver->negative_weight ); return true; } break; } case 2: { decltype(&visualization::train_2_moment<Vector, Index, LargeVis, kAdam>) train = nullptr; if (solver->model == "LargeVis") { if (optimizer.type == "Adam") train = &visualization::train_2_moment<Vector, Index, LargeVis, kAdam>; } if (train) { train<<<kBlockPerGrid, kThreadPerBlock, 0, work_stream>>> (*embeddings[0], *embeddings[1], (*moments[0])[0], (*moments[1])[0], (*moments[0])[1], (*moments[1])[1], batch, negative_batch, loss, optimizer, solver->negative_weight ); return true; } break; } } return false; } virtual bool predict_dispatch() { return false; } }; /** * @brief Visualization solver * @tparam _dim dimension of embeddings * @tparam _Float floating type of parameters * @tparam _Index integral type of node indexes */ template <size_t _dim, class _Float = float, class _Index = size_t> class VisualizationSolver : public SolverMixin<_dim, _Float, _Index, Graph, VisualizationSampler, VisualizationWorker> { public: typedef SolverMixin<_dim, _Float, _Index, Graph, VisualizationSampler, VisualizationWorker> Base; USING_SOLVER_MIXIN(Base); using Base::Base; std::shared_ptr<std::vector<Vector>> coordinates; /** * @brief Return the protocols of embeddings * * Head / tail coordinates are binded to head /tail partitions respectively. * The two embeddings share the same underlying storage. They are updated in place. */ inline std::vector<Protocol> get_protocols() const override { return {kHeadPartition | kInPlace, kTailPartition | kInPlace | kSharedWithPredecessor}; }; /** Return the protocol of negative sampling */ inline Protocol get_sampler_protocol() const override { return kTailPartition; } /** * @brief Return the shapes of embeddings * * Shapes of both head and tail coordinates can be inferred from the graph. */ inline std::vector<Index> get_shapes() const override { return {kAuto, kAuto}; } /** Return all available models of the solver */ inline std::set<std::string> get_available_models() const override { return {"LargeVis"}; } /** Return the default optimizer type and its hyperparameters */ inline Optimizer get_default_optimizer() const override { return Adam(0.5, 1e-5); } /** Build alias reference for embeddings */ inline void build_alias() override { coordinates = embeddings[0]; } /** Initialize the embeddings */ void init_embeddings() override { std::uniform_real_distribution<Float> init(-5e-5 / dim, 5e-5 / dim); for (auto &&coordinate : *coordinates) for (int i = 0; i < dim; i++) coordinate[i] = init(seed); } inline std::string name() const override { std::stringstream ss; ss << "VisualizationSolver<" << dim << ", " << pretty::type2name<Float>() << ", " << pretty::type2name<Index>() << ">"; return ss.str(); } /** * @brief Train visualization * @param _model "LargeVis" * @param _num_epoch number of epochs, i.e. #positive edges / |E| * @param _resume resume training from learned embeddings or not * @param _sample_batch_size batch size of samples in samplers * @param _positive_reuse times of reusing positive samples * @param _negative_sample_exponent exponent of degrees in negative sampling * @param _negative_weight weight for each negative sample * @param _log_frequency log every log_frequency batches */ void train(const std::string &_model = "LargeVis", int _num_epoch = 50, bool _resume = false, int _sample_batch_size = 2000, int _positive_reuse = 5, float _negative_sample_exponent = 0.75, float _negative_weight = 3, int _log_frequency = 1000) { Base::train(_model, _num_epoch, _resume, _sample_batch_size, _positive_reuse, _negative_sample_exponent, _negative_weight, _log_frequency); } }; } // namespace graphvite
the_stack
#define debug_aml(a...) //#define debug_aml(a...) printf(a); #define debug_aml_VK(a...) //#define debug_amlVK(a...) printf(a) #pragma once #ifdef BOOST_FOUND // Boost includes for CPU Push Relabel Max Flow reference algorithms #include <boost/config.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/edmonds_karp_max_flow.hpp> #include <boost/graph/push_relabel_max_flow.hpp> #include <boost/graph/boykov_kolmogorov_max_flow.hpp> #include <boost/graph/read_dimacs.hpp> #include <iostream> #include <string> #endif #include <algorithm> #include <queue> #include <map> namespace gunrock { namespace app { namespace mf { /***************************************************************************** * Housekeeping Routines ****************************************************************************/ /** * @brief Displays the MF result * * @tparam ValueT Type of capacity/flow/excess * @tparam VertxeT Type of vertex * * @param[in] h_flow Flow calculated on edges * @param[in] source Index of source vertex * @param[in] nodes Number of nodes */ template <typename GraphT, typename ValueT, typename VertexT> void DisplaySolution(GraphT graph, ValueT* h_flow, VertexT* reverse, VertexT sink, VertexT nodes) { typedef typename GraphT::CsrT CsrT; typedef typename GraphT::SizeT SizeT; ValueT flow_incoming_sink = 0; SizeT e_start = graph.CsrT::GetNeighborListOffset(sink); SizeT num_neighbors = graph.CsrT::GetNeighborListLength(sink); SizeT e_end = e_start + num_neighbors; for (auto e = e_start; e < e_end; ++e) { ValueT flow = h_flow[reverse[e]]; if (util::isValid(flow)) flow_incoming_sink += flow; } util::PrintMsg( "The maximum amount of flow that is feasible to reach \ from source to sink is " + std::to_string(flow_incoming_sink), true, false); } /** * @brief Push relabel reference algorithm * * @tparam ValueT Type of capacity/flow/excess * @tparam VertxeT Type of vertex * @tparam GraphT Type of graph * @param[in] graph Graph * @param[in] capacity Function of capacity on edges * @param[in] flow Function of flow on edges * @param[in] excess Function of excess on nodes * @param[in] height Function of height on nodes * @param[in] source Source vertex * @param[in] sink Sink vertex * @param[in] reverse For given edge returns reverse one * * return Value of computed max flow */ template <typename ValueT, typename VertexT, typename GraphT> ValueT max_flow(GraphT& graph, std::queue<VertexT>& que, ValueT* flow, ValueT* excess, VertexT* height, VertexT source, VertexT sink, VertexT* reverse) { typedef typename GraphT::CsrT CsrT; typedef typename GraphT::SizeT SizeT; bool update = true; debug_aml("que size %d\n", que.size()); int iter = 0; for (; !que.empty(); que.pop()) { update = false; VertexT x = que.front(); while (excess[x] > MF_EPSILON) { auto e_start = graph.CsrT::GetNeighborListOffset(x); auto num_neighbors = graph.CsrT::GetNeighborListLength(x); auto e_end = e_start + num_neighbors; VertexT lowest_h; SizeT lowest_id = util::PreDefinedValues<SizeT>::InvalidValue; VertexT lowest_y; for (auto e = e_start; e < e_end; ++e) { auto y = graph.CsrT::GetEdgeDest(e); auto c = graph.CsrT::edge_values[e]; auto move = std::min(c - flow[e], excess[x]); if (move > MF_EPSILON && (!util::isValid(lowest_id) || height[y] < lowest_h)) { lowest_h = height[y]; lowest_id = e; lowest_y = y; } } if (height[x] > lowest_h) { // push auto c = graph.CsrT::edge_values[lowest_id]; auto move = std::min(c - flow[lowest_id], excess[x]); excess[x] -= move; excess[lowest_y] += move; flow[lowest_id] += move; flow[reverse[lowest_id]] -= move; if (lowest_y != source and lowest_y != sink) que.push(lowest_y); debug_aml("push %lf, from %d to %d\n", move, x, lowest_y); } else { // relabel height[x] = lowest_h + 1; ++iter; } if (update && iter > 0 && iter % 100 == 0) { int up = relabeling(graph, source, sink, height, reverse, flow); if (up == 0) update = false; } } } return excess[sink]; } /** * @brief Min Cut algorithm * * @tparam ValueT Type of capacity/flow/excess * @tparam VertxeT Type of vertex * @tparam GraphT Type of graph * @param[in] graph Graph * @param[in] source Source vertex * @param[in] sink Sink vertex * @param[in] flow Function of flow on edges * @param[out] min_cut Function on nodes, 1 = connected to source, 0 = sink * */ template <typename VertexT, typename ValueT, typename GraphT> void minCut(GraphT& graph, VertexT src, ValueT* flow, int* min_cut, bool* vertex_reachabilities, ValueT* residuals) { typedef typename GraphT::CsrT CsrT; memset(vertex_reachabilities, true, graph.nodes * sizeof(vertex_reachabilities[0])); std::queue<VertexT> que; que.push(src); min_cut[src] = 1; for (auto e = 0; e < graph.edges; e++) { residuals[e] = graph.CsrT::edge_values[e] - flow[e]; } while (!que.empty()) { auto v = que.front(); que.pop(); auto e_start = graph.CsrT::GetNeighborListOffset(v); auto num_neighbors = graph.CsrT::GetNeighborListLength(v); auto e_end = e_start + num_neighbors; for (auto e = e_start; e < e_end; ++e) { auto u = graph.CsrT::GetEdgeDest(e); if (vertex_reachabilities[u] and abs(residuals[e]) > MF_EPSILON) { vertex_reachabilities[u] = false; que.push(u); min_cut[u] = 1; } } } } /**************************************************************************** * MF Testing Routines ***************************************************************************/ /** * @brief Simple CPU-based reference MF implementations * * @tparam GraphT Type of the graph * @tparam VertexT Type of the vertex * @tparam ValueT Type of the capacity/flow/excess * @param[in] parameters Running parameters * @param[in] graph Input graph * @param[in] src The source vertex * @param[in] sin The sink vertex * @param[out] maxflow Value of computed maxflow reached sink * @param[out] reverse Computed reverse * @param[out] edges_flow Computed flows on edges * * \return double Time taken for the MF */ template <typename VertexT, typename ValueT, typename GraphT, typename SizeT> double CPU_Reference(util::Parameters& parameters, GraphT& graph, std::map<std::pair<VertexT, VertexT>, SizeT>& edge_id, VertexT src, VertexT sin, ValueT& maxflow, VertexT* reverse, ValueT* flow) { debug_aml("CPU_Reference start\n"); typedef typename GraphT::CsrT CsrT; double elapsed = 0; #if (BOOST_FOUND == 1) debug_aml("boost found\n"); using namespace boost; // Prepare Boost Datatype and Data structure typedef adjacency_list_traits<vecS, vecS, directedS> Traits; typedef adjacency_list< vecS, vecS, directedS, // property<vertex_name_t, std::string>, property<vertex_name_t, std::string, property<vertex_index_t, long, property<vertex_color_t, boost::default_color_type, property<vertex_distance_t, long, property<vertex_predecessor_t, Traits::edge_descriptor>>>>>, property<edge_capacity_t, ValueT, property<edge_residual_capacity_t, ValueT, property<edge_reverse_t, Traits::edge_descriptor>>>> Graph; Graph boost_graph; typename property_map<Graph, edge_capacity_t>::type capacity = get(edge_capacity, boost_graph); typename property_map<Graph, edge_reverse_t>::type rev = get(edge_reverse, boost_graph); typename property_map<Graph, edge_residual_capacity_t>::type residual_capacity = get(edge_residual_capacity, boost_graph); std::vector<Traits::vertex_descriptor> verts; for (VertexT v = 0; v < graph.nodes; ++v) verts.push_back(add_vertex(boost_graph)); Traits::vertex_descriptor source = verts[src]; Traits::vertex_descriptor sink = verts[sin]; debug_aml("src = %d, sin %d\n", source, sink); for (VertexT x = 0; x < graph.nodes; ++x) { auto e_start = graph.CsrT::GetNeighborListOffset(x); auto num_neighbors = graph.CsrT::GetNeighborListLength(x); auto e_end = e_start + num_neighbors; for (auto e = e_start; e < e_end; ++e) { VertexT y = graph.CsrT::GetEdgeDest(e); ValueT cap = graph.CsrT::edge_values[e]; Traits::edge_descriptor e1, e2; bool in1, in2; tie(e1, in1) = add_edge(verts[x], verts[y], boost_graph); tie(e2, in2) = add_edge(verts[y], verts[x], boost_graph); if (!in1 || !in2) { debug_aml("error\n"); return -1; } capacity[e1] = cap; capacity[e2] = 0; rev[e1] = e2; rev[e2] = e1; } } // // Perform Boost reference // util::CpuTimer cpu_timer; cpu_timer.Start(); // maxflow = edmonds_karp_max_flow(boost_graph, source, sink); // maxflow = push_relabel_max_flow(boost_graph, source, sink); maxflow = boykov_kolmogorov_max_flow(boost_graph, source, sink); cpu_timer.Stop(); elapsed = cpu_timer.ElapsedMillis(); fprintf(stderr, "CPU Elapsed: %lf ms, cpu_reference result %lf\n", elapsed, maxflow); printf("CPU Elapsed: %lf ms, maxflow result %lf\n", elapsed, maxflow); // // Extracting results on CPU // typename graph_traits<Graph>::vertex_iterator u_it, u_end; typename graph_traits<Graph>::out_edge_iterator e_it, e_end; for (tie(u_it, u_end) = vertices(boost_graph); u_it != u_end; ++u_it) { for (tie(e_it, e_end) = out_edges(*u_it, boost_graph); e_it != e_end; ++e_it) { if (capacity[*e_it] > 0) { ValueT e_f = capacity[*e_it] - residual_capacity[*e_it]; VertexT t = target(*e_it, boost_graph); flow[edge_id[std::make_pair(*u_it, t)]] = e_f; } } } #else debug_aml("no boost\n"); debug_aml("graph nodes %d, edges %d source %d sink %d src %d\n", graph.nodes, graph.edges, src, sin); ValueT* excess = (ValueT*)malloc(sizeof(ValueT) * graph.nodes); VertexT* height = (VertexT*)malloc(sizeof(VertexT) * graph.nodes); for (VertexT v = 0; v < graph.nodes; ++v) { excess[v] = (ValueT)0; height[v] = (VertexT)0; } height[src] = graph.nodes; for (SizeT e = 0; e < graph.edges; ++e) { flow[e] = (ValueT)0; } relabeling(graph, src, sin, height, reverse, flow); auto e_start = graph.CsrT::GetNeighborListOffset(src); auto num_neighbors = graph.CsrT::GetNeighborListLength(src); auto e_end = e_start + num_neighbors; std::queue<VertexT> que; ValueT preflow = (ValueT)0; for (SizeT e = e_start; e < e_end; ++e) { auto y = graph.CsrT::GetEdgeDest(e); auto c = graph.CsrT::edge_values[e]; excess[y] += c; flow[e] = c; flow[reverse[e]] = -c; preflow += c; que.push(y); } // // Perform simple max flow reference // debug_aml("perform simple max flow reference\n"); debug_aml("source %d, sink %d\n", src, sin); debug_aml("source excess %lf, sink excess %lf\n", excess[src], excess[sin]); debug_aml("pre flow push from source %lf\n", preflow); debug_aml("source height %d, sink height %d\n", height[src], height[sin]); util::CpuTimer cpu_timer; cpu_timer.Start(); maxflow = max_flow(graph, que, flow, excess, height, src, sin, reverse); printf("maxflow result %lf\n", maxflow); cpu_timer.Stop(); elapsed = cpu_timer.ElapsedMillis(); // for (auto u = 0; u < graph.nodes; ++u){ // auto e_start = graph.CsrT::GetNeighborListOffset(u); // auto num_neighbors = graph.CsrT::GetNeighborListLength(u); // auto e_end = e_start + num_neighbors; // for (auto e = e_start; e < e_end; ++e){ // auto v = graph.CsrT::GetEdgeDest(e); // auto f = flow[e]; // if (v == sin){ // printf("flow(%d->%d) = %lf (incoming sink CPU)\n", u, v, f); // } // } // } free(excess); free(height); #endif return elapsed; } /** * @brief Validation of MF results * * @tparam GraphT Type of the graph * @tparam ValueT Type of the distances * * @param[in] parameters Excution parameters * @param[in] graph Input graph * @param[in] source The source vertex * @param[in] sink The sink vertex * @param[in] h_flow Computed flow on edges * @param[in] reverse Reverse array on edges * @param[in] min_cut Array on nodes, 0 - source set, 1 - sink set * @param[in] ref_max_flow Value of max flow for reference solution * @param[in] ref_flow Reference flow on edges * @param[in] verbose Whether to output detail comparsions * * \return int Number of errors */ template <typename GraphT, typename ValueT, typename VertexT> int Validate_Results(util::Parameters& parameters, GraphT& graph, VertexT source, VertexT sink, ValueT* h_flow, VertexT* reverse, int* min_cut, ValueT ref_max_flow, ValueT* ref_flow = NULL, bool verbose = true) { typedef typename GraphT::CsrT CsrT; typedef typename GraphT::SizeT SizeT; int num_errors = 0; bool quiet = parameters.Get<bool>("quiet"); bool quick = parameters.Get<bool>("quick"); auto nodes = graph.nodes; ValueT flow_incoming_sink = (ValueT)0; for (auto u = 0; u < graph.nodes; ++u) { auto e_start = graph.CsrT::GetNeighborListOffset(u); auto num_neighbors = graph.CsrT::GetNeighborListLength(u); auto e_end = e_start + num_neighbors; for (auto e = e_start; e < e_end; ++e) { auto v = graph.CsrT::GetEdgeDest(e); if (v != sink) continue; auto flow_e_in = h_flow[e]; // printf("flow(%d->%d) = %lf (incoming sink)\n", u, v, flow_e_in); if (util::isValid(flow_e_in)) flow_incoming_sink += flow_e_in; } } util::PrintMsg("Max Flow GPU = " + std::to_string(flow_incoming_sink)); fprintf(stderr, "lockfree maxflow %lf\n", flow_incoming_sink); // Verify min cut h_flow ValueT mincut_flow = (ValueT)0; for (auto u = 0; u < graph.nodes; ++u) { if (min_cut[u] == 1) { auto e_start = graph.CsrT::GetNeighborListOffset(u); auto num_neighbors = graph.CsrT::GetNeighborListLength(u); auto e_end = e_start + num_neighbors; for (auto e = e_start; e < e_end; ++e) { auto v = graph.CsrT::GetEdgeDest(e); if (min_cut[v] == 0) { auto f = graph.CsrT::edge_values[e]; mincut_flow += f; } } } } util::PrintMsg("MIN CUT flow = " + std::to_string(mincut_flow)); if (fabs(mincut_flow - flow_incoming_sink) > MF_EPSILON_VALIDATE) { ++num_errors; util::PrintMsg("FAIL: Min cut " + std::to_string(mincut_flow) + " and max flow " + std::to_string(flow_incoming_sink) + " are not equal", !quiet); fprintf(stderr, "FAIL: Min cut %lf and max flow %lf are not equal\n", mincut_flow, flow_incoming_sink); } // Verify the result if (!quick and ref_flow != NULL) { util::PrintMsg("Flow Validity (compare results):\n", !quiet, false); auto ref_flow_incoming_sink = (ValueT)0; for (auto u = 0; u < graph.nodes; ++u) { auto e_start = graph.CsrT::GetNeighborListOffset(u); auto num_neighbors = graph.CsrT::GetNeighborListLength(u); auto e_end = e_start + num_neighbors; for (auto e = e_start; e < e_end; ++e) { auto v = graph.CsrT::GetEdgeDest(e); if (v != sink) continue; auto flow_e_in = ref_flow[e]; if (util::isValid(flow_e_in)) ref_flow_incoming_sink += flow_e_in; } } if (fabs(flow_incoming_sink - ref_flow_incoming_sink) > MF_EPSILON_VALIDATE) { ++num_errors; debug_aml("flow_incoming_sink %lf, ref_flow_incoming_sink %lf\n", flow_incoming_sink, ref_flow_incoming_sink); } if (num_errors > 0) { util::PrintMsg(std::to_string(num_errors) + " errors occurred.", !quiet); } else { util::PrintMsg("PASS", !quiet); // fprintf(stderr, "PASS\n"); } } else { util::PrintMsg("Flow Validity:\n", !quiet, false); if (util::isValid(ref_max_flow) and fabs(flow_incoming_sink - ref_max_flow) > MF_EPSILON_VALIDATE) { ++num_errors; debug_aml("flow_incoming_sink %lf, ref_max_flow %lf\n", flow_incoming_sink, ref_max_flow); } for (VertexT v = 0; v < nodes; ++v) { if (v == source || v == sink) continue; auto e_start = graph.CsrT::GetNeighborListOffset(v); auto num_neighbors = graph.CsrT::GetNeighborListLength(v); auto e_end = e_start + num_neighbors; ValueT flow_v = (ValueT)0; for (auto e = e_start; e < e_end; ++e) { if (util::isValid(h_flow[e])) flow_v += h_flow[e]; else { ++num_errors; debug_aml("flow for edge %d is invalid\n", e); } } if (fabs(flow_v) > MF_EPSILON_VALIDATE) { debug_aml("summary flow for vertex %d is %lf > %llf\n", v, fabs(flow_v), MF_EPSILON); } else continue; ++num_errors; util::PrintMsg("FAIL: for vertex " + std::to_string(v) + " summary flow " + std::to_string(flow_v) + " is not equal 0", !quiet); fprintf(stderr, "FAIL: for vertex %d summary flow %lf is not equal 0\n", v, flow_v); } if (num_errors > 0) { util::PrintMsg(std::to_string(num_errors) + " errors occurred.", !quiet); } else { util::PrintMsg("PASS", !quiet); // fprintf(stderr, "PASS\n"); } } if (!quick && verbose) { // Display Solution util::PrintMsg("Max Flow of the GPU result:"); DisplaySolution(graph, h_flow, reverse, sink, graph.nodes); if (ref_flow != NULL) { util::PrintMsg("Max Flow of the CPU results:"); DisplaySolution(graph, ref_flow, reverse, sink, graph.nodes); } util::PrintMsg(""); } return num_errors; } } // namespace mf } // namespace app } // namespace gunrock // Leave this at the end of the file // Local Variables: // mode:c++ // c-file-style: "NVIDIA" // End:
the_stack
* \file * Utility types for device-wide scan and similar primitives */ #pragma once #include <iterator> #include "../../thread/thread_load.cuh" #include "../../thread/thread_store.cuh" #include "../../warp/warp_reduce.cuh" #include "../../util_arch.cuh" #include "../../util_device.cuh" #include "../../util_namespace.cuh" /// Optional outer namespace(s) CUB_NS_PREFIX /// CUB namespace namespace cub { /****************************************************************************** * Callback operator types for supplying BlockScan prefixes ******************************************************************************/ /** * Stateful callback operator type for supplying BlockScan prefixes. * Maintains a running prefix that can be applied to consecutive * BlockScan operations. */ template < typename T, ///< BlockScan value type typename ScanOp> ///< Wrapped scan operator type struct RunningBlockPrefixCallbackOp { ScanOp op; ///< Wrapped scan operator T running_total; ///< Running block-wide prefix /// Constructor __device__ __forceinline__ RunningBlockPrefixCallbackOp(ScanOp op) : op(op) {} /// Constructor __device__ __forceinline__ RunningBlockPrefixCallbackOp( T starting_prefix, ScanOp op) : op(op), running_total(starting_prefix) {} /** * Prefix callback operator. Returns the block-wide running_total in thread-0. */ __device__ __forceinline__ T operator()( const T &block_aggregate) ///< The aggregate sum of the BlockScan inputs { T retval = running_total; running_total = op(running_total, block_aggregate); return retval; } }; /****************************************************************************** * Bookkeeping types for single-pass device-wide scan with dynamic lookback ******************************************************************************/ /** * Enumerations of tile status */ enum LookbackTileStatus { LOOKBACK_TILE_OOB, // Out-of-bounds (e.g., padding) LOOKBACK_TILE_INVALID, // Not yet processed LOOKBACK_TILE_PARTIAL, // Tile aggregate is available LOOKBACK_TILE_INCLUSIVE, // Inclusive tile prefix is available }; /** * Tile status interface. */ template < typename T, bool SINGLE_WORD = Traits<T>::PRIMITIVE> struct TileLookbackStatus; /** * Tile status interface specialized for scan status and value types * that can be combined into one machine word that can be * read/written coherently in a single access. */ template <typename T> struct TileLookbackStatus<T, true> { // Status word type typedef typename If<(sizeof(T) == 8), long long, typename If<(sizeof(T) == 4), int, typename If<(sizeof(T) == 2), short, char>::Type>::Type>::Type StatusWord; // Unit word type typedef typename If<(sizeof(T) == 8), longlong2, typename If<(sizeof(T) == 4), int2, typename If<(sizeof(T) == 2), int, uchar2>::Type>::Type>::Type TxnWord; // Device word type struct TileDescriptor { StatusWord status; T value; }; // Constants enum { TILE_STATUS_PADDING = CUB_PTX_WARP_THREADS, }; // Device storage TileDescriptor *d_tile_status; /// Constructor __host__ __device__ __forceinline__ TileLookbackStatus() : d_tile_status(NULL) {} /// Initializer __host__ __device__ __forceinline__ cudaError_t Init( int num_tiles, ///< [in] Number of tiles void *d_temp_storage, ///< [in] %Device allocation of temporary storage. When NULL, the required allocation size is written to \p temp_storage_bytes and no work is done. size_t temp_storage_bytes) ///< [in] Size in bytes of \t d_temp_storage allocation { d_tile_status = reinterpret_cast<TileDescriptor*>(d_temp_storage); return cudaSuccess; } /** * Compute device memory needed for tile status */ __host__ __device__ __forceinline__ static cudaError_t AllocationSize( int num_tiles, ///< [in] Number of tiles size_t &temp_storage_bytes) ///< [out] Size in bytes of \t d_temp_storage allocation { temp_storage_bytes = (num_tiles + TILE_STATUS_PADDING) * sizeof(TileDescriptor); // bytes needed for tile status descriptors return cudaSuccess; } /** * Initialize (from device) */ __device__ __forceinline__ void InitializeStatus(int num_tiles) { int tile_idx = (blockIdx.x * blockDim.x) + threadIdx.x; if (tile_idx < num_tiles) { // Not-yet-set d_tile_status[TILE_STATUS_PADDING + tile_idx].status = StatusWord(LOOKBACK_TILE_INVALID); } if ((blockIdx.x == 0) && (threadIdx.x < TILE_STATUS_PADDING)) { // Padding d_tile_status[threadIdx.x].status = StatusWord(LOOKBACK_TILE_OOB); } } /** * Update the specified tile's inclusive value and corresponding status */ __device__ __forceinline__ void SetInclusive(int tile_idx, T tile_inclusive) { TileDescriptor tile_descriptor; tile_descriptor.status = LOOKBACK_TILE_INCLUSIVE; tile_descriptor.value = tile_inclusive; TxnWord alias; *reinterpret_cast<TileDescriptor*>(&alias) = tile_descriptor; ThreadStore<STORE_CG>(reinterpret_cast<TxnWord*>(d_tile_status + TILE_STATUS_PADDING + tile_idx), alias); } /** * Update the specified tile's partial value and corresponding status */ __device__ __forceinline__ void SetPartial(int tile_idx, T tile_partial) { TileDescriptor tile_descriptor; tile_descriptor.status = LOOKBACK_TILE_PARTIAL; tile_descriptor.value = tile_partial; TxnWord alias; *reinterpret_cast<TileDescriptor*>(&alias) = tile_descriptor; ThreadStore<STORE_CG>(reinterpret_cast<TxnWord*>(d_tile_status + TILE_STATUS_PADDING + tile_idx), alias); } /** * Wait for the corresponding tile to become non-invalid */ __device__ __forceinline__ void WaitForValid( int tile_idx, StatusWord &status, T &value) { // Use warp-any to determine when all threads have valid status TxnWord alias = ThreadLoad<LOAD_CG>(reinterpret_cast<TxnWord*>(d_tile_status + TILE_STATUS_PADDING + tile_idx)); TileDescriptor tile_descriptor = reinterpret_cast<TileDescriptor&>(alias); while ((tile_descriptor.status == LOOKBACK_TILE_INVALID)) { alias = ThreadLoad<LOAD_CG>(reinterpret_cast<TxnWord*>(d_tile_status + TILE_STATUS_PADDING + tile_idx)); tile_descriptor = reinterpret_cast<TileDescriptor&>(alias); } status = tile_descriptor.status; value = tile_descriptor.value; } }; /** * Tile status interface specialized for scan status and value types that * cannot be combined into one machine word. */ template <typename T> struct TileLookbackStatus<T, false> { // Status word type typedef char StatusWord; // Constants enum { TILE_STATUS_PADDING = CUB_PTX_WARP_THREADS, }; // Device storage StatusWord *d_tile_status; T *d_tile_partial; T *d_tile_inclusive; /// Constructor __host__ __device__ __forceinline__ TileLookbackStatus() : d_tile_status(NULL), d_tile_partial(NULL), d_tile_inclusive(NULL) {} /// Initializer __host__ __device__ __forceinline__ cudaError_t Init( int num_tiles, ///< [in] Number of tiles void *d_temp_storage, ///< [in] %Device allocation of temporary storage. When NULL, the required allocation size is written to \p temp_storage_bytes and no work is done. size_t temp_storage_bytes) ///< [in] Size in bytes of \t d_temp_storage allocation { cudaError_t error = cudaSuccess; do { void* allocations[3]; size_t allocation_sizes[3]; allocation_sizes[0] = (num_tiles + TILE_STATUS_PADDING) * sizeof(StatusWord); // bytes needed for tile status descriptors allocation_sizes[1] = num_tiles * sizeof(Uninitialized<T>); // bytes needed for partials allocation_sizes[2] = num_tiles * sizeof(Uninitialized<T>); // bytes needed for inclusives // Compute allocation pointers into the single storage blob if (CubDebug(error = AliasTemporaries(d_temp_storage, temp_storage_bytes, allocations, allocation_sizes))) break; // Alias the offsets d_tile_status = reinterpret_cast<StatusWord*>(allocations[0]); d_tile_partial = reinterpret_cast<T*>(allocations[1]); d_tile_inclusive = reinterpret_cast<T*>(allocations[2]); } while (0); return error; } /** * Compute device memory needed for tile status */ __host__ __device__ __forceinline__ static cudaError_t AllocationSize( int num_tiles, ///< [in] Number of tiles size_t &temp_storage_bytes) ///< [out] Size in bytes of \t d_temp_storage allocation { // Specify storage allocation requirements size_t allocation_sizes[3]; allocation_sizes[0] = (num_tiles + TILE_STATUS_PADDING) * sizeof(StatusWord); // bytes needed for tile status descriptors allocation_sizes[1] = num_tiles * sizeof(Uninitialized<T>); // bytes needed for partials allocation_sizes[2] = num_tiles * sizeof(Uninitialized<T>); // bytes needed for inclusives // Set the necessary size of the blob void* allocations[3]; return CubDebug(AliasTemporaries(NULL, temp_storage_bytes, allocations, allocation_sizes)); } /** * Initialize (from device) */ __device__ __forceinline__ void InitializeStatus(int num_tiles) { int tile_idx = (blockIdx.x * blockDim.x) + threadIdx.x; if (tile_idx < num_tiles) { // Not-yet-set d_tile_status[TILE_STATUS_PADDING + tile_idx] = StatusWord(LOOKBACK_TILE_INVALID); } if ((blockIdx.x == 0) && (threadIdx.x < TILE_STATUS_PADDING)) { // Padding d_tile_status[threadIdx.x] = StatusWord(LOOKBACK_TILE_OOB); } } /** * Update the specified tile's inclusive value and corresponding status */ __device__ __forceinline__ void SetInclusive(int tile_idx, T tile_inclusive) { // Update tile inclusive value ThreadStore<STORE_CG>(d_tile_inclusive + tile_idx, tile_inclusive); // Fence __threadfence(); // Update tile status ThreadStore<STORE_CG>(d_tile_status + TILE_STATUS_PADDING + tile_idx, StatusWord(LOOKBACK_TILE_INCLUSIVE)); } /** * Update the specified tile's partial value and corresponding status */ __device__ __forceinline__ void SetPartial(int tile_idx, T tile_partial) { // Update tile partial value ThreadStore<STORE_CG>(d_tile_partial + tile_idx, tile_partial); // Fence __threadfence(); // Update tile status ThreadStore<STORE_CG>(d_tile_status + TILE_STATUS_PADDING + tile_idx, StatusWord(LOOKBACK_TILE_PARTIAL)); } /** * Wait for the corresponding tile to become non-invalid */ __device__ __forceinline__ void WaitForValid( int tile_idx, StatusWord &status, T &value) { status = ThreadLoad<LOAD_CG>(d_tile_status + TILE_STATUS_PADDING + tile_idx); while (status == LOOKBACK_TILE_INVALID) { status = ThreadLoad<LOAD_CG>(d_tile_status + TILE_STATUS_PADDING + tile_idx); } T partial = ThreadLoad<LOAD_CG>(d_tile_partial + tile_idx); T inclusive = ThreadLoad<LOAD_CG>(d_tile_inclusive + tile_idx); value = (status == StatusWord(LOOKBACK_TILE_PARTIAL)) ? partial : inclusive; } }; /** * Stateful block-scan prefix functor. Provides the the running prefix for * the current tile by using the call-back warp to wait on on * aggregates/prefixes from predecessor tiles to become available. */ template < typename T, typename ScanOp, typename TileLookbackStatus> struct LookbackBlockPrefixCallbackOp { // Parameterized warp reduce typedef WarpReduce<T> WarpReduceT; // Temporary storage type typedef typename WarpReduceT::TempStorage _TempStorage; // Alias wrapper allowing temporary storage to be unioned struct TempStorage : Uninitialized<_TempStorage> {}; // Type of status word typedef typename TileLookbackStatus::StatusWord StatusWord; // Scan operator for switching the scan arguments struct SwizzleScanOp { ScanOp scan_op; // Constructor __host__ __device__ __forceinline__ SwizzleScanOp(ScanOp scan_op) : scan_op(scan_op) {} // Switch the scan arguments __host__ __device__ __forceinline__ T operator()(const T &a, const T &b) { return scan_op(b, a); } }; // Fields TileLookbackStatus &tile_status; ///< Interface to tile status _TempStorage &temp_storage; ///< Reference to a warp-reduction instance ScanOp scan_op; ///< Binary scan operator int tile_idx; ///< The current tile index T exclusive_prefix; ///< Exclusive prefix for the tile T inclusive_prefix; ///< Inclusive prefix for the tile // Constructor __device__ __forceinline__ LookbackBlockPrefixCallbackOp( TileLookbackStatus &tile_status, TempStorage &temp_storage, ScanOp scan_op, int tile_idx) : tile_status(tile_status), temp_storage(temp_storage.Alias()), scan_op(scan_op), tile_idx(tile_idx) {} // Block until all predecessors within the warp-wide window have non-invalid status __device__ __forceinline__ void ProcessWindow( int predecessor_idx, ///< Preceding tile index to inspect StatusWord &predecessor_status, ///< [out] Preceding tile status T &window_aggregate) ///< [out] Relevant partial reduction from this window of preceding tiles { T value; tile_status.WaitForValid(predecessor_idx, predecessor_status, value); // Perform a segmented reduction to get the prefix for the current window. // Use the swizzled scan operator because we are now scanning *down* towards thread0. int tail_flag = (predecessor_status == StatusWord(LOOKBACK_TILE_INCLUSIVE)); window_aggregate = WarpReduceT(temp_storage).TailSegmentedReduce(value, tail_flag, SwizzleScanOp(scan_op)); } // BlockScan prefix callback functor (called by the first warp) __device__ __forceinline__ T operator()(T block_aggregate) { // Update our status with our tile-aggregate if (threadIdx.x == 0) { tile_status.SetPartial(tile_idx, block_aggregate); } int predecessor_idx = tile_idx - threadIdx.x - 1; StatusWord predecessor_status; T window_aggregate; // Wait for the warp-wide window of predecessor tiles to become valid ProcessWindow(predecessor_idx, predecessor_status, window_aggregate); // The exclusive tile prefix starts out as the current window aggregate exclusive_prefix = window_aggregate; // Keep sliding the window back until we come across a tile whose inclusive prefix is known while (WarpAll(predecessor_status != StatusWord(LOOKBACK_TILE_INCLUSIVE))) { predecessor_idx -= CUB_PTX_WARP_THREADS; // Update exclusive tile prefix with the window prefix ProcessWindow(predecessor_idx, predecessor_status, window_aggregate); exclusive_prefix = scan_op(window_aggregate, exclusive_prefix); } // Compute the inclusive tile prefix and update the status for this tile if (threadIdx.x == 0) { inclusive_prefix = scan_op(exclusive_prefix, block_aggregate); tile_status.SetInclusive(tile_idx, inclusive_prefix); } // Return exclusive_prefix return exclusive_prefix; } }; } // CUB namespace CUB_NS_POSTFIX // Optional outer namespace(s)
the_stack
using namespace thrust; __constant__ uint __storeStart__; __constant__ uint __loadInvStart__; /** * number of variables of the input program. */ __constant__ uint __numVars__; __constant__ uint* __ptsConstraints__; __constant__ uint __numPtsConstraints__; __constant__ uint* __copyConstraints__; __constant__ uint __numCopyConstraints__; __constant__ uint* __loadConstraints__; __constant__ uint __numLoadConstraints__; __constant__ uint* __storeConstraints__; __constant__ uint __numStoreConstraints__; __device__ uint __numStore__ = 0; __constant__ uint* __gepInv__; __constant__ uint __numGepInv__; __constant__ uint* __size__; __constant__ uint* __initialRep__; __constant__ uint* __initialNonRep__; __constant__ uint __numInitialRep__; __constant__ uint* __nextVar__; /** * Table of indexes to the information inferred by HCD. * Each entry is a pair (index, index + delta) that refers to __hcdTable__ */ __constant__ uint* __hcdIndex__; __constant__ uint __numHcdIndex__; /** * List of pairs (y, x_0, x_(delta - 2)) where pts(*y) = pts(x_0) = ... pts(x_((delta - 2)) * The equivalences have been detected during the offline phase of HCD, executed in the CPU */ __constant__ uint* __hcdTable__; __constant__ uint __numHcdTable__; /** * Representative array */ __constant__ volatile uint* __rep__; // HAS to be volatile /** * array of elements containing all the edges in the graph. */ __constant__ volatile uint* __edges__; // HAS to be volatile __constant__ uint* __graph__; __constant__ uint* __lock__; __constant__ uint* __key__; __constant__ uint* __val__; __constant__ uint* __keyAux__; __device__ uint __numKeysCounter__ = 0; __device__ uint __numKeys__; __constant__ uint* __currPtsHead__; __device__ uint __counter__ = 0; __device__ uint __max__ = 0; __device__ uint __min__ = 0; __device__ bool __done__ = true; __device__ uint __error__; __device__ uint __worklistIndex0__ = 0; __device__ uint __worklistIndex1__ = 1; uint createTime = 0; double createTime2 = 0; //////////// utility functions for the GPU ///////// __device__ uint __errorCode__ = 0; __device__ uint __errorLine__ = 0; __device__ char* __errorMsg__; __device__ inline uint nextPowerOfTwo(uint v) { return 1U << (uintSize * 8 - __clz(v - 1)); } __device__ inline uint __count(int predicate) { const uint ballot = __ballot_sync(0xffffffff,predicate); return __popc(ballot); } __device__ inline uint isFirstThreadOfWarp(){ return !threadIdx.x; } __device__ inline uint getWarpIdInGrid(){ return (blockIdx.x * (blockDim.x * blockDim.y / WARP_SIZE) + threadIdx.y); } __device__ inline uint isFirstWarpOfGrid(){ return !(blockIdx.x || threadIdx.y); } __device__ inline uint isFirstWarpOfBlock(){ return !threadIdx.y; } __device__ inline uint getThreadIdInBlock(){ return mul32(threadIdx.y) + threadIdx.x; } __device__ inline uint isFirstThreadOfBlock(){ return !getThreadIdInBlock(); } __device__ inline uint getThreadIdInGrid(){ return mul32(getWarpIdInGrid()) + threadIdx.x; } __device__ inline uint getThreadsPerBlock() { return blockDim.x * blockDim.y; } __device__ inline uint isLastThreadOfBlock(){ return getThreadIdInBlock() == getThreadsPerBlock() - 1; } __device__ inline uint getWarpsPerBlock() { return blockDim.y; } __device__ inline uint getWarpsPerGrid() { return blockDim.y * gridDim.x; } __device__ inline uint getThreadsPerGrid() { return mul32(getWarpsPerGrid()); } __device__ inline uint getBlockIdInGrid(){ return blockIdx.x; } __device__ inline uint getBlocksPerGrid(){ return gridDim.x; } __device__ void syncAllThreads() { __syncthreads(); uint to = getBlocksPerGrid() - 1; if (isFirstThreadOfBlock()) { volatile uint* counter = &__counter__; if (atomicInc((uint*) counter, to) < to) { while (*counter); // spinning... } } __syncthreads(); } __device__ uint getValAtThread(volatile uint* const _shared_, const uint myVal, const uint i) { if (threadIdx.x == i) { _shared_[threadIdx.y] = myVal; } return _shared_[threadIdx.y]; } __device__ uint getValAtThread(const uint myVal, const uint i) { __shared__ volatile uint _shared_[MAX_WARPS_PER_BLOCK]; if (threadIdx.x == i) { _shared_[threadIdx.y] = myVal; } return _shared_[threadIdx.y]; } /* * Forward declarations */ __device__ void insertAll(const uint storeIndex, uint* _shared_, uint numFrom, bool sort = true); template<uint toRel, uint fromRel> __device__ void unionAll(const uint to, uint* _shared_, uint numFrom, bool sort = true); template<uint toRel, uint fromRel> __device__ void map(const uint to, const uint base, const uint myBits, uint* _shared_, uint& numFrom); __device__ inline uint mul960(uint num) { // 960 = 1024 - 64 return (num << 10) - (num << 6); } __device__ inline uint __graphGet__(const uint row, const uint col) { return __edges__[row + col]; } __device__ inline uint __graphGet__(const uint pos) { return __graph__[pos]; } __device__ inline void __graphSet__(const uint row, const uint col, const uint val) { __edges__[row + col] = val; } __device__ inline void __graphSet__(const uint pos, const uint val) { __graph__[pos] = val; } __device__ inline uint _sharedGet_(volatile uint* _shared_, uint index, uint offset) { return _shared_[index + offset]; } __device__ inline void _sharedSet_(volatile uint* _shared_, uint index, uint offset, uint val) { _shared_[index + offset] = val; } __device__ inline uint getHeadIndex(uint var, uint rel){ if (rel == NEXT_DIFF_PTS) { return NEXT_DIFF_PTS_START - mul32(var); } if (rel == COPY_INV) { return COPY_INV_START + mul32(var); } if (rel == CURR_DIFF_PTS) { return CURR_DIFF_PTS_START - mul32(var); } if (rel == PTS) { return mul32(var); } if (rel == STORE) { return __storeStart__ + mul32(var); } // it has to be LOAD_INV, right? return __loadInvStart__ + mul32(var); } __device__ inline uint getNextDiffPtsHeadIndex(uint var){ return NEXT_DIFF_PTS_START - mul32(var); } __device__ inline uint getCopyInvHeadIndex(uint var){ return COPY_INV_START + mul32(var); } __device__ inline uint getCurrDiffPtsHeadIndex(uint var){ return CURR_DIFF_PTS_START - mul32(var); } __device__ inline uint getPtsHeadIndex(uint var){ return mul32(var); } __device__ inline uint getStoreHeadIndex(uint var){ return __storeStart__ + mul32(var); } __device__ inline uint getLoadInvHeadIndex(uint var){ return __loadInvStart__ + mul32(var); } __device__ inline int isEmpty(uint var, uint rel) { const uint headIndex = getHeadIndex(var, rel); return __graphGet__(headIndex, BASE) == NIL; } /** * Mask that tells whether the variables contained in an element have size > offset * There is one such mask per offset. * stored in compressed format */ __constant__ uint* __offsetMask__; /** * Number of rows needed to represent the mask of ONE offset. * = ceil(numObjectVars / DST_PER_ELEMENT), since non-object pointers have size 1. */ __constant__ uint __offsetMaskRowsPerOffset__; __device__ inline uint __offsetMaskGet__(const uint base, const uint col, const uint offset) { return __offsetMask__[mul32((offset - 1) * __offsetMaskRowsPerOffset__ + base) + col]; } __device__ inline void __offsetMaskSet__(const uint base, const uint col, const uint offset, const uint val) { __offsetMask__[mul32((offset - 1) * __offsetMaskRowsPerOffset__ + base) + col] = val; } /** * Mask that tells whether the pts-to of an element changed. * the BASE and NEXT words are always equal to 0 * stored in compressed format */ __constant__ uint* __diffPtsMask__; __device__ inline uint __diffPtsMaskGet__(const uint base, const uint col) { return __diffPtsMask__[mul32(base) + col]; } __device__ inline void __diffPtsMaskSet__(const uint base, const uint col, const uint val) { __diffPtsMask__[mul32(base) + col] = val; } /** * Index of the next free element in the corresponding free list. * The index is given in words, not bytes or number of elements. */ __device__ uint __ptsFreeList__,__nextDiffPtsFreeList__, __currDiffPtsFreeList__, __otherFreeList__; __device__ inline uint mallocPts(uint size = ELEMENT_WIDTH) { __shared__ volatile uint _shared_[MAX_WARPS_PER_BLOCK]; if (isFirstThreadOfWarp()) { _shared_[threadIdx.y] = atomicAdd(&__ptsFreeList__, size); } return _shared_[threadIdx.y]; } __device__ inline uint mallocNextDiffPts() { __shared__ volatile uint _shared_[MAX_WARPS_PER_BLOCK]; if (isFirstThreadOfWarp()) { _shared_[threadIdx.y] = atomicSub(&__nextDiffPtsFreeList__, ELEMENT_WIDTH); } return _shared_[threadIdx.y]; } __device__ inline uint mallocCurrDiffPts() { __shared__ volatile uint _shared_[MAX_WARPS_PER_BLOCK]; if (isFirstThreadOfWarp()) { _shared_[threadIdx.y] = atomicSub(&__currDiffPtsFreeList__, ELEMENT_WIDTH); } return _shared_[threadIdx.y]; } __device__ inline uint mallocOther() { __shared__ volatile uint _shared_[MAX_WARPS_PER_BLOCK]; if (isFirstThreadOfWarp()) { _shared_[threadIdx.y] = atomicAdd(&__otherFreeList__, ELEMENT_WIDTH); } return _shared_[threadIdx.y]; } __device__ inline uint mallocIn(uint rel) { if (rel == NEXT_DIFF_PTS) { return mallocNextDiffPts(); } if (rel >= COPY_INV) { return mallocOther(); } if (rel == PTS) { return mallocPts(); } if (rel == CURR_DIFF_PTS) { return mallocCurrDiffPts(); } //printf("WTF! (%u)", rel); return 0; } /** * Get and increment the current worklist index * Granularity: warp * @param delta Number of elements to be retrieved at once * @return Worklist index 'i'. All the work items in the [i, i + delta) interval are guaranteed * to be assigned to the current warp. */ __device__ inline uint getAndIncrement(const uint delta) { __shared__ volatile uint _shared_[MAX_WARPS_PER_BLOCK]; if (isFirstThreadOfWarp()) { _shared_[threadIdx.y] = atomicAdd(&__worklistIndex0__, delta); } return _shared_[threadIdx.y]; } __device__ inline uint getAndIncrement(uint* counter, uint delta) { __shared__ volatile uint _shared_[MAX_WARPS_PER_BLOCK]; if (isFirstThreadOfWarp()) { _shared_[threadIdx.y] = atomicAdd(counter, delta); } return _shared_[threadIdx.y]; } /** * Lock a given variable * Granularity: warp * @param var Id of the variable * @return A non-zero value if the operation succeeded */ __device__ inline uint lock(const uint var) { uint any = __any_sync(0xffffffff,isFirstThreadOfWarp() && (atomicCAS(__lock__ + var, UNLOCKED, LOCKED) == UNLOCKED)); return any; } /** * Unlock a variable * Granularity: warp or thread * @param var Id of the variable */ __device__ inline void unlock(const uint var) { __lock__[var] = UNLOCKED; } __device__ inline int isRep(const uint var) { return __rep__[var] == var; } __device__ inline void setRep(const uint var, const uint rep) { __rep__[var] = rep; } __device__ inline uint getRep(const uint var) { return __rep__[var]; } __device__ inline uint getRepRec(const uint var) { uint rep = var; uint repRep = __rep__[rep]; while (repRep != rep) { rep = repRep; repRep = __rep__[rep]; } return rep; } __device__ ulongint recordStartTime() { __shared__ volatile ulongint _ret_[MAX_WARPS_PER_BLOCK]; if (isFirstThreadOfWarp()) { _ret_[threadIdx.y] = clock(); } return _ret_[threadIdx.y]; } __device__ void recordElapsedTime(ulongint start){ if (isFirstThreadOfWarp()) { ulongint delta; ulongint end = clock(); if (end > start) { delta = end - start; } else { delta = end + (0xffffffff - start); } double time = TICKS_TO_MS(delta); printf("Block %u, Warp: %u: %8.2f ms.\n", blockIdx.x, threadIdx.y, time); } } __device__ inline uint decodeWord(const uint base, const uint word, const uint bits) { uint ret = mul960(base) + mul32(word); return (isBitActive(bits, threadIdx.x)) ? __rep__[ret + threadIdx.x] : NIL; } __device__ inline void swap(volatile uint* const keyA, volatile uint* const keyB, const uint dir) { uint n1 = *keyA; uint n2 = *keyB; if ((n1 < n2) != dir) { *keyA = n2; *keyB = n1; } } // Bitonic Sort, in ascending order using one WARP // precondition: size of _shared_ has to be a power of 2 __device__ inline void bitonicSort(volatile uint* const _shared_, const uint to) { for (int size = 2; size <= to; size <<= 1) { for (int stride = size / 2; stride > 0; stride >>= 1) { for (int id = threadIdx.x; id < (to / 2); id += WARP_SIZE) { const uint myDir = ((id & (size / 2)) == 0); uint pos = 2 * id - mod(id, stride); volatile uint* start = _shared_ + pos; swap(start, start + stride, myDir); } } } } __device__ void blockBitonicSort(volatile uint* _shared_, uint to) { uint idInBlock = getThreadIdInBlock(); for (int size = 2; size <= to; size <<= 1) { for (int stride = size / 2; stride > 0; stride >>= 1) { __syncthreads(); for (int id = idInBlock; id < (to / 2); id += getThreadsPerBlock()) { const uint myDir = ((id & (size / 2)) == 0); uint pos = 2 * id - mod(id, stride); volatile uint* start = _shared_ + pos; swap(start, start + stride, myDir); } } } } /** * Sort an array in ascending order. * Granularity: block * @param _shared_ list of integers * @param to size of the sublist we want to process */ __device__ void blockSort(volatile uint* _shared_, uint to) { uint size = max(nextPowerOfTwo(to), 32); uint id = getThreadIdInBlock(); for (int i = to + id; i < size; i += getThreadsPerBlock()) { _shared_[i] = NIL; } blockBitonicSort(_shared_, size); __syncthreads(); } /** * Remove duplicates on a sorted sequence, equivalent to Thrust 'unique' function but uses one warp. * If there are NILS, they are treated like any other number * precondition: the input list is sorted * precondition: to >= 32 * precondition: shared_[-1] exists and is equal to NIL * Granularity: warp * * @param _shared_ list of integers * @param to size of the sublist we want to process * @return number of unique elements in the input. */ __device__ inline uint unique(volatile uint* const _shared_, uint to) { uint startPos = 0; uint myMask = (1 << (threadIdx.x + 1)) - 1; for (int id = threadIdx.x; id < to; id += WARP_SIZE) { uint myVal = _shared_[id]; uint fresh = __ballot_sync(0xffffffff,myVal != _shared_[id - 1]); // pos = starting position + number of 1's to my right (incl. myself) minus one uint pos = startPos + __popc(fresh & myMask) - 1; _shared_[pos] = myVal; startPos += __popc(fresh); } return startPos; } __device__ uint removeDuplicates(volatile uint* const _shared_, const uint to) { const uint size = max(nextPowerOfTwo(to), 32); for (int i = to + threadIdx.x; i < size; i += WARP_SIZE) { _shared_[i] = NIL; } bitonicSort(_shared_, size); uint ret = unique(_shared_, size); return (size > to) ? ret - 1 : ret; } __device__ void print(uint* m, const uint size) { if (!isFirstThreadOfWarp()) return; //printf("["); for (int i = 0; i < size; i++) { //printf("%u", m[i]); if (i < size - 1) { //printf(", "); } } //printf ("]"); } __device__ void print(int* m, const uint size) { if (!isFirstThreadOfWarp()) return; //printf("["); for (int i = 0; i < size; i++) { //printf("%d", m[i]); if (i < size - 1) { //printf(", "); } } //printf ("]"); } __device__ volatile uint __printBuffer__[PRINT_BUFFER_SIZE]; // TODO: assumes we print with 1 block and 1 warp... __device__ void printElementAsSet(const uint base, volatile uint myBits, bool& first) { for (int i = 0; i < BASE; i++) { uint word = getValAtThread(myBits, i); uint myDst = decodeWord(base, i, word); for (int j = 0; j < WARP_SIZE; j++) { uint dst = getValAtThread(myDst, j); if (dst != NIL && isFirstThreadOfWarp()) { if (first) { //printf("%u", dst); } else { //printf(", %u", dst); } first = false; } } } } __device__ void printDiffPtsMask() { uint numVars = __numVars__; if (isFirstThreadOfWarp()) { //printf("DIFF_PTS_MASK: ["); } bool first = true; int to = ceil((float) numVars / (float) ELEMENT_CARDINALITY); for (int base = 0; base < to; base++) { uint myBits = __diffPtsMaskGet__(base, threadIdx.x); printElementAsSet(base, myBits, first); } if (isFirstThreadOfWarp()) ;//printf("]\n"); } __global__ void __printDiffPtsMask() { printDiffPtsMask(); } __device__ void printOffsetMask(uint numObjectsVars, uint offset) { if (isFirstThreadOfWarp()) { //printf("MASK for offset %u: [", offset); } bool first = true; int to = __offsetMaskRowsPerOffset__; for (int base = 0; base < to; base++) { uint myBits = __offsetMaskGet__(base, threadIdx.x, offset); printElementAsSet(base, myBits, first); } if (isFirstThreadOfWarp()) ;//printf("]\n"); } __device__ void printOffsetMasks(uint numObjectsVars, uint maxOffset) { if (!isFirstWarpOfGrid()) { return; } for (int i = 1; i <= maxOffset; i++) { printOffsetMask(numObjectsVars, i); } } __global__ void __printOffsetMasks(uint numObjectsVars, uint maxOffset) { printOffsetMasks(numObjectsVars, maxOffset); } __device__ void printElementRec(uint index) { volatile uint myBits = __graphGet__(index, threadIdx.x); uint all = __all_sync(0xffffffff,myBits == NIL); if (all) { return; } while (index != NIL) { //printf("Thread: %u, value: %u\n", threadIdx.x, myBits); index = __graphGet__(index, NEXT); if (index != NIL) { myBits = __graphGet__(index, threadIdx.x); } } } __device__ void printSharedElementRec(uint* volatile _shared_, uint index) { volatile uint myBits = _sharedGet_(_shared_, index, threadIdx.x); uint all = __all_sync(0xffffffff,myBits == NIL); if (all) { return; } while (index != NIL) { //printf("Thread: %u, value: %u\n", threadIdx.x, myBits); index = _sharedGet_(_shared_, index, NEXT); if (index != NIL) { myBits = _sharedGet_(_shared_, index, threadIdx.x); } } } __device__ void accumulate(const uint base, uint myBits, uint& numFrom, uint rel) { uint nonEmpty = __ballot_sync(0xffffffff,myBits && threadIdx.x < BASE); while (nonEmpty) { uint pos = __ffs(nonEmpty) - 1; nonEmpty &= (nonEmpty - 1); uint bits = getValAtThread(myBits, pos); uint numOnes = __popc(bits); //cudaAssert(numFrom + numOnes > PRINT_BUFFER_SIZE); uint var = mul960(base) + mul32(pos) + threadIdx.x; // PTS edges: we do not use representatives. In all the other relations we do. var = isBitActive(bits, threadIdx.x) ? (rel > CURR_DIFF_PTS ? __rep__[var] : var) : NIL; pos = numFrom + __popc(bits & ((1 << threadIdx.x) - 1)); if (var != NIL) { __printBuffer__[pos] = var; } numFrom += numOnes; } } __device__ void printEdges(const uint src, const uint rel, const uint printEmptySets) { if (isEmpty(src, rel) && !printEmptySets) { return; } if (isFirstThreadOfWarp()) { //printf("%d => [", src); } uint index = getHeadIndex(src, rel); uint numFrom = 0; do { uint myBits = __graphGet__(index, threadIdx.x); uint base = __graphGet__(index, BASE); if (base == NIL) { break; } index = __graphGet__(index, NEXT); accumulate(base, myBits, numFrom, rel); } while (index != NIL); if (numFrom) { if (rel > CURR_DIFF_PTS) { numFrom = removeDuplicates(__printBuffer__, numFrom); } for (int i = 0; i < numFrom; i++) { uint val = __printBuffer__[i]; // has to be non-NIL if (isFirstThreadOfWarp()) { if (!i) { //printf("%u", val); } else { //printf(", %u", val); } } } } if (isFirstThreadOfWarp()) { //printf("]\n"); } } __device__ void printEdgesOf(const uint src, int rel) { if (isFirstThreadOfWarp()) { //printf("%s of ", getName(rel)); } printEdges(src, rel, 1); } __device__ void printEdgesStartingAt(uint index, int rel) { if (isFirstThreadOfWarp()) { //printf("%s @ %u => [", getName(rel), index); } uint numFrom = 0; do { uint myBits = __graphGet__(index, threadIdx.x); uint base = __graphGet__(index, BASE); if (base == NIL) { break; } index = __graphGet__(index, NEXT); accumulate(base, myBits, numFrom, rel); } while (index != NIL); if (numFrom) { if (rel > CURR_DIFF_PTS) { numFrom = removeDuplicates(__printBuffer__, numFrom); } for (int i = 0; i < numFrom; i++) { uint val = __printBuffer__[i]; // has to be non-NIL if (isFirstThreadOfWarp()) { if (!i) { //printf("%u", val); } else { //printf(", %u", val); } } } } if (isFirstThreadOfWarp()) { //printf("]\n"); } } __device__ void printEdgesOf(uint src) { for (int i = 0; i <= LAST_DYNAMIC_REL; i++) { printEdgesOf(src, i); } } __global__ void __printEdgesOf(uint src, int rel) { printEdgesOf(src, rel); } __global__ void __printEdgesOf(uint src) { printEdgesOf(src); } __device__ void printEdges(int rel) { if (isFirstThreadOfWarp()) { //printf("%s edges:\n", getName(rel)); } for (int src = 0; src < __numVars__; src++) { printEdges(src, rel, 0); } } __global__ void __printEdges(int rel) { printEdges(rel); } __device__ void printGepEdges() { uint numVarsGepInv = __numGepInv__; if (isFirstThreadOfWarp()) { //printf("GEP_INV edges:\n"); } volatile __shared__ uint _shared_[WARP_SIZE]; for (int i = 0; i < numVarsGepInv; i += WARP_SIZE) { _shared_[threadIdx.x] = __gepInv__[i + threadIdx.x]; for (int j= 0; j < WARP_SIZE && _shared_[j] != NIL; j +=2) { uint dst = _shared_[j]; uint srcOffset = _shared_[j + 1]; if (isFirstThreadOfWarp()) { //printf("%u => %u (%u)\n", dst, id(srcOffset), offset(srcOffset)); } } } } __global__ void __printGepEdges() { printGepEdges(); } __device__ void printConstraints(uint* __constraints__, const uint numConstraints) { volatile __shared__ uint _shared_[WARP_SIZE]; for (int i = 0; i < numConstraints * 2; i += WARP_SIZE) { _shared_[threadIdx.x] = __constraints__[i + threadIdx.x]; for (int j = 0; j < WARP_SIZE; j += 2) { if (i + j >= numConstraints * 2) { return; } uint src = _shared_[j]; uint dst = _shared_[j + 1]; if (isFirstThreadOfWarp()) { //printf("%u => %u\n", src, dst); } } } } __device__ int checkForErrors(uint var, uint rel) { uint index = getHeadIndex(var, rel); uint lastBase = 0; uint first = 1; uint bits = __graphGet__(index, threadIdx.x); uint all = __all_sync(0xffffffff,bits == NIL); if (all) { return 0; } do { bits = __graphGet__(index, threadIdx.x); uint all_bits = __all_sync(0xffffffff,threadIdx.x >= BASE || bits == NIL); if (all_bits) { if (isFirstThreadOfWarp()) { //printf("ERROR: empty element at %s of %u \n", getName(rel), var); } //printElementRec(getHeadIndex(var, rel)); __error__ = 1; return 1; } uint base = __graphGet__(index, BASE); index = __graphGet__(index, NEXT); if (base == NIL) { if (isFirstThreadOfWarp()) { //printf("ERROR: inconsistency at %s of %u: BASE is NIL but other word is not\n", //getName(rel), var); } printElementRec(getHeadIndex(var, rel)); __error__ = 1; return 1; } if (!first && base <= lastBase) { if (isFirstThreadOfWarp()) { //printf("ERROR: BASE(element) = %u <= BASE(prev(element)) = %u at %s of %u\n", base, //lastBase, getName(rel), var); } //printElementRec(getHeadIndex(var, rel)); __error__ = 1; return 1; } first = 0; lastBase = base; } while (index != NIL); return 0; } __global__ void checkForErrors(uint rel) { uint numVars = __numVars__; int inc = mul32(getWarpsPerGrid()); int init = mul32(getWarpIdInGrid()); for (int initVar = init; initVar < numVars; initVar += inc) { for (int i = 0; i < WARP_SIZE; i++) { uint var = initVar + i; if (var > numVars || checkForErrors(var, rel)) { return; } } } } __device__ uint hashCode(uint index) { __shared__ uint _sh_[DEF_THREADS_PER_BLOCK]; volatile uint* _shared_ = &_sh_[threadIdx.y * WARP_SIZE]; uint myRet = 0; uint bits = __graphGet__(index + threadIdx.x); uint base = __graphGet__(index + BASE); if (base == NIL) { return 0; } while (1) { uint elementHash = base * (30 + threadIdx.x) ^ bits; if (bits) { myRet ^= elementHash; } index = __graphGet__(index + NEXT); if (index == NIL) { break; } bits = __graphGet__(index + threadIdx.x); base = __graphGet__(index + BASE); } _shared_[threadIdx.x] = myRet; if (threadIdx.x < 14) { _shared_[threadIdx.x] ^= _shared_[threadIdx.x + WARP_SIZE / 2]; } if (threadIdx.x < 8) { _shared_[threadIdx.x] ^= _shared_[threadIdx.x + WARP_SIZE / 4]; } if (threadIdx.x < 4) { _shared_[threadIdx.x] ^= _shared_[threadIdx.x + WARP_SIZE / 8]; } return _shared_[0] ^ _shared_[1] ^ _shared_[2] ^ _shared_[3]; } __device__ uint equal(uint index1, uint index2) { uint bits1 = __graphGet__(index1 + threadIdx.x); uint bits2 = __graphGet__(index2 + threadIdx.x); uint all = __all_sync(0xffffffff,(threadIdx.x == NEXT) || (bits1 == bits2)); while (all) { index1 = __graphGet__(index1 + NEXT); index2 = __graphGet__(index2 + NEXT); if (index1 == NIL || index2 == NIL) { return index1 == index2; } bits1 = __graphGet__(index1 + threadIdx.x); bits2 = __graphGet__(index2 + threadIdx.x); } return 0; } __device__ uint size(uint var, uint rel) { __shared__ uint _sh_[DEF_THREADS_PER_BLOCK]; volatile uint* _shared_ = &_sh_[threadIdx.y * WARP_SIZE]; if (isEmpty(var, rel)) { return 0; } uint index = getHeadIndex(var, rel); uint myRet = 0; do { uint myBits = __graphGet__(index, threadIdx.x); index = __graphGet__(index, NEXT); myRet += __popc(myBits); } while (index != NIL); _shared_[threadIdx.x] = threadIdx.x >= BASE ? 0 : myRet; for (int stride = WARP_SIZE / 2; stride > 0; stride >>= 1) { if (threadIdx.x < stride) { _shared_[threadIdx.x] += _shared_[threadIdx.x + stride]; } } return _shared_[0]; } __device__ void unionToCopyInv(const uint to, const uint fromIndex, uint* const _shared_, bool applyCopy = true) { uint toIndex = getCopyInvHeadIndex(to); if (fromIndex == toIndex) { return; } uint fromBits = __graphGet__(fromIndex + threadIdx.x); uint fromBase = __graphGet__(fromIndex + BASE); if (fromBase == NIL) { return; } uint fromNext = __graphGet__(fromIndex + NEXT); uint toBits = __graphGet__(toIndex + threadIdx.x); uint toBase = __graphGet__(toIndex + BASE); uint toNext = __graphGet__(toIndex + NEXT); uint numFrom = 0; uint newVal; while (1) { if (toBase > fromBase) { if (toBase == NIL) { newVal = fromNext == NIL ? NIL : mallocOther(); } else { newVal = mallocOther(); __graphSet__(newVal + threadIdx.x, toBits); } fromBits = threadIdx.x == NEXT ? newVal : fromBits; __graphSet__(toIndex + threadIdx.x, fromBits); if (applyCopy) { map<NEXT_DIFF_PTS, PTS>(to, fromBase, fromBits, _shared_, numFrom); } if (fromNext == NIL) { break; } toIndex = newVal; fromBits = __graphGet__(fromNext + threadIdx.x); fromBase = __graphGet__(fromNext + BASE); fromNext = __graphGet__(fromNext + NEXT); } else if (toBase == fromBase) { uint orBits = fromBits | toBits; uint diffs = __any_sync(0xffffffff,uint(orBits != toBits && threadIdx.x < NEXT)); bool nextWasNil = false; if (toNext == NIL && fromNext != NIL) { toNext = mallocOther(); nextWasNil = true; } uint newBits = threadIdx.x == NEXT ? toNext : orBits; if (newBits != toBits) { __graphSet__(toIndex + threadIdx.x, newBits); } // if there was any element added to COPY_INV, apply COPY_INV rule if (applyCopy && diffs) { uint diffBits = fromBits & ~toBits; map<NEXT_DIFF_PTS, PTS > (to, fromBase, diffBits, _shared_, numFrom); } //advance `to` and `from` if (fromNext == NIL) { break; } toIndex = toNext; if (nextWasNil) { toBits = NIL; toBase = NIL; toNext = NIL; } else { toBits = __graphGet__(toIndex + threadIdx.x); toBase = __graphGet__(toIndex + BASE); toNext = __graphGet__(toIndex + NEXT); } fromBits = __graphGet__(fromNext + threadIdx.x); fromBase = __graphGet__(fromNext + BASE); fromNext = __graphGet__(fromNext + NEXT); } else { //toBase < fromBase if (toNext == NIL) { uint newNext = mallocOther(); __graphSet__(toIndex + NEXT, newNext); toIndex = newNext; toBits = NIL; toBase = NIL; } else { toIndex = toNext; toBits = __graphGet__(toNext + threadIdx.x); toBase = __graphGet__(toIndex + BASE); toNext = __graphGet__(toNext + NEXT); } } } if (applyCopy && numFrom) { // flush pending unions unionAll<NEXT_DIFF_PTS, PTS> (to, _shared_, numFrom); } } __device__ void clone(uint toIndex, uint fromBits, uint fromNext, const uint toRel) { while (1) { uint newIndex = fromNext == NIL ? NIL : mallocIn(toRel); uint val = threadIdx.x == NEXT ? newIndex : fromBits; __graphSet__(toIndex + threadIdx.x, val); if (fromNext == NIL) { break; } toIndex = newIndex; fromBits = __graphGet__(fromNext + threadIdx.x); fromNext = __graphGet__(fromNext + NEXT); } } // toRel = any non-static relationship __device__ void unionG2G(const uint to, const uint toRel, const uint fromIndex) { uint toIndex = getHeadIndex(to, toRel); uint fromBits = __graphGet__(fromIndex + threadIdx.x); uint fromBase = __graphGet__(fromIndex + BASE); if (fromBase == NIL) { return; } uint fromNext = __graphGet__(fromIndex + NEXT); uint toBits = __graphGet__(toIndex + threadIdx.x); uint toBase = __graphGet__(toIndex + BASE); if (toBase == NIL) { clone(toIndex, fromBits, fromNext, toRel); return; } uint toNext = __graphGet__(toIndex + NEXT); while (1) { if (toBase > fromBase) { uint newIndex = mallocIn(toRel); __graphSet__(newIndex + threadIdx.x, toBits); uint val = threadIdx.x == NEXT ? newIndex : fromBits; __graphSet__(toIndex + threadIdx.x, val); // advance 'from' if (fromNext == NIL) { return; } toIndex = newIndex; fromBits = __graphGet__(fromNext + threadIdx.x); fromBase = __graphGet__(fromNext + BASE); fromNext = __graphGet__(fromNext + NEXT); } else if (toBase == fromBase) { uint newToNext = (toNext == NIL && fromNext != NIL) ? mallocIn(toRel) : toNext; uint orBits = fromBits | toBits; uint newBits = threadIdx.x == NEXT ? newToNext : orBits; if (newBits != toBits) { __graphSet__(toIndex + threadIdx.x, newBits); } //advance `to` and `from` if (fromNext == NIL) { return; } fromBits = __graphGet__(fromNext + threadIdx.x); fromBase = __graphGet__(fromNext + BASE); fromNext = __graphGet__(fromNext + NEXT); if (toNext == NIL) { clone(newToNext, fromBits, fromNext, toRel); return; } toIndex = newToNext; toBits = __graphGet__(toNext + threadIdx.x); toBase = __graphGet__(toNext + BASE); toNext = __graphGet__(toNext + NEXT); } else { // toBase < fromBase if (toNext == NIL) { toNext = mallocIn(toRel); __graphSet__(toIndex + NEXT, toNext); clone(toNext, fromBits, fromNext, toRel); return; } toIndex = toNext; toBits = __graphGet__(toNext + threadIdx.x); toBase = __graphGet__(toNext + BASE); toNext = __graphGet__(toNext + NEXT); } } } // WATCH OUT: ASSUMES fromRel==toRel // like unionTo, but reusing the elements of 'from' (introduces sharing of elements) // toRel = any non-static relationship __device__ void unionG2GRecycling(const uint to, const uint toRel, uint fromIndex) { uint fromBits = __graphGet__(fromIndex, threadIdx.x); uint fromBase = __graphGet__(fromIndex, BASE); if (fromBase == NIL) { return; } uint toIndex = getHeadIndex(to, toRel); uint toBits = __graphGet__(toIndex, threadIdx.x); uint toBase = __graphGet__(toIndex, BASE); if (toBase == NIL) { __graphSet__(toIndex, threadIdx.x, fromBits); return; } uint toNext = __graphGet__(toIndex, NEXT); uint fromNext = __graphGet__(fromIndex, NEXT); uint fromHeadIndex = fromIndex; do { if (toBase == fromBase) { uint newToNext = (toNext == NIL) ? fromNext : toNext; uint orBits = fromBits | toBits; uint newBits = threadIdx.x == NEXT ? newToNext : orBits; if (newBits != toBits) { __graphSet__(toIndex, threadIdx.x, newBits); } //advance `to` and `from` if (toNext == NIL || fromNext == NIL) { // done with current elt and there is no NEXT => exit return; } fromIndex = fromNext; fromBits = __graphGet__(fromIndex, threadIdx.x); fromBase = __graphGet__(fromIndex, BASE); fromNext = __graphGet__(fromIndex, NEXT); toIndex = toNext; toBits = __graphGet__(toIndex, threadIdx.x); toBase = __graphGet__(toIndex, BASE); toNext = __graphGet__(toIndex, NEXT); } else if (toBase < fromBase) { if (toNext == NIL) { if (fromIndex == fromHeadIndex) { fromIndex = mallocIn(toRel); __graphSet__(fromIndex, threadIdx.x, fromBits); } __graphSet__(toIndex, NEXT, fromIndex); return; } // advance 'to' toIndex = toNext; toBits = __graphGet__(toIndex, threadIdx.x); toBase = __graphGet__(toIndex, BASE); toNext = __graphGet__(toIndex, NEXT); } else { // toBase > fromBase if (fromIndex == fromHeadIndex) { fromIndex = mallocIn(toRel); } __graphSet__(fromIndex, threadIdx.x, toBits); int val = threadIdx.x == NEXT ? fromIndex : fromBits; __graphSet__(toIndex, threadIdx.x, val); toIndex = fromIndex; // toBits does not change fromIndex = fromNext; if (fromNext != NIL) { //advance 'from' fromBits = __graphGet__(fromIndex, threadIdx.x); fromBase = __graphGet__(fromIndex, BASE); fromNext = __graphGet__(fromIndex, NEXT); } } } while (fromIndex != NIL); } __device__ uint addVirtualElement(uint index, const uint fromBase, const uint fromBits, const uint toRel) { for (;;) { uint toBits = __graphGet__(index + threadIdx.x); uint toBase = __graphGet__(index + BASE); if (toBase == NIL) { // can only happen if the adjancency list of `to` is empty // cost: exactly one global write __graphSet__(index + threadIdx.x, fromBits); return index; } if (toBase == fromBase) { // cost: at most one global write uint orBits = toBits | fromBits; if (orBits != toBits && threadIdx.x < NEXT) { __graphSet__(index + threadIdx.x, orBits); } return index; } if (toBase < fromBase) { uint toNext = getValAtThread(toBits, NEXT); if (toNext == NIL) { // appending; cost: two global writes uint newIndex = mallocIn(toRel); __graphSet__(newIndex + threadIdx.x, fromBits); __graphSet__(index + NEXT, newIndex); return newIndex; } index = toNext; } else { // cost: two global writes uint newIndex = mallocIn(toRel); __graphSet__(newIndex + threadIdx.x, toBits); uint val = threadIdx.x == NEXT ? newIndex : fromBits; __graphSet__(index + threadIdx.x, val); return index; } } } __device__ uint insert(const uint index, const uint var, const int rel) { uint base = BASE_OF(var); uint word = WORD_OF(var); uint bit = BIT_OF(var); uint myBits = 0; if (threadIdx.x == word) { myBits = 1 << bit; } else if (threadIdx.x == BASE) { myBits = base; } else if (threadIdx.x == NEXT) { myBits = NIL; } return addVirtualElement(index, base, myBits, rel); } __device__ inline uint resetWorklistIndex() { __syncthreads(); uint numBlocks = getBlocksPerGrid(); if (isFirstThreadOfBlock() && atomicInc(&__counter__, numBlocks - 1) == (numBlocks - 1)) { __worklistIndex0__ = 0; __counter__ = 0; return 1; } return 0; } __global__ void addEdges(uint* __key__, uint* __keyAux__, uint* __val__, const uint to, uint rel) { __shared__ uint _sh_[WARPS_PER_BLOCK(DEF_THREADS_PER_BLOCK) * WARP_SIZE]; uint* _shared_ = &_sh_[threadIdx.y * WARP_SIZE]; uint i = getAndIncrement(1); while (i < to) { uint src = __key__[i]; if (src == NIL) { break; } uint index = getHeadIndex(src, rel); uint startIndex = __keyAux__[i]; uint end = __keyAux__[i + 1]; uint start = roundToPrevMultipleOf(startIndex, WARP_SIZE); // to ensure alignment for (int j = start; j < end; j += WARP_SIZE) { uint myIndex = j + threadIdx.x; _shared_[threadIdx.x] = myIndex < end ? __val__[myIndex] : NIL; uint startK = max(((int) startIndex) - j, 0); uint endK = min(end - j, WARP_SIZE); for (int k = startK; k < endK; k++) { uint dst = _shared_[k]; index = insert(index, dst, rel); } } i = getAndIncrement(1); } resetWorklistIndex(); } template<uint toRel, uint fromRel> __device__ inline void unionAll(const uint to, uint* const _shared_, uint numFrom, bool sort) { if (numFrom > 1 && sort) { numFrom = removeDuplicates(_shared_, numFrom); } for (int i = 0; i < numFrom; i++) { uint fromIndex = _shared_[i]; if (fromRel != CURR_DIFF_PTS) { fromIndex = getHeadIndex(fromIndex, fromRel); } if (toRel == COPY_INV) { unionToCopyInv(to, fromIndex, _shared_ + DECODE_VECTOR_SIZE + 1); } else { unionG2G(to, toRel, fromIndex); } } } template<uint toRel, uint fromRel> __device__ void map(uint to, const uint base, const uint myBits, uint* const _shared_, uint& numFrom) { uint ballot = __ballot_sync(0xffffffff,myBits); uint nonEmpty = ballot & LT_BASE; const uint threadMask = 1 << threadIdx.x; const uint myMask = threadMask - 1; const uint mul960base = mul960(base); while (nonEmpty) { uint pos = __ffs(nonEmpty) - 1; nonEmpty &= (nonEmpty - 1); uint bits = getValAtThread(myBits, pos); uint var = getRep(mul960base + mul32(pos) + threadIdx.x); //coalesced uint bitActive = (var != I2P) && (bits & threadMask); bits = __ballot_sync(0xffffffff,bitActive); uint numOnes = __popc(bits); if (numFrom + numOnes > DECODE_VECTOR_SIZE) { numFrom = removeDuplicates(_shared_, numFrom); if (numFrom + numOnes > DECODE_VECTOR_SIZE) { if (toRel == STORE) { insertAll(to, _shared_, numFrom, false); } else { unionAll<toRel, fromRel>(to, _shared_, numFrom, false); } numFrom = 0; } } pos = numFrom + __popc(bits & myMask); if (bitActive) { if (fromRel == CURR_DIFF_PTS) { _shared_[pos] = __currPtsHead__[var]; } else { _shared_[pos] = var; } } numFrom += numOnes; } } template<uint firstRel, uint secondRel, uint thirdRel> __device__ void apply(const uint src, uint* const _shared_) { uint numFrom = 0; uint index = getHeadIndex(src, firstRel); do { uint myBits = __graphGet__(index + threadIdx.x); uint base = __graphGet__(index + BASE); if (base == NIL) { break; } index = __graphGet__(index + NEXT); if (secondRel == CURR_DIFF_PTS) { myBits &= __diffPtsMaskGet__(base, threadIdx.x); } map<thirdRel, secondRel>(src, base, myBits, _shared_, numFrom); } while (index != NIL); if (numFrom) { unionAll<thirdRel, secondRel>(src, _shared_, numFrom); } } __device__ void insertAll(const uint src, uint* const _shared_, uint numFrom, const bool sort) { if (numFrom > 1 && sort) { numFrom = removeDuplicates(_shared_, numFrom); } const uint storeIndex = getStoreHeadIndex(src); for (int i = 0; i < numFrom; i += WARP_SIZE) { uint size = min(numFrom - i, WARP_SIZE); uint next = getAndIncrement(&__numKeysCounter__, size); // TODO: we need to make sure that (next + threadIdx.x < MAX_HASH_SIZE) if (threadIdx.x < size) { __key__[next + threadIdx.x] = _shared_[i + threadIdx.x]; // at most 2 transactions __val__[next + threadIdx.x] = storeIndex; } } } __device__ void store2storeInv(const uint src, uint* const _shared_) { uint currDiffPtsIndex = getCurrDiffPtsHeadIndex(src); uint numFrom = 0; do { uint myBits = __graphGet__(currDiffPtsIndex + threadIdx.x); uint base = __graphGet__(currDiffPtsIndex + BASE); if (base == NIL) { break; } currDiffPtsIndex = __graphGet__(currDiffPtsIndex + NEXT); map<STORE, STORE>(src, base, myBits, _shared_, numFrom); } while (currDiffPtsIndex != NIL); if (numFrom) { insertAll(src, _shared_, numFrom); } } __global__ void copyInv_loadInv_store2storeInv() { __shared__ uint _sh_[WARPS_PER_BLOCK(COPY_INV_THREADS_PER_BLOCK) * (DECODE_VECTOR_SIZE * 2 + 2)]; uint* const _shared_ = &_sh_[threadIdx.y * (DECODE_VECTOR_SIZE * 2 + 2)]; _shared_[0] = NIL; _shared_[DECODE_VECTOR_SIZE + 1] = NIL; uint to = __numVars__; uint src = getAndIncrement(&__worklistIndex1__, 1); while (src < to) { apply<COPY_INV, CURR_DIFF_PTS, NEXT_DIFF_PTS>(src, _shared_ + 1 + DECODE_VECTOR_SIZE + 1); apply<LOAD_INV, CURR_DIFF_PTS, COPY_INV>(src, _shared_ + 1); src = getAndIncrement(&__worklistIndex1__,1); } to = __numStore__; src = getAndIncrement(1); while (src < to) { src = __storeConstraints__[src]; if (src != NIL) { store2storeInv(src, _shared_ + 1); } src = getAndIncrement(1); } if (resetWorklistIndex()) { __key__[__numKeysCounter__] = NIL; __val__[__numKeysCounter__] = NIL; __numKeys__ = __numKeysCounter__ + 1; __numKeysCounter__ = 0; __worklistIndex1__ = 0; } } __device__ void warpStoreInv(const uint i, uint* const _pending_, uint* _numPending_) { uint src = __key__[i]; uint startIndex = __keyAux__[i]; uint end = __keyAux__[i + 1]; if (end - startIndex > WARPS_PER_BLOCK(STORE_INV_THREADS_PER_BLOCK) * 4) { // too big for a single warp => add to pending, so the whole block will process this variable if (isFirstThreadOfWarp()) { uint where = 3 * atomicAdd(_numPending_, 1); _pending_[where] = src; _pending_[where + 1] = startIndex; _pending_[where + 2] = end; } return; } uint* const _shared_ = _pending_ + WARPS_PER_BLOCK(STORE_INV_THREADS_PER_BLOCK) * 3 + threadIdx.y * (WARP_SIZE + DECODE_VECTOR_SIZE + 1); _shared_[WARP_SIZE] = NIL; uint start = roundToPrevMultipleOf(startIndex, WARP_SIZE); // to ensure alignment for (int j = start; j < end; j += WARP_SIZE) { uint myIndex = j + threadIdx.x; _shared_[threadIdx.x] = myIndex < end ? __val__[myIndex] : NIL; uint startK = max(((int) startIndex) - j, 0); uint endK = min(end - j, WARP_SIZE); for (int k = startK; k < endK; k++) { uint fromIndex = _shared_[k]; unionToCopyInv(src, fromIndex, _shared_ + 1 + WARP_SIZE); } } } __device__ void blockStoreInv(uint src, uint* const _dummyVars_, volatile uint* _warpInfo_, uint& _numPending_) { uint* _shared_ = _dummyVars_ + WARPS_PER_BLOCK(STORE_INV_THREADS_PER_BLOCK) * 4 + threadIdx.y * (WARP_SIZE + DECODE_VECTOR_SIZE + 1); __shared__ uint _counter_, _start_, _end_; _shared_[WARP_SIZE] = NIL; _shared_ += WARP_SIZE + 1; __syncthreads(); for (int i = 0; i < _numPending_; i++) { if (isFirstWarpOfBlock()) { uint* pending = _dummyVars_ + WARPS_PER_BLOCK(STORE_INV_THREADS_PER_BLOCK); src = pending[3 * i]; _start_ = pending[3 * i + 1]; _end_ = pending[3 * i + 2]; _counter_ = _start_; } __syncthreads(); if (isFirstThreadOfWarp()) { _warpInfo_[threadIdx.y] = atomicAdd(&_counter_, 1); } uint j = _warpInfo_[threadIdx.y]; while (j < _end_) { uint fromIndex = __val__[j]; unionToCopyInv(src, fromIndex, _shared_, isFirstWarpOfBlock()); if (isFirstThreadOfWarp()) { _warpInfo_[threadIdx.y] = atomicAdd(&_counter_, 1); } j = _warpInfo_[threadIdx.y]; } __syncthreads(); if (isFirstWarpOfBlock()) { for (int i = 1; i < WARPS_PER_BLOCK(STORE_INV_THREADS_PER_BLOCK); i++) { uint var2 = _dummyVars_[i]; unionToCopyInv(src, getCopyInvHeadIndex(var2), _shared_); } } __syncthreads(); if (!isFirstWarpOfBlock()) { //reset fields so updateDiffPts doesn't work on dummy variables uint index = getHeadIndex(src, COPY_INV); __graphSet__(index, threadIdx.x, NIL); } } if (isFirstWarpOfBlock()) { _numPending_ = 0; } __syncthreads(); } __global__ void storeInv() { __shared__ uint _sh_[WARPS_PER_BLOCK(STORE_INV_THREADS_PER_BLOCK) * (5 + WARP_SIZE + DECODE_VECTOR_SIZE + 1)]; __shared__ volatile uint* _warpInfo_; __shared__ volatile uint _warpsWorking_; __shared__ uint* _dummyVars_; __shared__ uint _numPending_, _to_; if (isFirstWarpOfBlock()) { _to_ = __numKeys__ - 1; // because the last one is NIL _dummyVars_ = _sh_ + WARPS_PER_BLOCK(STORE_INV_THREADS_PER_BLOCK); if (threadIdx.x < WARPS_PER_BLOCK(STORE_INV_THREADS_PER_BLOCK)) { _dummyVars_[threadIdx.x] = __initialNonRep__[mul32(blockIdx.x) + threadIdx.x]; } _warpInfo_ = _sh_; _numPending_ = 0; _warpsWorking_ = WARPS_PER_BLOCK(STORE_INV_THREADS_PER_BLOCK); } __syncthreads(); uint counter, src; if (!isFirstWarpOfBlock()) { src = _dummyVars_[threadIdx.y]; } if (isFirstThreadOfWarp()) { uint next = atomicAdd(&__worklistIndex0__, 1); if (next >= _to_) { atomicSub((uint*) &_warpsWorking_, 1); } _warpInfo_[threadIdx.y] = next; } counter = _warpInfo_[threadIdx.y]; while (_warpsWorking_) { if (counter < _to_) { warpStoreInv(counter, _sh_ + WARPS_PER_BLOCK(STORE_INV_THREADS_PER_BLOCK) * 2, &_numPending_); } __syncthreads(); if (_numPending_) { blockStoreInv(src, _dummyVars_, _warpInfo_, _numPending_); } if (counter < _to_ ) { if (isFirstThreadOfWarp()) { uint next = atomicAdd(&__worklistIndex0__, 1); if (next >= _to_) { atomicSub((uint*) &_warpsWorking_, 1); } _warpInfo_[threadIdx.y] = next; } counter = _warpInfo_[threadIdx.y]; } } resetWorklistIndex(); } __device__ void shift(const uint base, const uint bits, const uint offset, volatile uint* _shifted_) { _shifted_[threadIdx.x] = 0; _shifted_[threadIdx.x + WARP_SIZE] = 0; _shifted_[threadIdx.x + WARP_SIZE * 2] = 0; uint delta = div32(offset); uint highWidth = mod32(offset); uint lowWidth = WARP_SIZE - highWidth; // these memory accesses do not conflict _shifted_[threadIdx.x + delta] = (bits << highWidth); _shifted_[threadIdx.x + delta + 1] |= (bits >> lowWidth); _shifted_[threadIdx.x + WARP_SIZE * 2] = _shifted_[threadIdx.x + BASE * 2]; _shifted_[threadIdx.x + WARP_SIZE] = _shifted_[threadIdx.x + BASE]; _shifted_[BASE] = base; _shifted_[BASE + WARP_SIZE] = base + 1; _shifted_[BASE + WARP_SIZE * 2] = base + 2; } __device__ void applyGepInvRule(uint x, const uint y, const uint offset, volatile uint* _shared_) { uint yIndex = getCurrDiffPtsHeadIndex(y); uint myBits = __graphGet__(yIndex, threadIdx.x); uint all = __all_sync(0xffffffff,myBits == NIL); if (all) { return; } uint xIndex = getNextDiffPtsHeadIndex(x); do { myBits = __graphGet__(yIndex, threadIdx.x); uint base = __graphGet__(yIndex, BASE); yIndex = __graphGet__(yIndex, NEXT); myBits &= __offsetMaskGet__(base, threadIdx.x, offset); uint all = __all_sync(0xffffffff,myBits == 0); if (all) { continue; } shift(base, myBits, offset, _shared_); for (int i = 0; i < 3; i++) { uint myBits = threadIdx.x == NEXT ? NIL : _shared_[threadIdx.x + WARP_SIZE * i]; uint all = __any_sync(0xffffffff,myBits && threadIdx.x < BASE); if (all) { xIndex = addVirtualElement(xIndex, base + i, myBits, NEXT_DIFF_PTS); } } } while (yIndex != NIL); } __global__ void gepInv() { __shared__ uint _sh_[WARPS_PER_BLOCK(GEP_INV_THREADS_PER_BLOCK) * (WARP_SIZE * 3)]; volatile uint* _shared_ = &_sh_[threadIdx.y * (WARP_SIZE * 3)]; const uint to = __numGepInv__ * 2; uint index = getAndIncrement(2); while (index < to) { uint x = __gepInv__[index]; x = getRep(x); uint val1 = __gepInv__[index + 1]; while (!lock(x)); // busy wait, should be short const uint y = getRep(id(val1)); applyGepInvRule(x, y, offset(val1), _shared_); unlock(x); index = getAndIncrement(2); } if (resetWorklistIndex()) { __done__ = true; } } __device__ void cloneAndLink(const uint var, const uint ptsIndex, uint& currDiffPtsIndex, const uint diffPtsBits, const uint diffPtsNext) { clone(ptsIndex, diffPtsBits, diffPtsNext, PTS); if (currDiffPtsIndex != NIL) { __graphSet__(currDiffPtsIndex + NEXT, ptsIndex); } else { currDiffPtsIndex = getCurrDiffPtsHeadIndex(var); uint ptsBits = __graphGet__(ptsIndex + threadIdx.x); __graphSet__(currDiffPtsIndex + threadIdx.x, ptsBits); } } /** * Update the current, next and total PTS sets of a variable. In the last iteration of the main * loop, points-to edges have been added to NEXT_DIFF_PTS. However, many of them might already be * present in PTS. The purpose of this function is to update PTS as PTS U NEXT_DIFF_PTS, and set * CURR_DIFF_PTS as the difference between the old and new PTS for the given variable. * * @param var ID of the variable * @return true if new pts edges have been added to this variable */ __device__ bool updatePtsAndDiffPts(const uint var) { const uint diffPtsHeadIndex = getNextDiffPtsHeadIndex(var); uint diffPtsBits = __graphGet__(diffPtsHeadIndex + threadIdx.x); uint diffPtsBase = __graphGet__(diffPtsHeadIndex + BASE); if (diffPtsBase == NIL) { return false; } uint diffPtsNext = __graphGet__(diffPtsHeadIndex + NEXT); __graphSet__(diffPtsHeadIndex + threadIdx.x, NIL); uint ptsIndex = getPtsHeadIndex(var); uint ptsBits = __graphGet__(ptsIndex + threadIdx.x); uint ptsBase = __graphGet__(ptsIndex + BASE); if (ptsBase == NIL) { //we pass ptsBase instead of NIL because it's also NIL but it can be modified cloneAndLink(var, ptsIndex, ptsBase, diffPtsBits, diffPtsNext); return true; } uint ptsNext = __graphGet__(ptsIndex + NEXT); uint currDiffPtsIndex = NIL; while (1) { if (ptsBase > diffPtsBase) { uint newIndex = mallocPts(); __graphSet__(newIndex + threadIdx.x, ptsBits); uint val = threadIdx.x == NEXT ? newIndex : diffPtsBits; __graphSet__(ptsIndex + threadIdx.x, val); ptsIndex = newIndex; // update CURR_DIFF_PTS newIndex = currDiffPtsIndex == NIL ? getCurrDiffPtsHeadIndex(var) : mallocCurrDiffPts(); val = threadIdx.x == NEXT ? NIL : diffPtsBits; __graphSet__(newIndex + threadIdx.x, val); if (currDiffPtsIndex != NIL) { __graphSet__(currDiffPtsIndex + NEXT, newIndex); } if (diffPtsNext == NIL) { return true; } currDiffPtsIndex = newIndex; diffPtsBits = __graphGet__(diffPtsNext + threadIdx.x); diffPtsBase = __graphGet__(diffPtsNext + BASE); diffPtsNext = __graphGet__(diffPtsNext + NEXT); } else if (ptsBase == diffPtsBase) { uint newPtsNext = (ptsNext == NIL && diffPtsNext != NIL) ? mallocPts() : ptsNext; uint orBits = threadIdx.x == NEXT ? newPtsNext : ptsBits | diffPtsBits; uint ballot = __ballot_sync(0xffffffff,orBits != ptsBits); if (ballot) { __graphSet__(ptsIndex + threadIdx.x, orBits); if (ballot & LT_BASE) { // update CURR_DIFF_PTS orBits = diffPtsBits & ~ptsBits; if (threadIdx.x == BASE) { orBits = ptsBase; } else if (threadIdx.x == NEXT) { orBits = NIL; } uint newIndex; if (currDiffPtsIndex != NIL) { newIndex = mallocCurrDiffPts(); __graphSet__(currDiffPtsIndex + NEXT, newIndex); } else { newIndex = getCurrDiffPtsHeadIndex(var); } __graphSet__(newIndex + threadIdx.x, orBits); currDiffPtsIndex = newIndex; } } if (diffPtsNext == NIL) { return (currDiffPtsIndex != NIL); } diffPtsBits = __graphGet__(diffPtsNext + threadIdx.x); diffPtsBase = __graphGet__(diffPtsNext + BASE); diffPtsNext = __graphGet__(diffPtsNext + NEXT); if (ptsNext == NIL) { cloneAndLink(var, newPtsNext, currDiffPtsIndex, diffPtsBits, diffPtsNext); return true; } ptsIndex = ptsNext; ptsBits = __graphGet__(ptsIndex + threadIdx.x); ptsBase = __graphGet__(ptsIndex + BASE); ptsNext = __graphGet__(ptsIndex + NEXT); } else { // ptsBase > diffPtsBase if (ptsNext == NIL) { uint newPtsIndex = mallocPts(); __graphSet__(ptsIndex + NEXT, newPtsIndex); cloneAndLink(var, newPtsIndex, currDiffPtsIndex, diffPtsBits, diffPtsNext); return true; } ptsIndex = ptsNext; ptsBits = __graphGet__(ptsIndex + threadIdx.x); ptsBase = __graphGet__(ptsIndex + BASE); ptsNext = __graphGet__(ptsIndex + NEXT); } } } __global__ void updatePtsInformation() { bool newWork = false; const uint numVars = __numVars__; const uint CHUNK_SIZE = 12; //ulongint start = recordStartTime(); int i = getAndIncrement(CHUNK_SIZE); while (i < numVars) { for (int var = i; var < min(i + CHUNK_SIZE, numVars); var++) { bool newStuff = updatePtsAndDiffPts(var); newWork |= newStuff; if (!newStuff) { const uint currPtsHeadIndex = getCurrDiffPtsHeadIndex(var); __graphSet__(currPtsHeadIndex + threadIdx.x, NIL); } } i = getAndIncrement(CHUNK_SIZE); } if (newWork) { __done__ = false; } // if (isFirstThreadOfWarp()) { // //printf("Warp %u: %u\n", getWarpIdInGrid(), getEllapsedTime(start)); // } uint headerSize = numVars * ELEMENT_WIDTH; if (resetWorklistIndex()) { __currDiffPtsFreeList__ = CURR_DIFF_PTS_START - headerSize; __nextDiffPtsFreeList__ = NEXT_DIFF_PTS_START - headerSize; } } __global__ void createOffsetMasks(int numObjectVars, uint maxOffset) { __shared__ uint _sh_[DEF_THREADS_PER_BLOCK]; volatile uint* _mask_ = &_sh_[threadIdx.y * WARP_SIZE]; int inc = mul960(getWarpsPerGrid()); int init = mul960(getWarpIdInGrid()); for (int i = init; i < numObjectVars; i += inc) { uint base = BASE_OF(i); for (int offset = 1; offset <= maxOffset; offset++) { _mask_[threadIdx.x] = 0; for (int src = i; src < min(i + ELEMENT_CARDINALITY, numObjectVars); src += WARP_SIZE) { uint size = __size__[src + threadIdx.x]; uint all = __all_sync(0xffffffff,size <= offset); if (all) { continue; } uint word = WORD_OF(src - i); _mask_[word] = __ballot_sync(0xffffffff,size > offset); } __offsetMaskSet__(base, threadIdx.x, offset, _mask_[threadIdx.x]); } } } __device__ uint lockToVar(uint lock) { if ((lock < VAR(0)) || (lock >= LOCKED)) { return lock; } return lock - VAR(0); } __device__ void merge(const uint var1, const uint var2, const uint rep) { //if (isFirstThreadOfWarp()) //printf("%u <= %u\n", var1, var2); uint headIndex = getPtsHeadIndex(var2); unionG2GRecycling(var1, PTS, headIndex); __graphSet__(headIndex, threadIdx.x, NIL); headIndex = getCopyInvHeadIndex(var2); unionG2GRecycling(var1, COPY_INV, headIndex); __graphSet__(headIndex, threadIdx.x, NIL); headIndex = getStoreHeadIndex(var2); unionG2GRecycling(var1, STORE, headIndex); __graphSet__(headIndex, threadIdx.x, NIL); headIndex = getLoadInvHeadIndex(var2); unionG2GRecycling(var1, LOAD_INV, headIndex); __graphSet__(headIndex, threadIdx.x, NIL); // clear CURR_DIFF_PTS headIndex = getCurrDiffPtsHeadIndex(var2); //unionG2GRecycling(var1, CURR_DIFF_PTS, headIndex); __graphSet__(headIndex, threadIdx.x, NIL); setRep(var2, rep); __threadfence(); unlock(var2); } /** * Merge a list of pointer-equivalent variables * Granularity: block * @param _list_ Pointer-equivalent variables * @param _listSize_ Number of variables to be processed */ __device__ void mergeCycle(const uint* const _list_, const uint _listSize_) { __shared__ uint _counter_; if (!_listSize_) { __syncthreads(); return; } // 'ry' will be the representative of this cycle uint ry = _list_[0]; if (_listSize_ == 1) { if (isFirstWarpOfBlock()) { unlock(ry); } __syncthreads(); return; } uint warpsPerBlock = getWarpsPerBlock(); if (_listSize_ > warpsPerBlock) { // each warp chooses a local representative and then merges each popped worklist item with it. uint var1 = _list_[threadIdx.y]; _counter_ = warpsPerBlock; __syncthreads(); uint index = getAndIncrement(&_counter_, 1); while (index < _listSize_) { uint var2 = _list_[index]; merge(var1, var2, ry); index = getAndIncrement(&_counter_, 1); } } __syncthreads(); // the first warp merges the local representatives. This is actually faster (and simpler) // than performing a reduction of the list using the entire block, due to load imbalance. if (isFirstWarpOfBlock()) { uint to = min(_listSize_, warpsPerBlock); for (int i = 1; i < to; i++) { uint var = _list_[i]; merge(ry, var, ry); } //reset CURR_PTS of the cycle representative to be PTS uint myBits = __graphGet__(getPtsHeadIndex(ry), threadIdx.x); __graphSet__(getCurrDiffPtsHeadIndex(ry), threadIdx.x, myBits); __threadfence(); unlock(ry); } __syncthreads(); } // to be executed by one thread __device__ uint lockVarRep(uint& var) { while (1) { uint rep = getRepRec(var); uint old = atomicCAS(__lock__ + rep, UNLOCKED, VAR(blockIdx.x)); if (old == PTR(blockIdx.x)) { // try to promote lock to type VAR old = atomicCAS(__lock__ + rep, PTR(blockIdx.x), VAR(blockIdx.x)); } if (old != UNLOCKED && old != PTR(blockIdx.x)) { var = rep; return old; } // we locked it, but maybe is not a representative anymore var = getRep(rep); if (var == rep) { return UNLOCKED; } if (old == PTR(blockIdx.x)) { // back to PTR __lock__[rep] = PTR(blockIdx.x); } else { unlock(rep); } } } /** * Lock a list of variables * Granularity: block * @param _currVar_ List of variables to lock, sorted in ascending order * @param _currVarSize_ Number of variables we want to process. At the end of the function, * it stores the number of variables we were able to lock. * @param _nextVar_ List where to add all the variables we could not lock * @param _nextVarSize_ Number of variables we could not lock */ __device__ void lockVars(uint* const _currVar_, uint& _currVarSize_, uint* const _nextVar_, uint* _nextVarSize_) { __shared__ uint _count_; _count_ = 0; __syncthreads(); for (int i = getThreadIdInBlock(); i < _currVarSize_; i+= getThreadsPerBlock()) { uint var = _currVar_[i]; // block culling to filter out some duplicates if (i && var == _currVar_[i - 1]) { continue; } uint stat = lockVarRep(var); uint pos; if (stat == UNLOCKED) { pos = atomicAdd(&_count_, 1); _currVar_[pos] = var; } else if (stat != VAR(blockIdx.x)) { uint pos = atomicAdd(_nextVarSize_, 1); _nextVar_[pos] = var; } } __syncthreads(); _currVarSize_ = _count_; //first currVarSize positions are populated __syncthreads(); } // to be executed by one WARP __device__ uint lockPtr(uint ptr) { __shared__ volatile uint _shared_[MAX_WARPS_PER_BLOCK]; uint intended = PTR(getBlockIdInGrid()); if (isFirstThreadOfWarp()) { _shared_[threadIdx.y] = atomicCAS(__lock__ + ptr, UNLOCKED, intended); } return _shared_[threadIdx.y]; } /** * Lock every variable in the current points-to set of the input variable. * Granularity: warp * @param x A variable locked by the current block * @param _currVar_ List of locked variables * @param _currVarSize_ Number of locked variables * @param _nextVar_ List of variables we could not lock * @param _nextVarSize_ Number of variables we could not lock */ __device__ void decodeCurrPts(const uint x, uint* const _currVar_, uint* const _currVarSize_, uint* const _nextVar_, uint* const _nextVarSize_) { uint index = getCurrDiffPtsHeadIndex(x); do { uint myBits = __graphGet__(index, threadIdx.x); uint base = __graphGet__(index, BASE); if (base == NIL) { break; } index = __graphGet__(index, NEXT); uint nonEmpty = __ballot_sync(0xffffffff,myBits && threadIdx.x < BASE); uint lastVar = NIL; while (nonEmpty) { uint pos = __ffs(nonEmpty) - 1; nonEmpty &= (nonEmpty - 1); uint bits = getValAtThread(myBits, pos); uint var = mul960(base) + mul32(pos) + threadIdx.x; if (var == I2P || !isBitActive(bits, threadIdx.x)) { var = NIL; } else { uint stat = lockVarRep(var); if (stat != UNLOCKED) { if (stat != VAR(blockIdx.x) && var != lastVar) { // TODO: do something so we do not lose equivalences. This only affects Linux, though uint where = atomicInc(_nextVarSize_, HCD_DECODE_VECTOR_SIZE - 1); _nextVar_[where] = var; lastVar = var; } var = NIL; } } bits = __ballot_sync(0xffffffff,var != NIL); if (!bits) { continue; } uint numOnes = __popc(bits); uint prevNumFrom = 0; if (isFirstThreadOfWarp()) { prevNumFrom = atomicAdd(_currVarSize_, numOnes); } prevNumFrom = getValAtThread(prevNumFrom, 0); // TODO: make sure that (prevNumFrom + numOnes < HCD_DECODE_VECTOR_SIZE) //if (isFirstThreadOfWarp() && ((prevNumFrom + numOnes) >= HCD_DECODE_VECTOR_SIZE)) { // //printf("Exceeded HCD_DECODE_VECTOR_SIZE!!\n"); //} pos = prevNumFrom + __popc(bits & ((1 << threadIdx.x) - 1)); if (var != NIL) { _currVar_[pos] = var; } } } while (index != NIL); } /** * Lock a list of (pointer) variables and their points-to sets * Granularity: block */ __device__ void lockPtrs(uint* const _currPtr_, uint& _currPtrSize_, uint* const _nextPtr_, uint* _nextPtrSize_, uint* const _currVar_, uint* _currVarSize_, uint* const _nextVar_, uint* _nextVarSize_) { const uint warpsPerBlock = getWarpsPerBlock(); for (int i = threadIdx.y; i < _currPtrSize_; i += warpsPerBlock) { uint ptr = _currPtr_[i]; uint stat = lockPtr(ptr); if (stat != UNLOCKED && stat != VAR(blockIdx.x)) { _currPtr_[i] = NIL; if (isFirstThreadOfWarp()) { uint pos = atomicAdd(_nextPtrSize_, 1); _nextPtr_[pos] = ptr; } } else { decodeCurrPts(ptr, _currVar_, _currVarSize_, _nextVar_, _nextVarSize_); } } __syncthreads(); } __device__ void unlockPtrs(const uint* const _list_, const uint _listSize_) { int init = getThreadIdInBlock(); int inc = getThreadsPerBlock(); for (int i = init; i < _listSize_; i += inc) { uint var = _list_[i]; if (var != NIL) { // if it is locked by VAR(blockIdx.x), keep it that way atomicCAS(__lock__ + var, PTR(blockIdx.x), UNLOCKED); } } __syncthreads(); } /** * Online phase of Hybrid Cycle Detection * This is when things get really hairy -- but the overall performance of the algorithm is * dramatically improved by removing the equivalents discovered during the offline analysis, so * there is not way around it AFAIK. * The kernel takes a list of tuples (y, x_0, ..., x_N) where pts(*y) = pts(x_0) = ... pts(x_N) * Each block pops a pair out of the worklist, and performs the following logic: * a) lock variables y,x_0,...,x_N * b) decode and lock the points-to of x_0,...,x_N * c) merge all the variables that we were able to lock * d) unlock the merged variables * e) repeat a-d for all the variables we were not able to lock * Note that e) is not strictly necessary, but we would be missing some (maybe relevant) * equivalences that will eventually result in more work for the standard graph rules. */ __global__ void hcd() { __shared__ uint _counter_; /** * list of variables (x,...,x_N) such that all the variables in the set {pts(x),...pts(x_N)} * are pointer-equivalent. */ __shared__ uint _ptr_[HCD_TABLE_SIZE * 2]; /* * pointer to _ptr_ indicating where the current list starts */ __shared__ uint *_currPtr_; /** * pointer to _ptr_ indicating where the next list starts. * The reason why need of sublists within _ptr_ is because we might not have been able to lock * all the variables in _currPtr_, so everything that is pending (=needs to be processed in the * next iteration) is placed in the subarray pointed by _nextPtr_ */ __shared__ uint *_nextPtr_; /** * list of variables that are pointer equivalent (thus need to be merged) */ __shared__ uint _currVar_[HCD_DECODE_VECTOR_SIZE]; /** * list of variables that are pointer equivalent but could not be locked in the current iteration */ __shared__ uint *_nextVar_; __shared__ uint _currPtrSize_, _nextPtrSize_, _currVarSize_, _nextVarSize_; const uint threadIdInBlock = getThreadIdInBlock(); const uint threadsInBlock = getThreadsPerBlock(); const uint to = __numHcdIndex__; // first thread of the block picks next hcd pair to work on if (isFirstThreadOfBlock()) { _counter_ = atomicAdd(&__worklistIndex0__, 1); _nextVar_ = __nextVar__ + getBlockIdInGrid() * HCD_DECODE_VECTOR_SIZE; } __syncthreads(); while (_counter_ < to) { uint pair = __hcdIndex__[_counter_]; uint start = getFirst(pair); uint end = getSecond(pair); // move the (x0,...,x_N) sublist to shared memory for (int i = start + 1 + threadIdInBlock; i < end; i += threadsInBlock) { _ptr_[i - start - 1] = __hcdTable__[i]; } if (isFirstWarpOfBlock()) { _currPtrSize_ = end - start - 1; _currVar_[0] = __hcdTable__[start]; _currVarSize_ = 1; _currPtr_ = _ptr_; // we do not know how many variables we will not be able to lock, so unfortunately we have // use a statically fixed index _nextPtr_ = _ptr_ + HCD_TABLE_SIZE; } while (1) { _nextPtrSize_ = 0; _nextVarSize_ = 0; __syncthreads(); // lock variables in the current variable list (variables that belong to the points-to set // of x_I and could not be locked in a previous iteration) lockVars(_currVar_, _currVarSize_, _nextVar_, &_nextVarSize_); // lock variables in current pointer list, then decode their points-to sets and lock those too lockPtrs(_currPtr_, _currPtrSize_, _nextPtr_, &_nextPtrSize_, _currVar_, &_currVarSize_, _nextVar_, &_nextVarSize_); // unlock variables in pointer list if they are not in the variable list unlockPtrs(_currPtr_, _currPtrSize_); blockSort(_currVar_, _currVarSize_); // merge variable list! mergeCycle(_currVar_, _currVarSize_); // if there is any pending work -because variables or pointers could not be locked-, update // the corresponding information and retry if (!_nextPtrSize_ && (!_nextVarSize_ || (_currVarSize_ + _nextVarSize_ == 1))) { break; } if (isFirstWarpOfBlock() && _currVarSize_) { _currVar_[_nextVarSize_] = _currVar_[0]; // merge representative with pending } __syncthreads(); for (int i = threadIdInBlock; i < _nextVarSize_; i+= threadsInBlock) { _currVar_[i] = _nextVar_[i]; } if (isFirstWarpOfBlock()) { _currVarSize_ = _nextVarSize_ + (_currVarSize_ > 0); _currPtrSize_ = _nextPtrSize_; uint* tmp = _nextPtr_; _nextPtr_ = _currPtr_; _currPtr_ = tmp; } __syncthreads(); blockSort(_currVar_, _currVarSize_); } if (isFirstThreadOfBlock()) { _counter_ = atomicAdd(&__worklistIndex0__, 1); } __syncthreads(); } resetWorklistIndex(); } __global__ void updateInfo() { int inc = getThreadsPerGrid(); int init = getThreadIdInGrid(); uint to = __numVars__; // a) path compression for (int var = init; var < to; var += inc) { uint rep = getRepRec(var); // non-coalesced if (rep != var) { setRep(var, rep); //coalesced } uint diffPtsMask = __ballot_sync(0xffffffff,!isEmpty(rep, CURR_DIFF_PTS)); //non aligned __diffPtsMaskSet__(BASE_OF(var), WORD_OF(var), diffPtsMask); //aligned } syncAllThreads(); // b) update store rules to = __numStore__; for (int index = init; index < to; index += inc) { // the size of store has been rounded to a multiple of 32, so no out-of-bounds uint src = __storeConstraints__[index]; if (src != NIL) { src = getRep(src); uint val = (atomicCAS(__lock__ + src, UNLOCKED, LOCKED) == UNLOCKED) ? src : NIL; __storeConstraints__[index] = val; } } syncAllThreads(); // c) unlock for (int index = init; index < to; index += inc) { uint src = __storeConstraints__[index]; if (src != NIL) { unlock(getRep(src)); } } } __launch_bounds__ (DEF_THREADS_PER_BLOCK) __global__ void initialize() { uint to = __numVars__; uint headerSize = to * ELEMENT_WIDTH; if (isFirstThreadOfBlock()) { __ptsFreeList__ = headerSize; __currDiffPtsFreeList__ = CURR_DIFF_PTS_START - headerSize; __nextDiffPtsFreeList__ = NEXT_DIFF_PTS_START - headerSize; // after LOAD_INV, STORE and CURR_DIFF_PTS_INV header regions __otherFreeList__ = COPY_INV_START + headerSize * (LAST_DYNAMIC_REL - COPY_INV + 1); } __syncthreads(); int inc = mul32(getWarpsPerGrid()); int init = mul32(getWarpIdInGrid()); for (int var = init; var < to; var += inc) { unlock(var + threadIdx.x); setRep(var + threadIdx.x, var + threadIdx.x); for (int i = 0; i < WARP_SIZE; i++) { uint index = getHeadIndex(var + i, PTS); __graphSet__(index + threadIdx.x, NIL); index = getHeadIndex(var + i, NEXT_DIFF_PTS); __graphSet__(index + threadIdx.x, NIL); index = getHeadIndex(var + i, CURR_DIFF_PTS); __graphSet__(index + threadIdx.x, NIL); index = getHeadIndex(var + i, COPY_INV); __graphSet__(index + threadIdx.x, NIL); index = getHeadIndex(var + i, STORE); __graphSet__(index + threadIdx.x, NIL); index = getHeadIndex(var + i, LOAD_INV); __graphSet__(index + threadIdx.x, NIL); } } inc = mul960(getWarpsPerGrid()); init = mul960(getWarpIdInGrid()); for (int i = init; i < to; i += inc) { uint base = BASE_OF(i); __diffPtsMaskSet__(base, threadIdx.x, 0); } syncAllThreads(); to = __numInitialRep__; init = getThreadIdInGrid(); inc = getThreadsPerGrid(); // the offline phase of Hybrid Cycle Detection already detected some pointer equivalent variables. for (int i = init; i < to; i += inc) { setRep(__initialNonRep__[i], __initialRep__[i]); } } __global__ void computeCurrPtsHash() { const uint to = __numVars__; uint src = getAndIncrement(WARP_SIZE); while (src < to) { for (int i = 0; i < WARP_SIZE; i++) { if (!isEmpty(src + i, CURR_DIFF_PTS)) { uint hash = hashCode(getHeadIndex(src + i, CURR_DIFF_PTS)); uint next = getAndIncrement(&__numKeysCounter__, 1); __key__[next] = hash; __val__[next] = src + i; } } src = getAndIncrement(WARP_SIZE); } if (resetWorklistIndex()) { __numKeys__ = __numKeysCounter__; __numKeysCounter__ = 0; } } __global__ void findCurrPtsEquivalents() { __shared__ uint _sh_[WARPS_PER_BLOCK(UPDATE_THREADS_PER_BLOCK) * WARP_SIZE * 2]; uint* _key_ = &_sh_[threadIdx.y * WARP_SIZE * 2]; uint* _val_ = _key_ + WARP_SIZE; const uint to = __numKeys__; uint index = getAndIncrement(WARP_SIZE); while (index < to) { if (index + threadIdx.x < to) { _key_[threadIdx.x] = __key__[index + threadIdx.x]; _val_[threadIdx.x] = __val__[index + threadIdx.x]; } for (int i = 0; i < WARP_SIZE && index + i < to; i++) { uint var1 = _val_[i]; uint var1Head = getHeadIndex(var1, CURR_DIFF_PTS); uint j = _key_[i]; while (j < index + i) { uint var2 = __val__[j]; uint var2Head = getHeadIndex(var2, CURR_DIFF_PTS); if (equal(var1Head, var2Head)) { __currPtsHead__[var1] = var2Head; break; } j++; } if (j == index + i) { __currPtsHead__[var1] = var1Head; } } index = getAndIncrement(WARP_SIZE); } resetWorklistIndex(); } __host__ void checkKernelErrors(char *msg) { cudaError_t e; cudaThreadSynchronize(); if (cudaSuccess != (e = cudaGetLastError())) { printf("\n%s: %s\n", msg, cudaGetErrorString(e)); exit(-1); } } __host__ void checkErrors(uint rel) { #if CHECK_SPV uint error = 0; checkForErrors << <getBlocks(), THREADS_PER_BLOCK >> >(rel); checkKernelErrors("ERROR while checking for errors"); cudaSafeCall(cudaMemcpyFromSymbol(&error, __error__, uintSize, 0, D2H)); if (error) { exit(-1); } #endif } __host__ void checkAllErrors() { checkErrors(PTS); checkErrors(NEXT_DIFF_PTS); checkErrors(CURR_DIFF_PTS); checkErrors(COPY_INV); checkErrors(LOAD_INV); checkErrors(STORE); } __host__ void addTimeToRule(uint& counter, clock_t& startTime) { uint ellapsedTime = (int) (1000.0f * (clock() - startTime) / CLOCKS_PER_SEC); counter += ellapsedTime; startTime = clock(); } __host__ void printRule(const char* msg) { #if PRINT_RULES printf("%s", msg); #endif } template <typename Vector> __host__ void printVector(const Vector& v, uint size) { std::cout << "["; for (size_t i = 0; i < size; i++) { uint num = v[i]; if (num != NIL) { std::cout << num; if (i < size - 1) { std::cout << ", "; } } } std::cout << "]"; } __host__ void initializeEdges(uint* &constraintsName, uint &constraintNumber, uint rel) { dim3 dimInitialize(WARP_SIZE, getThreadsPerBlock(DEF_THREADS_PER_BLOCK) / WARP_SIZE); uint* constraints; uint numConstraints; cudaSafeCall(cudaMemcpyFromSymbol(&constraints, constraintsName, sizeof(uint*))); cudaSafeCall(cudaMemcpyFromSymbol(&numConstraints, constraintNumber, uintSize)); device_ptr<uint> src(constraints); device_vector<uint> dstIndex(numConstraints); sequence(dstIndex.begin(), dstIndex.begin() + numConstraints); uint numSrc = unique_by_key(src, src + numConstraints, dstIndex.begin()).first - src; addEdges<<<getBlocks() * 3, dimInitialize>>>(constraints, raw_pointer_cast(&dstIndex[0]), constraints + numConstraints, numSrc, rel); if (rel == STORE) { cudaSafeCall(cudaMemcpyToSymbol(__numStore__, &numSrc, uintSize)); } else { cudaFree(constraints); } checkKernelErrors("ERROR while adding initial edges"); } extern "C" void createGraph(const uint numObjectVars, const uint maxOffset) { setbuf(stdout, NULL); printf("[dev] Creating graph and masks out of constraints..."); const uint startTime = clock(); double startTime2 = rtclock(); dim3 dim(WARP_SIZE, getThreadsPerBlock(DEF_THREADS_PER_BLOCK)/ WARP_SIZE); /* no need for maximum_residency here, since kernel will fail to launch otherwise */ initialize<<<getBlocks(), dim>>>(); checkKernelErrors("ERROR at initialize"); initializeEdges(__ptsConstraints__, __numPtsConstraints__, NEXT_DIFF_PTS); initializeEdges(__copyConstraints__, __numCopyConstraints__, COPY_INV); initializeEdges(__loadConstraints__, __numLoadConstraints__, LOAD_INV); initializeEdges(__storeConstraints__, __numStoreConstraints__, STORE); // no need to add GEP_INV edges, there is only one per variable createOffsetMasks<<<getBlocks(), dim>>>(numObjectVars, maxOffset); checkKernelErrors("ERROR while creating the offset mask"); uint* size; cudaSafeCall(cudaMemcpyFromSymbol(&size, __size__, sizeof(uint*))); cudaFree(size); printf("OK.\n"); createTime = getEllapsedTime(startTime); createTime2 = rtclock() - startTime2; } struct neqAdapter : public thrust::unary_function<tuple<uint, uint>, uint>{ __host__ __device__ uint operator()(const tuple<uint, uint>& a) { return get<0>(a) != get<1>(a); } }; struct mulAdapter : public thrust::unary_function<tuple<uint, uint>, uint>{ __host__ __device__ uint operator()(const tuple<uint, uint>& a) { return get<0>(a) * get<1>(a); } }; __host__ void buildHashMap(device_vector<uint>& key, device_vector<uint>& val,const uint size) { sort_by_key(key.begin(), key.begin() + size, val.begin()); thrust::maximum<uint> uintMax; inclusive_scan( make_transform_iterator( make_zip_iterator(make_tuple( make_transform_iterator( make_zip_iterator(make_tuple(key.begin() + 1, key.begin())), neqAdapter()), counting_iterator<uint>(1))), mulAdapter()), make_transform_iterator( make_zip_iterator(make_tuple( make_transform_iterator( make_zip_iterator(make_tuple(key.begin() + size, key.begin() + size - 1)), neqAdapter()), counting_iterator<uint>(1))), mulAdapter()), key.begin() + 1, uintMax); key[0] = 0; } extern "C" uint andersen(uint numVars) { setbuf(stdout, NULL); printf("[dev] Solving: "); const uint startTime = clock(); const double startTime2 = rtclock(); uint iteration = 0; uint updatePtsTime = 0; uint hcdTime = 0; uint ptsEquivTime = 0; uint copyInvTime = 0; uint storeInvTime = 0; uint gepInvTime = 0; dim3 dim512(WARP_SIZE, getThreadsPerBlock(512) / WARP_SIZE); dim3 dimDefThreads(WARP_SIZE, getThreadsPerBlock(DEF_THREADS_PER_BLOCK) / WARP_SIZE); dim3 dimUpdate2(WARP_SIZE, getThreadsPerBlock(UPDATE_THREADS_PER_BLOCK) / WARP_SIZE); dim3 dimHcd(WARP_SIZE, getThreadsPerBlock(HCD_THREADS_PER_BLOCK) / WARP_SIZE); dim3 dimCopy(WARP_SIZE, getThreadsPerBlock(COPY_INV_THREADS_PER_BLOCK) / WARP_SIZE); dim3 dimStore(WARP_SIZE, getThreadsPerBlock(STORE_INV_THREADS_PER_BLOCK) / WARP_SIZE); dim3 dimGep(WARP_SIZE, getThreadsPerBlock(GEP_INV_THREADS_PER_BLOCK) / WARP_SIZE); device_vector<uint> key(MAX_HASH_SIZE); uint* ptr = raw_pointer_cast(&key[0]); cudaSafeCall(cudaMemcpyToSymbol(__key__, &ptr, sizeof(uint*))); device_vector<uint> keyAux(MAX_HASH_SIZE); ptr = raw_pointer_cast(&keyAux[0]); cudaSafeCall(cudaMemcpyToSymbol(__keyAux__, &ptr, sizeof(uint*))); device_vector<uint> val(MAX_HASH_SIZE); ptr = raw_pointer_cast(&val[0]); cudaSafeCall(cudaMemcpyToSymbol(__val__, &ptr, sizeof(uint*))); clock_t ruleTime = clock(); uint blocks = getBlocks(); // TODO: mega-hack to avoid race condition on 'gcc' input. uint hcdBlocks = getenv("GCC") ? 4 : blocks; /** * TODO (Jan'11) * * a) use pointers instead of integers for the indexes, which is possible because all the * inputs can be analyzed using a 4GB heap. Advantages: * a.1) when dereferencing an index, currently we assume that in reality is a delta with * respect to __edges__. Because of that, every access to an element becomes *(__edges__ + delta). * If we are using pointers, we could simply do *ptr. Note that __edges__ is in constant memory. * a.2.) we could use the malloc in the CUDA libraries. Malloc could potentially be used in two * places: OTHER and PTS edges. In practice, we currently keep the PTS edges together because they * contain the solution so we would restric malloc to allocating copy/load/store edges. Since * malloc returns a pointer, it would be compatible with the index-is-a-pointer system * * b) HCD is buggy when many blocks are used. This happens only for the gcc input, so the * temporal path (see "hcdBlocks" variable) is to set the limit of blocks to four. * * c) retrieve the amount of memory and use that as HEAP_SIZE. * * d) devise a better representation scheme st all the benchmarks fit in 3GB, so I can effectively * use an MSI GTX580 (=> much faster than the Tesla C2070 or Quadro 6000) for all the inputs. */ const int updateInfo_residency = maximum_residency(updateInfo, dim512.x * dim512.y * dim512.z, 0); uint ptsStartIndex; while (1) { //printf("\n\nIteration: %u\n", iteration); cudaSafeCall(cudaMemcpyFromSymbol(&ptsStartIndex, __ptsFreeList__, uintSize)); //printf("\tstart = %d.\n", ptsStartIndex); printRule(" updating pts..."); updatePtsInformation<<<blocks, dimUpdate2>>>(); checkKernelErrors("ERROR at update pts"); printRule("done\n"); addTimeToRule(updatePtsTime, ruleTime); bool done = true; cudaSafeCall(cudaMemcpyFromSymbol(&done, __done__, sizeof(bool))); if (done) { break; } // Ideally, we would use one stream to copy all the points-to edges discovered during the // last iteration (resident in the interval [CURR_DIFF_PTS_START, __currDiffPtsFreeList__]) // back to the host while the other stream computes the next iteration, computation that does // not modify the CURR_DIFF_PTS set. However, Thrust does not currently support streams, and // kernel invocations using the default stream add a implicit synchronization point [CUDA 4.1 // programming guide, 3.2.5.5.4] // If you do want to implement the simultaneous copy-kernel scheme, you can always modify // the Thrust source code or create your custom Thrust library with the stream hardcoded on it. // To avoid going that way, I chose to publish the version of the code that does pay a penalty // for the data transfer. printRule(" hcd..."); hcd<<<hcdBlocks, dimHcd>>>(); checkKernelErrors("ERROR at hcd rule"); updateInfo<<<updateInfo_residency * blocks, dim512>>>(); checkKernelErrors("ERROR while updating information after collapsing"); printRule("done\n"); addTimeToRule(hcdTime, ruleTime); printRule(" finding curr_pts equivalences..."); computeCurrPtsHash<<<3 * blocks, dimDefThreads>>>(); checkKernelErrors("ERROR at compute hash"); uint numKeys; cudaSafeCall(cudaMemcpyFromSymbol(&numKeys, __numKeys__, uintSize)); buildHashMap(key, val, numKeys); findCurrPtsEquivalents<<<3 * blocks, dimUpdate2>>>(); checkKernelErrors("ERROR in finding CURR_PTS equivalents"); printRule("done\n"); addTimeToRule(ptsEquivTime, ruleTime); printRule(" copy_inv and load_inv and store2storeInv..."); copyInv_loadInv_store2storeInv<<<blocks, dimCopy>>>(); checkKernelErrors("ERROR at copy_inv/load_inv/store2storeinv rule"); cudaSafeCall(cudaMemcpyFromSymbol(&numKeys, __numKeys__, uintSize)); assert(numKeys <= MAX_HASH_SIZE); sort_by_key(key.begin(), key.begin() + numKeys, val.begin()); sequence(keyAux.begin(), keyAux.begin() + numKeys); numKeys = unique_by_key(key.begin(), key.begin() + numKeys, keyAux.begin()).first - key.begin(); cudaSafeCall(cudaMemcpyToSymbol(__numKeys__, &numKeys, uintSize)); printRule("done\n"); addTimeToRule(copyInvTime, ruleTime); printRule(" store_inv..."); storeInv<<<blocks, dimStore>>>(); checkKernelErrors("ERROR at store_inv rule"); printRule("done\n"); addTimeToRule(storeInvTime, ruleTime); printRule(" gep_inv..."); gepInv<<<blocks, dimGep>>>(); checkKernelErrors("ERROR at gep_inv rule"); printRule("done\n"); addTimeToRule(gepInvTime, ruleTime); iteration++; printf("."); } printf("OK.\n"); printf("Iterations = %u.\n", iteration); // store the last index for the PTS elements uint ptsEndIndex; cudaSafeCall(cudaMemcpyFromSymbol(&ptsEndIndex, __ptsFreeList__, uintSize)); uint solveTime = getEllapsedTime(startTime); double solveTime2 = rtclock() - startTime2; printf("SOLVE runtime: %u ms.\n", createTime + solveTime); printf("SOLVE runtime2: %f ms.\n", (createTime2 + solveTime2) * 1000.0); printf(" create graph : %u ms.\n", createTime); printf(" rule solving : %u ms.\n", solveTime); printf(" updatePts : %u ms.\n", updatePtsTime); printf(" hcd : %u ms.\n", hcdTime); printf(" equiv : %u ms.\n", ptsEquivTime); printf(" cpLdSt2inv : %u ms.\n", copyInvTime); printf(" store : %u ms.\n", storeInvTime); printf(" gepInv : %u ms.\n", gepInvTime); //printf("amount of points-to info = %d.\n", ptsEndIndex - ptsStartIndex); // return ptsEndIndex - ptsStartIndex; return ptsEndIndex; }
the_stack