blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f03be7799f7be18acf18aebb517c87ae020769d7 | 27a9f38fe49e6fcaa64b376694998fc4635f770f | /MeshViewer/Geodesics/geodesic_constants_and_simple_functions.h | 54e217f4d011750201afa4b03e9ffbfc0f975557 | [] | no_license | zhangk430/MeshViewer | 37039929a7f38d2a5b418642ec7f6dfbeaeda44c | 379542fac17bb6d08c55518f4aa6d0af3cde0ce8 | refs/heads/master | 2021-01-10T21:58:35.725534 | 2015-10-19T11:44:48 | 2015-10-19T11:44:48 | 40,841,724 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,888 | h | //Copyright (C) 2008 Danil Kirsanov, MIT License
#ifndef GEODESIC_CONSTANTS_20071231
#define GEODESIC_CONSTANTS_20071231
// some constants and simple math functions
#include <assert.h>
#include <math.h>
#include <limits>
#include <fstream>
#ifdef min
#undef min
#endif
namespace geodesic{
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
//double const GEODESIC_INF = std::numeric_limits<double>::max();
double const GEODESIC_INF = 1e100;
//in order to avoid numerical problems with "infinitely small" intervals,
//we drop all the intervals smaller than SMALLEST_INTERVAL_RATIO*edge_length
double const SMALLEST_INTERVAL_RATIO = 1e-6;
//double const SMALL_EPSILON = 1e-10;
inline double cos_from_edges(double const a, //compute the cosine of the angle given the lengths of the edges
double const b,
double const c)
{
assert(a>1e-50);
assert(b>1e-50);
assert(c>1e-50);
double result = (b*b + c*c - a*a)/(2.0*b*c);
result = std::max(result, -1.0);
return std::min(result, 1.0);
}
inline double angle_from_edges(double const a, //compute the cosine of the angle given the lengths of the edges
double const b,
double const c)
{
return acos(cos_from_edges(a,b,c));
}
template<class Points, class Faces>
inline bool read_mesh_from_file(char* filename,
Points& points,
Faces& faces)
{
std::ifstream file(filename);
assert(file.is_open());
if(!file.is_open()) return false;
unsigned num_points;
file >> num_points;
assert(num_points>=3);
unsigned num_faces;
file >> num_faces;
points.resize(num_points*3);
for(typename Points::iterator i=points.begin(); i!=points.end(); ++i)
{
file >> *i;
}
faces.resize(num_faces*3);
for(typename Faces::iterator i=faces.begin(); i!=faces.end(); ++i)
{
file >> *i;
}
file.close();
return true;
}
} //geodesic
#endif //GEODESIC_CONSTANTS_20071231
| [
"zhangk430@gmail.com"
] | zhangk430@gmail.com |
e0b023bc9312814c2693c6ade00e2e191fade62b | 38570f997b3fe8a9f03e1863ab2bf8de7189b1f5 | /DBStatLIb/Column.cpp | 2f5b1d5f362d4b0dffd13add05c1337ddeb656f0 | [] | no_license | BRIGADA-B/DBStatLIb | 2a1827445c5eee3002c389c5254ff4c2946b38e7 | 87b7c5691bf482e7585b811233fd6f115e697216 | refs/heads/master | 2021-04-30T03:33:36.721761 | 2018-10-07T16:06:07 | 2018-10-07T16:06:07 | 121,517,009 | 1 | 2 | null | 2018-10-07T16:06:08 | 2018-02-14T14:00:18 | C++ | UTF-8 | C++ | false | false | 574 | cpp | #include "Column.h"
namespace dbmanager {
void Column::SetType(DBType dbtype)
{
dbtype_ = dbtype;
}
void Column::SetLength(int length)
{
length_ = length;
}
void Column::SetColumnName(const std::string & name)
{
columnName_ = name;
}
DBType Column::GetDbtype() const
{
return dbtype_;
}
int Column::GetLength() const
{
return length_;
}
std::string Column::GetColumnName() const
{
return columnName_;
}
bool Column::IsValueEmpty()
{
return isValueEmpty_;
}
void Column::SetIsValueEmpty(bool value)
{
isValueEmpty_ = value;
}
} | [
"sinimawath@gmail.com"
] | sinimawath@gmail.com |
2ae1bb1b407ad69451d3c0792a7a1768c1e6fca3 | dbbfaa251da8fe95e4e656a7c8b0950e077e9a51 | /Functions/pruningFunctions.cpp | c550ad70616556e5201d4ef914c0a4565583e942 | [] | no_license | sbianchin/TargetAnalysis | ac8c9a7a68906aa57e7f82dfadb8930fbe7985e5 | 11acff186a91b7d4fff4f8f66124316ba1aa9cbe | refs/heads/master | 2020-03-31T15:13:17.730536 | 2018-10-09T22:36:15 | 2018-10-09T22:36:15 | 146,795,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,807 | cpp | /*
* Created by Sebastien Bianchin on 2018-07-24 (s.bianchin@triumf.ca)
*/
#include <iostream>
#include <vector>
#include <math.h>
#include "TGraph.h"
#include "pruningFunctions.hpp"
#include "DetectorGeometry.hpp"
#include "CommonParameters.hpp"
namespace DG = DetectorGeometry;
namespace CP = CommonParameters;
vector<int> TOF1Neighbours(int TOF1_gap){
vector<int> TOF1_neighbours;
int TOF1_minus;
int TOF1_plus;
if(TOF1_gap-1 == 0){
TOF1_minus = 11;
TOF1_plus = 1;
}
else if(TOF1_gap-1==11){
TOF1_minus = 10;
TOF1_plus = 0;
}
else{
TOF1_minus = (TOF1_gap-1) - 1;
TOF1_plus = (TOF1_gap-1) + 1;
}
TOF1_neighbours.push_back(TOF1_minus);
TOF1_neighbours.push_back(TOF1_plus);
return TOF1_neighbours;
}
vector<double> PruningArea(double x1, double x2, double x3){
vector<double> vec_xx_pruning_area;
vec_xx_pruning_area.clear();
vec_xx_pruning_area.push_back(x1);
vec_xx_pruning_area.push_back(x2);
vec_xx_pruning_area.push_back(x3);
vec_xx_pruning_area.push_back(x1);
return vec_xx_pruning_area;
}
vector<int> TriangularPruning(int TOF1_Gap, double x_kstop, double y_kstop, vector<int> kaon_bars, vector<int> lepton_bars){
vector<int> vec_pruned_temp;
vector<int> vec_pruned;
vector<int> vec_temp;
///DETERMINE TOF1 NEIGHBOURS USING THE "TOF1Neighbours" FUNCTION
vector<int> vec_TOF1_neighbours;
vec_TOF1_neighbours = TOF1Neighbours(TOF1_Gap);
/// DETERMINE PRUNING AREA USING THE "PruningArea" FUNCTION
vector<double> vec_xx_pruning_area;
vector<double> vec_yy_pruning_area;
vec_xx_pruning_area = PruningArea(x_kstop, DG::TOF1_Xloc[vec_TOF1_neighbours[0]][2], DG::TOF1_Xloc[vec_TOF1_neighbours[1]][2]);
vec_yy_pruning_area = PruningArea(y_kstop, DG::TOF1_Yloc[vec_TOF1_neighbours[0]][2], DG::TOF1_Yloc[vec_TOF1_neighbours[1]][2]);
TGraph *gr_pruning_area;
gr_pruning_area = new TGraph(vec_xx_pruning_area.size(), &vec_xx_pruning_area[0], &vec_yy_pruning_area[0]);
if(kaon_bars.size()==0){
for(unsigned int i=0; i<lepton_bars.size(); i++){
vec_pruned.push_back(lepton_bars[i]);
}
}
else{
for(unsigned int i=0; i<lepton_bars.size(); i++){
if(gr_pruning_area->IsInside(DG::Xloc[lepton_bars[i]], DG::Yloc[lepton_bars[i]])==1){
vec_pruned_temp.push_back(lepton_bars[i]);
}
}
}
if(vec_pruned_temp.size() >= 2){
vec_pruned = vec_pruned_temp;
}
else{
if(kaon_bars.size() > 0){
for(unsigned int i=0; i<lepton_bars.size(); i++){
vec_pruned.push_back(lepton_bars[i]);
}
}
}
vector<double> vec_xx_pruned;
vector<double> vec_yy_pruned;
for(unsigned int i=0; i<vec_pruned.size(); i++){
vec_xx_pruned.push_back(DG::Xloc[vec_pruned[i]]);
vec_yy_pruned.push_back(DG::Yloc[vec_pruned[i]]);
}
return vec_pruned;
}
vector<double> PruningLine(int TOF1_Gap, double x_kstop, double y_kstop){
double x1, y1;
double x2, y2;
double b;
double a_out = -1;
double b_out = -1;
vector<double> vec_pruning_line;
vector<double> vec_pruning_line_coordinates;
///DEFINE MIN AND MAX
if(TOF1_Gap == 3 || TOF1_Gap == 9){
x1 = x_kstop;
y1 = -50;
x2 = x_kstop;
y2 = 50.;
a_out = 999.99;
b_out = 999.99;
}
else{
b = y_kstop - DG::TOF1_line_slope[TOF1_Gap-1] * x_kstop;
x1 = -50.;
y1 = DG::TOF1_line_slope[TOF1_Gap-1] * x1 + b;
x2 = 50.;
y2 = DG::TOF1_line_slope[TOF1_Gap-1] * x2 + b;
a_out = DG::TOF1_line_slope[TOF1_Gap-1];
b_out = b;
}
vec_pruning_line_coordinates.push_back(x1);
vec_pruning_line_coordinates.push_back(y1);
vec_pruning_line_coordinates.push_back(x2);
vec_pruning_line_coordinates.push_back(y2);
vec_pruning_line.push_back(x1);
vec_pruning_line.push_back(y1);
vec_pruning_line.push_back(x2);
vec_pruning_line.push_back(y2);
vec_pruning_line.push_back(a_out);
vec_pruning_line.push_back(b_out);
return vec_pruning_line;
}
vector<double> PruningLine2(int TOF1_Gap, double distance, double x_kstop, double y_kstop){
double d_angle = 999.99;
double ddx = 999.99;
double ddy = 999.99;
double a_out = 999.99;
double b_out = 999.99;
vector<double> vec_temp;
vector<double> vec_output;
if(TOF1_Gap==1) d_angle = 60. - 90.;
if(TOF1_Gap==2) d_angle = 30. - 90.;
if(TOF1_Gap==3) d_angle = 0. - 90.;
if(TOF1_Gap==4) d_angle = 330. - 90.;
if(TOF1_Gap==5) d_angle = 300. - 90.;
if(TOF1_Gap==6) d_angle = 270. - 90.;
if(TOF1_Gap==7) d_angle = 240. - 90.;
if(TOF1_Gap==8) d_angle = 210. - 90.;
if(TOF1_Gap==9) d_angle = 180. - 90.;
if(TOF1_Gap==10) d_angle = 150. - 90.;
if(TOF1_Gap==11) d_angle = 120. - 90.;
if(TOF1_Gap==12) d_angle = 90. - 90.;
ddx = distance * sin(d_angle * TMath::Pi() / 180.);
ddy = distance * cos(d_angle * TMath::Pi() / 180.);
vec_temp = PruningLine(TOF1_Gap, x_kstop, y_kstop);
a_out = ((vec_temp[1]-ddy) - (vec_temp[3]-ddy)) / ((vec_temp[0]+ddx) - (vec_temp[2]+ddx));
b_out = (vec_temp[1]-ddy) - a_out * (vec_temp[0]+ddx);
vec_output.push_back(vec_temp[0]+ddx);
vec_output.push_back(vec_temp[1]-ddy);
vec_output.push_back(vec_temp[2]+ddx);
vec_output.push_back(vec_temp[3]-ddy);
vec_output.push_back(a_out);
vec_output.push_back(b_out);
return vec_output;
}
vector<int> LinearPruning(int TOF1_Gap, double x_kstop, double y_kstop, vector<int> lepton_bars, double distance){
///Determine Pruning Line using "PruningLine" function
vector<double> vec_pruning_line; vec_pruning_line.clear();
vec_pruning_line = PruningLine(TOF1_Gap, x_kstop, y_kstop);
///Pruning the data
vector<int> vec_temp;
vector<int> vec_TBR;
vector<int> vec_pruned;
vec_temp = lepton_bars;
if(TOF1_Gap==1 || TOF1_Gap==2 || TOF1_Gap == 10 || TOF1_Gap == 11 || TOF1_Gap == 12){
for(unsigned int i=0; i<vec_temp.size(); i++){
if(DG::Yloc[vec_temp[i]] < DG::Xloc[vec_temp[i]] * vec_pruning_line[4] + vec_pruning_line[5]){
vec_TBR.push_back(vec_temp[i]);
}
}
}
else if(TOF1_Gap==4 || TOF1_Gap==5 || TOF1_Gap==6|| TOF1_Gap==7 || TOF1_Gap==8){
for(unsigned int i=0; i<vec_temp.size(); i++){
if(DG::Yloc[vec_temp[i]] > DG::Xloc[vec_temp[i]] * vec_pruning_line[4] + vec_pruning_line[5]){
vec_TBR.push_back(vec_temp[i]);
}
}
}
else if(TOF1_Gap == 3){
for(unsigned int i=0; i<vec_temp.size(); i++){
if(DG::Xloc[vec_temp[i]] < x_kstop){
vec_TBR.push_back(vec_temp[i]);
}
}
}
else if(TOF1_Gap == 9){
for(unsigned int i=0; i<vec_temp.size(); i++){
if(DG::Xloc[vec_temp[i]] > x_kstop){
vec_TBR.push_back(vec_temp[i]);
}
}
}
vector<double> vec_xx_temp;
vector<double> vec_yy_temp;
for(unsigned i=0; i<vec_TBR.size(); i++){
vec_temp.erase(find(vec_temp.begin(), vec_temp.end(), vec_TBR[i]));
}
for(unsigned j=0; j<vec_temp.size(); j++){
vec_xx_temp.push_back(DG::Xloc[vec_temp[j]]);
vec_yy_temp.push_back(DG::Yloc[vec_temp[j]]);
}
/// REPRUNING IF TOO FEW LEPTONS
vector<double> vec_line2;
if(vec_temp.size() <= CP::lepton_cluster_size){
vec_temp.clear();
vec_TBR.clear();
vec_line2 = PruningLine2(TOF1_Gap, distance, x_kstop, y_kstop);
vec_temp = lepton_bars;
if(TOF1_Gap==1 || TOF1_Gap==2 || TOF1_Gap==10 || TOF1_Gap==11 || TOF1_Gap==12){
for(unsigned int i=0; i<vec_temp.size(); i++){
if(DG::Yloc[vec_temp[i]] < DG::Xloc[vec_temp[i]] * vec_line2[4] + vec_line2[5]){
vec_TBR.push_back(vec_temp[i]);
}
}
}
else if(TOF1_Gap==4 || TOF1_Gap==5 || TOF1_Gap==6|| TOF1_Gap==7 || TOF1_Gap==8){
for(unsigned int i=0; i<vec_temp.size(); i++){
if(DG::Yloc[vec_temp[i]] > DG::Xloc[vec_temp[i]] * vec_line2[4] + vec_line2[5]){
vec_TBR.push_back(vec_temp[i]);
}
}
}
else if(TOF1_Gap==3){
for(unsigned int i=0; i<vec_temp.size(); i++){
if(DG::Xloc[vec_temp[i]] < vec_line2[0]){
vec_TBR.push_back(vec_temp[i]);
}
}
}
else if(TOF1_Gap==9){
for(unsigned int i=0; i<vec_temp.size(); i++){
if(DG::Xloc[vec_temp[i]] > vec_line2[0]){
vec_TBR.push_back(vec_temp[i]);
}
}
}
for(unsigned int i=0; i<vec_TBR.size(); i++){
vec_temp.erase(find(vec_temp.begin(), vec_temp.end(), vec_TBR[i]));
}
vec_xx_temp.clear();
vec_yy_temp.clear();
for(unsigned int j=0; j<vec_temp.size(); j++){
vec_xx_temp.push_back(DG::Xloc[vec_temp[j]]);
vec_yy_temp.push_back(DG::Yloc[vec_temp[j]]);
}
}
vector<double> vec_xx_pruned;
vector<double> vec_yy_pruned;
if(vec_temp.size() <= CP::lepton_cluster_size){
vec_pruned = lepton_bars;
}
else{
vec_pruned = vec_temp;
}
for(unsigned int i=0; i<vec_pruned.size(); i++){
vec_xx_pruned.push_back(DG::Xloc[vec_pruned[i]]);
vec_yy_pruned.push_back(DG::Yloc[vec_pruned[i]]);
}
vector<int> vec_pruned_output;
vec_pruned_output = vec_pruned;
return vec_pruned_output;
}
vector<double> pruningLines(int TOF1_Gap, double x_kstop, double y_kstop, vector<int> lepton_bars, double distance){
vector<double> vec_output;
///Determine Pruning Line using "PruningLine" function
vector<double> vec_pruning_line1; vec_pruning_line1.clear();
vector<double> vec_pruning_line2; vec_pruning_line2.clear();
vec_pruning_line1 = PruningLine(TOF1_Gap, x_kstop, y_kstop);
vec_output.push_back(vec_pruning_line1[0]);
vec_output.push_back(vec_pruning_line1[1]);
vec_output.push_back(vec_pruning_line1[2]);
vec_output.push_back(vec_pruning_line1[3]);
///Pruning the data
vector<int> vec_temp;
vector<int> vec_TBR;
vector<int> vec_pruned;
vec_temp = lepton_bars;
if(TOF1_Gap==1 || TOF1_Gap==2 || TOF1_Gap == 10 || TOF1_Gap == 11 || TOF1_Gap == 12){
for(unsigned int i=0; i<vec_temp.size(); i++){
if(DG::Yloc[vec_temp[i]] < DG::Xloc[vec_temp[i]] * vec_pruning_line1[4] + vec_pruning_line1[5]){
vec_TBR.push_back(vec_temp[i]);
}
}
}
else if(TOF1_Gap==4 || TOF1_Gap==5 || TOF1_Gap==6|| TOF1_Gap==7 || TOF1_Gap==8){
for(unsigned int i=0; i<vec_temp.size(); i++){
if(DG::Yloc[vec_temp[i]] > DG::Xloc[vec_temp[i]] * vec_pruning_line1[4] + vec_pruning_line1[5]){
vec_TBR.push_back(vec_temp[i]);
}
}
}
else if(TOF1_Gap == 3){
for(unsigned int i=0; i<vec_temp.size(); i++){
if(DG::Xloc[vec_temp[i]] < x_kstop){
vec_TBR.push_back(vec_temp[i]);
}
}
}
else if(TOF1_Gap == 9){
for(unsigned int i=0; i<vec_temp.size(); i++){
if(DG::Xloc[vec_temp[i]] > x_kstop){
vec_TBR.push_back(vec_temp[i]);
}
}
}
for(unsigned i=0; i<vec_TBR.size(); i++){
vec_temp.erase(find(vec_temp.begin(), vec_temp.end(), vec_TBR[i]));
}
/// REPRUNING IF TOO FEW LEPTONS
if(vec_temp.size() <= CP::lepton_cluster_size){
vec_pruning_line2 = PruningLine2(TOF1_Gap, distance, x_kstop, y_kstop);
vec_output.push_back(vec_pruning_line2[0]);
vec_output.push_back(vec_pruning_line2[1]);
vec_output.push_back(vec_pruning_line2[2]);
vec_output.push_back(vec_pruning_line2[3]);
}
return vec_output;
} | [
"s.bianchin@gmail.com"
] | s.bianchin@gmail.com |
3a8ab3602094b38d111f2fdc2003272d3c0c4544 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /base/pickle.cc | c8d784a3a8243e9ea586cbeec9b631ed62bbd04f | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 12,458 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/pickle.h"
#include <stdlib.h>
#include <algorithm> // for max()
#include <limits>
#include "base/bits.h"
#include "base/macros.h"
#include "base/numerics/safe_conversions.h"
#include "base/numerics/safe_math.h"
#include "build/build_config.h"
namespace base {
// static
const int Pickle::kPayloadUnit = 64;
static const size_t kCapacityReadOnly = static_cast<size_t>(-1);
PickleIterator::PickleIterator(const Pickle& pickle)
: payload_(pickle.payload()),
read_index_(0),
end_index_(pickle.payload_size()) {
}
template <typename Type>
inline bool PickleIterator::ReadBuiltinType(Type* result) {
const char* read_from = GetReadPointerAndAdvance<Type>();
if (!read_from)
return false;
if (sizeof(Type) > sizeof(uint32_t))
memcpy(result, read_from, sizeof(*result));
else
*result = *reinterpret_cast<const Type*>(read_from);
return true;
}
inline void PickleIterator::Advance(size_t size) {
size_t aligned_size = bits::Align(size, sizeof(uint32_t));
if (end_index_ - read_index_ < aligned_size) {
read_index_ = end_index_;
} else {
read_index_ += aligned_size;
}
}
template<typename Type>
inline const char* PickleIterator::GetReadPointerAndAdvance() {
if (sizeof(Type) > end_index_ - read_index_) {
read_index_ = end_index_;
return nullptr;
}
const char* current_read_ptr = payload_ + read_index_;
Advance(sizeof(Type));
return current_read_ptr;
}
const char* PickleIterator::GetReadPointerAndAdvance(int num_bytes) {
if (num_bytes < 0 ||
end_index_ - read_index_ < static_cast<size_t>(num_bytes)) {
read_index_ = end_index_;
return nullptr;
}
const char* current_read_ptr = payload_ + read_index_;
Advance(num_bytes);
return current_read_ptr;
}
inline const char* PickleIterator::GetReadPointerAndAdvance(
int num_elements,
size_t size_element) {
// Check for int32_t overflow.
int num_bytes;
if (!CheckMul(num_elements, size_element).AssignIfValid(&num_bytes))
return nullptr;
return GetReadPointerAndAdvance(num_bytes);
}
bool PickleIterator::ReadBool(bool* result) {
return ReadBuiltinType(result);
}
bool PickleIterator::ReadInt(int* result) {
return ReadBuiltinType(result);
}
bool PickleIterator::ReadLong(long* result) {
// Always read long as a 64-bit value to ensure compatibility between 32-bit
// and 64-bit processes.
int64_t result_int64 = 0;
if (!ReadBuiltinType(&result_int64))
return false;
// CHECK if the cast truncates the value so that we know to change this IPC
// parameter to use int64_t.
*result = base::checked_cast<long>(result_int64);
return true;
}
bool PickleIterator::ReadUInt16(uint16_t* result) {
return ReadBuiltinType(result);
}
bool PickleIterator::ReadUInt32(uint32_t* result) {
return ReadBuiltinType(result);
}
bool PickleIterator::ReadInt64(int64_t* result) {
return ReadBuiltinType(result);
}
bool PickleIterator::ReadUInt64(uint64_t* result) {
return ReadBuiltinType(result);
}
bool PickleIterator::ReadFloat(float* result) {
// crbug.com/315213
// The source data may not be properly aligned, and unaligned float reads
// cause SIGBUS on some ARM platforms, so force using memcpy to copy the data
// into the result.
const char* read_from = GetReadPointerAndAdvance<float>();
if (!read_from)
return false;
memcpy(result, read_from, sizeof(*result));
return true;
}
bool PickleIterator::ReadDouble(double* result) {
// crbug.com/315213
// The source data may not be properly aligned, and unaligned double reads
// cause SIGBUS on some ARM platforms, so force using memcpy to copy the data
// into the result.
const char* read_from = GetReadPointerAndAdvance<double>();
if (!read_from)
return false;
memcpy(result, read_from, sizeof(*result));
return true;
}
bool PickleIterator::ReadString(std::string* result) {
int len;
if (!ReadInt(&len))
return false;
const char* read_from = GetReadPointerAndAdvance(len);
if (!read_from)
return false;
result->assign(read_from, len);
return true;
}
bool PickleIterator::ReadStringPiece(StringPiece* result) {
int len;
if (!ReadInt(&len))
return false;
const char* read_from = GetReadPointerAndAdvance(len);
if (!read_from)
return false;
*result = StringPiece(read_from, len);
return true;
}
bool PickleIterator::ReadString16(string16* result) {
int len;
if (!ReadInt(&len))
return false;
const char* read_from = GetReadPointerAndAdvance(len, sizeof(char16));
if (!read_from)
return false;
result->assign(reinterpret_cast<const char16*>(read_from), len);
return true;
}
bool PickleIterator::ReadStringPiece16(StringPiece16* result) {
int len;
if (!ReadInt(&len))
return false;
const char* read_from = GetReadPointerAndAdvance(len, sizeof(char16));
if (!read_from)
return false;
*result = StringPiece16(reinterpret_cast<const char16*>(read_from), len);
return true;
}
bool PickleIterator::ReadData(const char** data, int* length) {
*length = 0;
*data = nullptr;
if (!ReadInt(length))
return false;
return ReadBytes(data, *length);
}
bool PickleIterator::ReadBytes(const char** data, int length) {
const char* read_from = GetReadPointerAndAdvance(length);
if (!read_from)
return false;
*data = read_from;
return true;
}
Pickle::Attachment::Attachment() = default;
Pickle::Attachment::~Attachment() = default;
// Payload is uint32_t aligned.
Pickle::Pickle()
: header_(nullptr),
header_size_(sizeof(Header)),
capacity_after_header_(0),
write_offset_(0) {
static_assert((Pickle::kPayloadUnit & (Pickle::kPayloadUnit - 1)) == 0,
"Pickle::kPayloadUnit must be a power of two");
Resize(kPayloadUnit);
header_->payload_size = 0;
}
Pickle::Pickle(int header_size)
: header_(nullptr),
header_size_(bits::Align(header_size, sizeof(uint32_t))),
capacity_after_header_(0),
write_offset_(0) {
DCHECK_GE(static_cast<size_t>(header_size), sizeof(Header));
DCHECK_LE(header_size, kPayloadUnit);
Resize(kPayloadUnit);
header_->payload_size = 0;
}
Pickle::Pickle(const char* data, size_t data_len)
: header_(reinterpret_cast<Header*>(const_cast<char*>(data))),
header_size_(0),
capacity_after_header_(kCapacityReadOnly),
write_offset_(0) {
if (data_len >= static_cast<int>(sizeof(Header)))
header_size_ = data_len - header_->payload_size;
if (header_size_ > static_cast<unsigned int>(data_len))
header_size_ = 0;
if (header_size_ != bits::Align(header_size_, sizeof(uint32_t)))
header_size_ = 0;
// If there is anything wrong with the data, we're not going to use it.
if (!header_size_)
header_ = nullptr;
}
Pickle::Pickle(const Pickle& other)
: header_(nullptr),
header_size_(other.header_size_),
capacity_after_header_(0),
write_offset_(other.write_offset_) {
Resize(other.header_->payload_size);
memcpy(header_, other.header_, header_size_ + other.header_->payload_size);
}
Pickle::~Pickle() {
if (capacity_after_header_ != kCapacityReadOnly)
free(header_);
}
Pickle& Pickle::operator=(const Pickle& other) {
if (this == &other) {
return *this;
}
if (capacity_after_header_ == kCapacityReadOnly) {
header_ = nullptr;
capacity_after_header_ = 0;
}
if (header_size_ != other.header_size_) {
free(header_);
header_ = nullptr;
header_size_ = other.header_size_;
}
Resize(other.header_->payload_size);
memcpy(header_, other.header_,
other.header_size_ + other.header_->payload_size);
write_offset_ = other.write_offset_;
return *this;
}
void Pickle::WriteString(const StringPiece& value) {
WriteInt(static_cast<int>(value.size()));
WriteBytes(value.data(), static_cast<int>(value.size()));
}
void Pickle::WriteString16(const StringPiece16& value) {
WriteInt(static_cast<int>(value.size()));
WriteBytes(value.data(), static_cast<int>(value.size()) * sizeof(char16));
}
void Pickle::WriteData(const char* data, int length) {
DCHECK_GE(length, 0);
WriteInt(length);
WriteBytes(data, length);
}
void Pickle::WriteBytes(const void* data, int length) {
WriteBytesCommon(data, length);
}
void Pickle::Reserve(size_t length) {
size_t data_len = bits::Align(length, sizeof(uint32_t));
DCHECK_GE(data_len, length);
#ifdef ARCH_CPU_64_BITS
DCHECK_LE(data_len, std::numeric_limits<uint32_t>::max());
#endif
DCHECK_LE(write_offset_, std::numeric_limits<uint32_t>::max() - data_len);
size_t new_size = write_offset_ + data_len;
if (new_size > capacity_after_header_)
Resize(capacity_after_header_ * 2 + new_size);
}
bool Pickle::WriteAttachment(scoped_refptr<Attachment> attachment) {
return false;
}
bool Pickle::ReadAttachment(base::PickleIterator* iter,
scoped_refptr<Attachment>* attachment) const {
return false;
}
bool Pickle::HasAttachments() const {
return false;
}
void Pickle::Resize(size_t new_capacity) {
CHECK_NE(capacity_after_header_, kCapacityReadOnly);
capacity_after_header_ = bits::Align(new_capacity, kPayloadUnit);
void* p = realloc(header_, GetTotalAllocatedSize());
CHECK(p);
header_ = reinterpret_cast<Header*>(p);
}
void* Pickle::ClaimBytes(size_t num_bytes) {
void* p = ClaimUninitializedBytesInternal(num_bytes);
CHECK(p);
memset(p, 0, num_bytes);
return p;
}
size_t Pickle::GetTotalAllocatedSize() const {
if (capacity_after_header_ == kCapacityReadOnly)
return 0;
return header_size_ + capacity_after_header_;
}
// static
const char* Pickle::FindNext(size_t header_size,
const char* start,
const char* end) {
size_t pickle_size = 0;
if (!PeekNext(header_size, start, end, &pickle_size))
return nullptr;
if (pickle_size > static_cast<size_t>(end - start))
return nullptr;
return start + pickle_size;
}
// static
bool Pickle::PeekNext(size_t header_size,
const char* start,
const char* end,
size_t* pickle_size) {
DCHECK_EQ(header_size, bits::Align(header_size, sizeof(uint32_t)));
DCHECK_GE(header_size, sizeof(Header));
DCHECK_LE(header_size, static_cast<size_t>(kPayloadUnit));
size_t length = static_cast<size_t>(end - start);
if (length < sizeof(Header))
return false;
const Header* hdr = reinterpret_cast<const Header*>(start);
if (length < header_size)
return false;
// If payload_size causes an overflow, we return maximum possible
// pickle size to indicate that.
*pickle_size = ClampAdd(header_size, hdr->payload_size);
return true;
}
template <size_t length> void Pickle::WriteBytesStatic(const void* data) {
WriteBytesCommon(data, length);
}
template void Pickle::WriteBytesStatic<2>(const void* data);
template void Pickle::WriteBytesStatic<4>(const void* data);
template void Pickle::WriteBytesStatic<8>(const void* data);
inline void* Pickle::ClaimUninitializedBytesInternal(size_t length) {
DCHECK_NE(kCapacityReadOnly, capacity_after_header_)
<< "oops: pickle is readonly";
size_t data_len = bits::Align(length, sizeof(uint32_t));
DCHECK_GE(data_len, length);
#ifdef ARCH_CPU_64_BITS
DCHECK_LE(data_len, std::numeric_limits<uint32_t>::max());
#endif
DCHECK_LE(write_offset_, std::numeric_limits<uint32_t>::max() - data_len);
size_t new_size = write_offset_ + data_len;
if (new_size > capacity_after_header_) {
size_t new_capacity = capacity_after_header_ * 2;
const size_t kPickleHeapAlign = 4096;
if (new_capacity > kPickleHeapAlign)
new_capacity = bits::Align(new_capacity, kPickleHeapAlign) - kPayloadUnit;
Resize(std::max(new_capacity, new_size));
}
char* write = mutable_payload() + write_offset_;
memset(write + length, 0, data_len - length); // Always initialize padding
header_->payload_size = static_cast<uint32_t>(new_size);
write_offset_ = new_size;
return write;
}
inline void Pickle::WriteBytesCommon(const void* data, size_t length) {
DCHECK_NE(kCapacityReadOnly, capacity_after_header_)
<< "oops: pickle is readonly";
MSAN_CHECK_MEM_IS_INITIALIZED(data, length);
void* write = ClaimUninitializedBytesInternal(length);
memcpy(write, data, length);
}
} // namespace base
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
dce90c8dafd5280b7660930e9345225abb2b5c93 | 8c0266134815a22c634553a57a855abad9832ce4 | /Geometry/dialog.cpp | dcbae8c1ecd62612f3a4d54daeb09c70f84df44b | [] | no_license | rxy-possible/QtExample | 9c9d00d89772d9dd1bcf17df670b8f7e8bfe820b | 771a7cfe15947c5cff96e175c78a32a81549df5c | refs/heads/master | 2023-08-28T06:35:36.064912 | 2021-09-25T12:42:46 | 2021-09-25T12:42:46 | 399,064,747 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,091 | cpp | #include "dialog.h"
#include <QDebug>
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("Geometry"));
xLabel = new QLabel(tr("x():"));
xValueLabel = new QLabel();
yLabel = new QLabel(tr("y():"));
yValueLabel = new QLabel();
FrmLabel = new QLabel(tr("Frame():"));
FrmValueLabel = new QLabel();
posLabel = new QLabel(tr("pos():"));
posValueLabel = new QLabel();
geoLabel = new QLabel(tr("geometry():"));
geoValueLabel = new QLabel();
widthLabel = new QLabel(tr("width():"));
widthValueLabel = new QLabel();
heightLabel = new QLabel(tr("height():"));
heightValueLabel = new QLabel();
rectLabel = new QLabel(tr("rect():"));
rectValueLabel = new QLabel();
sizeLabel = new QLabel(tr("size():"));
sizeValueLabel = new QLabel();
mainLayout = new QGridLayout(this);
mainLayout->addWidget(xLabel,0,0);
mainLayout->addWidget(xValueLabel,0,1);
mainLayout->addWidget(yLabel,1,0);
mainLayout->addWidget(yValueLabel,1,1);
mainLayout->addWidget(posLabel,2,0);
mainLayout->addWidget(posValueLabel,2,1);
mainLayout->addWidget(FrmLabel,3,0);
mainLayout->addWidget(FrmValueLabel,3,1);
mainLayout->addWidget(geoLabel,4,0);
mainLayout->addWidget(geoValueLabel,4,1);
mainLayout->addWidget(widthLabel,5,0);
mainLayout->addWidget(widthValueLabel,5,1);
mainLayout->addWidget(heightLabel,6,0);
mainLayout->addWidget(heightValueLabel,6,1);
mainLayout->addWidget(rectLabel,7,0);
mainLayout->addWidget(rectValueLabel,7,1);
mainLayout->addWidget(sizeLabel,8,0);
mainLayout->addWidget(sizeValueLabel,8,1);
updateLabel();
}
Dialog::~Dialog()
{
}
void Dialog::updateLabel()
{
QString xStr; //获得x()函数的结果并显示
xValueLabel->setText(xStr.setNum(x()));
QString yStr; //获得y()函数的结果并显示
yValueLabel->setText(yStr.setNum(y()));
QString frameStr; //获得frameGeometry()函数的结果并显示
QString tempStr1,tempStr2,tempStr3,tempStr4;
frameStr = tempStr1.setNum(frameGeometry().x())+","+
tempStr2.setNum(frameGeometry().y())+","+
tempStr3.setNum(frameGeometry().width())+","+
tempStr4.setNum(frameGeometry().height());
FrmValueLabel->setText(frameStr);
QString positionStr; //获得pos()函数的结果并显示
QString tempStr11,tempStr12;
positionStr = tempStr11.setNum(pos().x())+","+tempStr12.setNum(pos().y());
posValueLabel->setText(positionStr);
QString geoStr; //获得geometry()函数的结果并显示
QString tempStr21,tempStr22,tempStr23,tempStr24;
geoStr = tempStr21.setNum(geometry().x())+","+
tempStr22.setNum(geometry().y())+","+
tempStr23.setNum(geometry().width())+","+
tempStr24.setNum(geometry().height());
geoValueLabel->setText(geoStr);
QString wStr,hStr; //获得width(),height()函数的结果并显示
widthValueLabel->setText(wStr.setNum(width()));
heightValueLabel->setText(hStr.setNum(height()));
QString rectStr; //获得rect()函数的结果并显示
QString tempStr31,tempStr32,tempStr33,tempStr34;
rectStr = tempStr31.setNum(rect().x())+","+
tempStr32.setNum(rect().y())+","+
tempStr33.setNum(/*rect().width*/width())+","+
tempStr34.setNum(/*rect().height*/height());
rectValueLabel->setText(rectStr);
QString sizeStr; //获得size()函数的结果并显示
QString tempStr41,tempStr42;
sizeStr = tempStr41.setNum(size().width())+","+
tempStr42.setNum(size().height());
sizeValueLabel->setText(sizeStr);
}
void Dialog::moveEvent(QMoveEvent *)
{
qDebug()<<"-----";
updateLabel();
}
void Dialog::resizeEvent(QMoveEvent *)
{
qDebug()<<"+++++";
updateLabel();
}
| [
"rxy18645231697@163.com"
] | rxy18645231697@163.com |
88e3fc68fe749d161629b9b6d639529410186efb | 2ba94892764a44d9c07f0f549f79f9f9dc272151 | /Engine/Source/Runtime/IOS/IOSRuntimeSettings/Private/IOSRuntimeSettings.cpp | 835df106900fdf9aba21dbae438ac6ffc8e19ce6 | [
"BSD-2-Clause",
"LicenseRef-scancode-proprietary-license"
] | permissive | PopCap/GameIdea | 934769eeb91f9637f5bf205d88b13ff1fc9ae8fd | 201e1df50b2bc99afc079ce326aa0a44b178a391 | refs/heads/master | 2021-01-25T00:11:38.709772 | 2018-09-11T03:38:56 | 2018-09-11T03:38:56 | 37,818,708 | 0 | 0 | BSD-2-Clause | 2018-09-11T03:39:05 | 2015-06-21T17:36:44 | null | UTF-8 | C++ | false | false | 3,418 | cpp | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "IOSRuntimeSettingsPrivatePCH.h"
#include "IOSRuntimeSettings.h"
UIOSRuntimeSettings::UIOSRuntimeSettings(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
bEnableGameCenterSupport = true;
bEnableCloudKitSupport = false;
bSupportsPortraitOrientation = true;
BundleDisplayName = TEXT("UE4 Game");
BundleName = TEXT("MyUE4Game");
BundleIdentifier = TEXT("com.YourCompany.GameNameNoSpaces");
VersionInfo = TEXT("1.0.0");
FrameRateLock = EPowerUsageFrameRateLock::PUFRL_30;
bSupportsIPad = true;
bSupportsIPhone = true;
MinimumiOSVersion = EIOSVersion::IOS_61;
bDevForArmV7 = true;
bDevForArm64 = false;
bDevForArmV7S = false;
bShipForArmV7 = true;
bShipForArm64 = true;
bShipForArmV7S = false;
bUseRSync = true;
AdditionalPlistData = TEXT("");
}
#if WITH_EDITOR
void UIOSRuntimeSettings::PostEditChangeProperty(struct FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
// Ensure that at least one orientation is supported
if (!bSupportsPortraitOrientation && !bSupportsUpsideDownOrientation && !bSupportsLandscapeLeftOrientation && !bSupportsLandscapeRightOrientation)
{
bSupportsPortraitOrientation = true;
}
// Ensure that at least one API is supported
if (!bSupportsMetal && !bSupportsOpenGLES2 && !bSupportsMetalMRT)
{
bSupportsOpenGLES2 = true;
}
// Ensure that at least armv7 is selected for shipping and dev
if (!bDevForArmV7 && !bDevForArm64 && !bDevForArmV7S)
{
bDevForArmV7 = true;
}
if (!bShipForArmV7 && !bShipForArm64 && !bShipForArmV7S)
{
bShipForArmV7 = true;
}
}
void UIOSRuntimeSettings::PostInitProperties()
{
Super::PostInitProperties();
// We can have a look for potential keys
if (!RemoteServerName.IsEmpty() && !RSyncUsername.IsEmpty())
{
SSHPrivateKeyLocation = TEXT("");
const FString DefaultKeyFilename = TEXT("RemoteToolChainPrivate.key");
const FString RelativeFilePathLocation = FPaths::Combine(TEXT("SSHKeys"), *RemoteServerName, *RSyncUsername, *DefaultKeyFilename);
TCHAR Path[4096];
FPlatformMisc::GetEnvironmentVariable(TEXT("APPDATA"), Path, ARRAY_COUNT(Path));
TArray<FString> PossibleKeyLocations;
PossibleKeyLocations.Add(FPaths::Combine(*FPaths::GameDir(), TEXT("Build"), TEXT("NotForLicensees"), *RelativeFilePathLocation));
PossibleKeyLocations.Add(FPaths::Combine(*FPaths::GameDir(), TEXT("Build"), TEXT("NoRedist"), *RelativeFilePathLocation));
PossibleKeyLocations.Add(FPaths::Combine(*FPaths::GameDir(), TEXT("Build"), *RelativeFilePathLocation));
PossibleKeyLocations.Add(FPaths::Combine(*FPaths::EngineDir(), TEXT("Build"), TEXT("NotForLicensees"), *RelativeFilePathLocation));
PossibleKeyLocations.Add(FPaths::Combine(*FPaths::EngineDir(), TEXT("Build"), TEXT("NoRedist"), *RelativeFilePathLocation));
PossibleKeyLocations.Add(FPaths::Combine(*FPaths::EngineDir(), TEXT("Build"), *RelativeFilePathLocation));
PossibleKeyLocations.Add(FPaths::Combine(Path, TEXT("Unreal Engine"), TEXT("UnrealBuildTool"), *RelativeFilePathLocation));
// Find a potential path that we will use if the user hasn't overridden.
// For information purposes only
for (const FString& NextLocation : PossibleKeyLocations)
{
if (IFileManager::Get().FileSize(*NextLocation) > 0)
{
SSHPrivateKeyLocation = NextLocation;
break;
}
}
}
}
#endif
| [
"dkroell@acm.org"
] | dkroell@acm.org |
8fd4fdee8f18213aa960525f7a300843329f3830 | 8c331685de6f0e8725b326ca74c593a14b912fc9 | /src/Room.cpp | db3395c93b1e93d2074643d46771a7f73bf6622c | [] | no_license | magedavee/mygame | bbc60b2660227ab0e2d346e0ba7d46db9b5afbc9 | 22723a6eabe3e018a50da80d0e61b499dbab017a | refs/heads/master | 2021-06-06T13:50:03.840641 | 2018-11-18T23:33:48 | 2018-11-18T23:33:48 | 7,384,367 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | cpp | #include"Room.h"
#include <iostream>
#include <memory>
using namespace std;
REGISTER_ROOM(Room)
Room::Room()
{
//cerr<<"db. Room\n";
auto& factory=ObjectFactory::getInstance();
auto obj=factory.getPlugin("Magus");
s_obj= vector<shared_ptr<Object>>();
s_obj.push_back(obj);
}
void Room::update()
{
//cerr<<"db. Room update \n";
for(auto so: s_obj)
{
so->update();
}
}
void Room::render()
{
//cerr<<"db. Room render \n";
for(auto so: s_obj)
{
so->render();
}
}
| [
"dvdavee@email.wm.edu"
] | dvdavee@email.wm.edu |
756fba2236939eab74f0fccd5779501a4e417f01 | ce80d0da332985ea3aecd0381feae9ea65649a51 | /Contests/Google Code Jam/2014/Google Code Jam 2014/Google Code Jam - May 03/Problem B. New Lottery Game/lottery.cpp | dbfda478c398a5d5ae67e981e5fd6de1c1427cc0 | [] | no_license | EstebanFS/Competitive-Programming | e3c1e35073b5a713ba553c2c0548433f7c41aa3c | b154c833098086f69177883c4f38bf58f428186f | refs/heads/master | 2022-09-29T22:01:22.692452 | 2022-09-13T16:15:20 | 2022-09-13T16:15:20 | 10,339,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,039 | cpp | //Esteban Foronda Sierra
using namespace std;
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <sstream>
#include <fstream>
#include <cassert>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <set>
template <class T> string toStr(const T &x)
{ stringstream s; s << x; return s.str(); }
template <class T> int toInt(const T &x)
{ stringstream s; s << x; int r; s >> r; return r;}
#define D(x) cout << #x " is " << x << endl
#define ll long long
int main(){
int cases; cin >> cases;
for(int d=1; d<=cases; d++){
int a,b,k; cin >> a>>b>>k;
ll ans=0;
for(int i=0; i<max(a,b); i++){
for(int j=0; j<min(a,b); j++){
if((i&j)<k)ans++;
}
}
printf("Case #%d: %d\n",d, ans);
}
return 0;
}
| [
"estebanforondasierra@Estebans-MacBook-Air.local"
] | estebanforondasierra@Estebans-MacBook-Air.local |
82b9c1473b62cf415575604a2432523e7d4ce924 | 9af88fbc14af49918e326ac939bc435e6d4c9132 | /include/CachedElement.h | 9335f8c3e343116a2ddc11d2f936039da97038eb | [
"MIT"
] | permissive | bungle/CoolProp | a74cd8b12235101442058affc77fcca3e0bcb3f3 | 88fe0d3d895d74b515a21cb5079c265a88083bcf | refs/heads/master | 2023-03-20T02:15:27.792751 | 2015-02-02T10:00:14 | 2015-02-02T10:00:14 | 30,015,503 | 1 | 0 | null | 2015-01-29T10:32:58 | 2015-01-29T10:32:57 | null | UTF-8 | C++ | false | false | 1,725 | h | /*
* CachedElement.h
*
* Created on: 21 Dec 2013
* Author: jowr
*/
#ifndef CACHEDELEMENT_H_
#define CACHEDELEMENT_H_
#include "CoolPropTools.h"
#include "DataStructures.h"
namespace CoolProp {
/*!
A class that contains the magic to cache a value.
Includes an "=" assignment operator and casting to boolean
so you can do something like::
double CoolPropStateClassSI::d3phir_dTau3(double tau, double delta){
if (cache.d3phir_dTau3) {
return cache.d3phir_dTau3;
} else {
cache.d3phir_dTau3 = pFluid->d3phir_dTau3(tau,delta);
return cache.d3phir_dTau3;
}
};
*/
class CachedElement {
private:
bool is_cached;
long double value;
public:
/// Default constructor
CachedElement() {
this->clear();
};
/// Function to carry out the caching
void _do_cache(double value)
{
this->value = value;
this->is_cached = true;
}
/// Assignment operator - sets the value and sets the flag
void operator=(const double& value) {
_do_cache(value);
};
/// Cast to boolean, for checking if cached
operator bool() {return is_cached;};
/// Cast to double, for returning value
operator double() {
if (is_cached) {return static_cast<double>(value); }
else {
throw std::exception();
}
}
operator long double() {
if (is_cached) {return value; }
else {
throw std::exception();
}
}
/// Clear the flag and the value
void clear() {
is_cached = false;
this->value = _HUGE;
};
long double &pt(){
return this->value;
}
};
} /* namespace CoolProp */
#endif /* CACHEDELEMENT_H_ */
| [
"ian.h.bell@gmail.com"
] | ian.h.bell@gmail.com |
1bca2b21a3bc81fca592e2224e9bd4d2a16e3d31 | 642e07d31f88a5e68f83856d87774a4531733e51 | /Homework 4/ExtCalc/parser.hpp | 8d7c8f1a30a96b40d3e6c9bb7bc034ae5af0d56b | [] | no_license | draganjovic/Compiler-Design | 0a9160ac1b02c2cac2862540906bd74f04eee6d0 | 29ad3b2a022e49708f78ca8a90131387e7eeeaa7 | refs/heads/master | 2021-01-22T08:02:59.244446 | 2019-12-03T02:26:41 | 2019-12-03T02:26:41 | 81,871,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,132 | hpp | #ifndef PARSER_HPP
#define PARSER_HPP
#include "ast.hpp"
#include "prelude.hpp"
#include "evaluate.hpp"
#include "lexer.hpp"
#include <iostream>
#include <vector>
class Parser {
private:
std::vector<Token*> t;
std::vector<Token*>::iterator it;
context* cxt;
// return if there are no more tokens
bool Eof() { return it == t.end(); }
// returns the kind of current token
Token * LookAhead() { return (this->Eof() ? new punc_operator_token(Eof_tok) : *it); }
// returns the nth token past the current token
Token * LookAhead(int);
// consume
void Consume() { ++it; }
Token * Consume_();
// compare token kind, if current token has given kind, consume it
// otherwise no action.
bool MatchIf(Token_kind k) { return LookAhead()->kind == k; }
// compare token kind, if current token has given kind, consume it
// otherwise give error.
Token * Match(Token_kind k);
// require that token have given kind & consume
Token * Require(Token_kind k);
// Parse functions
expr * ParseExpr(); // expression
expr * ParseCond(); // conditional expression
expr * ParseOr(); // logical or expression
expr * ParseAnd(); // logical and expression
expr * ParseEqual(); // equality expression
expr * ParseOrdering(); // relational expression
expr * ParseAdd(); // additive expression
expr * ParseMult(); // multiplicative expression
expr * ParseUnary(); // unary expression
expr * ParsePrimary(); // boolean and integer literals
// Statements
Statement * ParseStmt(); // statement
Statement * ParseDecl_Stmt(); // declaration statement
Statement * ParseExpr_Stmt(); // expression statement
// Declarations
Declaration * ParseDecl();
Declaration * ParseVariable_Decl();
// Types
const type * ParseType();
public:
Statement * Parse() { return ParseStmt(); }
// Constructor
Parser(std::vector<Token*> _t, Context* _cxt) : t(_t), cxt(_cxt)
{
it = t.begin();
}
// destructor
~Parser() {}
}
| [
"noreply@github.com"
] | noreply@github.com |
87273963578ccaa4e30f35f21a534a1305f52700 | fe1b2ad7fd98fc2ccfa2b9aae75b77209a15f19c | /Primer/9_seq_containers/CP5_ex9_24.h | adba1b5a0c877d7539df63f97c0c4772baa55b62 | [] | no_license | timtingwei/cppd | 58519d403272b4ea35ab350bdfbd771d0ce1ccde | 8e0caf97fbed3a0c24ab21ca44f1750f376534f8 | refs/heads/master | 2018-10-10T14:58:09.419241 | 2018-07-06T22:13:06 | 2018-07-06T22:13:06 | 109,270,504 | 1 | 2 | null | 2018-07-14T13:22:38 | 2017-11-02T13:46:59 | C++ | UTF-8 | C++ | false | false | 661 | h | /* ------------------------------
Copyright <2018> [Tim Hu]
email: timtingwei@gmail.com
------------------------------
File:CP5_ex9_24.h
Date:Fri Jun 22 19:22:56 CST 2018
-----------------------------
*/
#ifndef CP5_ex9_24_h
#define CP5_ex9_24_h
#include <iostream>
#include <vector>
using std::vector;
void visit_firstEle(const vector<int> &iv) {
// iv.empty() = true;
// auto v1 = iv.at(0); // out of range
// auto v2 = iv[0]; // 运行时错误 Segmentation fault: 11
// auto v3 = *iv.cbegin(); // Segmentation fault: 11
auto v4 = iv.front(); // Segmentation fault: 11
// 看起来at比较安全
}
#endif
| [
"timtingwei@hotmail.com"
] | timtingwei@hotmail.com |
8f104f0cedb9b5f1705caadc3b5591ac94acfc21 | d3e6039edeeffa71e4c4c5ca2e4b07862ae00c8e | /算法习题/1831050171 王婧 3-1.cpp | a741c06e54d8dc4dff607d8cf2d1f4bccdab6fc0 | [] | no_license | WJ-0928/algorithm | 4cf031bf00e657e1752348746bb6943feaa5b14d | 99c752b21347b97014ac3a81c3f32198228dacca | refs/heads/master | 2022-12-29T10:14:06.415188 | 2020-10-15T08:21:53 | 2020-10-15T08:21:53 | 304,040,064 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,504 | cpp | /*
问题描述:
用2台处理机A和B处理n个作业。设第i个作业交给机器A处理时需要时间ai,若由机器B来处理,则需要时间bi。
由于各作业的特点和机器的性能关系,很可能对于某些i,有ai>bi,而对于某些j,j≠i,有aj>bj。
既不能将一个作业分开由2台机器处理,也没有一台机器能同时处理2个作业。
设计一个动态规划算法,使得这2台机器处理完这n个作业的时间最短(从任何一台机器开工到最后一台机器停工的总时间)。
研究一个实例:
(a1,a2,a3,a4,a5,a6)=(2,5,7,10,5,2);(b1,b2,b3,b4,b5,b6)=(3,8,4,11,3,4)。
对于给定的2台处理机A和B处理n个作业,找出一个最优调度方案,使2台机器处理完这n个作业的时间最短。
思路:
首先要注意每个作业仅需要处理一次就行,不需要被机器A和B各处理一遍
采用动态规划;
定义F[i][j]为:表示完成i个作业且机器A花费j时间的条件下机器B所花费时间的最小值,
那么F[i][j] = min{F[i - 1][j] + b[i], F[i - 1][j - a[i]]}。解释一下:
假设前i - 1件已经被处理了,那么第 i 件作业由谁来处理呢?
可以分两种情况:
1:由机器A处理i,则机器B的时间为 F[i - 1][j - a[i]];
2:由机器B处理i,则机器B的时间为 F[i - 1][j] + b[i];
特殊情况:如果j < a[i],则不可能由机器A来完成,此时F[i][j] = F[i - 1][j] + b[i];
最终F[i][j] 选择 1 和 2 中较小的一个,即F[i][j] = min{F[i - 1][j] + b[i], F[i - 1][j - a[i]]}。
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int time_a = 0;
int a[1024], b[1024];
void inPut()
{
cin>>n;
for (int i = 1; i <= n; ++i)
{
cin>>a[i];
time_a += a[i];
}
for (int i = 1; i <= n; ++i)
cin>>b[i];
}
int min_t = 0x3f3f3f;
int F[1024][1024];
void solve()
{
memset(F, 0, sizeof(F));
for (int i = 1; i <= n; ++i)
{
for (int j = 0; j <= time_a; ++j)
{
if (j > a[i])
{
F[i][j] = min(F[i - 1][j - a[i]], F[i - 1][j] + b[i]);
}
else
{
F[i][j] = F[i - 1][j] + b[i];
}
}
}
int temp;
for (int i = 0; i <= time_a; ++i)
{
temp = max(F[n][i], i);
if (min_t > temp)
min_t = temp;
}
}
int main()
{
inPut();
solve();
printf("%d\n", min_t);
}
*/
| [
"1031160332@qq.com"
] | 1031160332@qq.com |
3eb526c921aa3558f1c1a0a05bf950b7664b670e | 39b831ae89e0ba0627b2631482efcf4b3e5e67b4 | /include/trisycl.hpp | f3216f5bcf83aa22400ce85a0ad8120c867cac32 | [
"NCSA"
] | permissive | triSYCL/triSYCL | 082a6284ade929925fab02cbf9ac25e40c1a0ea1 | 929ec95fae74e1123734417a95577842a9911a6f | refs/heads/master | 2023-08-17T10:40:46.579696 | 2023-08-15T20:59:10 | 2023-08-15T20:59:10 | 18,943,874 | 437 | 74 | NOASSERTION | 2023-09-08T17:14:25 | 2014-04-19T15:19:51 | C++ | UTF-8 | C++ | false | false | 3,668 | hpp | #ifndef TRISYCL_TRISYCL_HPP
#define TRISYCL_TRISYCL_HPP
/** \file
\mainpage
This is the main triSYCL C++ header file to experiment with the
SYCL specification.
It declares everything into the \c ::trisycl namespace instead of
\c ::cl::sycl for SYCL 1.2.1 to express triSYCL specific extensions
and to be used in full or partially with other SYCL
implementations without naming conflict.
You can use CL/sycl.hpp or sycl.hpp headers instead to use this
implementation with the usual \c ::cl::sycl or \c ::sycl namespaces.
For more information about SYCL:
http://www.khronos.org/sycl/
For more information on this project and to access to the source of
this file, look at https://github.com/triSYCL/triSYCL
The Doxygen version of the implementation itself is in
http://trisycl.github.io/triSYCL/Doxygen/triSYCL/html and
http://trisycl.github.io/triSYCL/Doxygen/triSYCL/triSYCL-implementation-refman.pdf
Ronan at keryell dot FR
Copyright 2014--2015 Advanced Micro Devices, Inc.
Copyright 2015--2019 Xilinx, Inc.
This file is distributed under the University of Illinois Open Source
License. See LICENSE.TXT for details.
*/
/** Some global triSYCL configuration */
#include "trisycl/detail/global_config.hpp"
#include "trisycl/detail/default_classes.hpp"
/** Related to triSYCL/Intel SYCL compiler offload wrapping and binary/program
management
*/
#include "trisycl/detail/program_manager.hpp"
/* All the SYCL components, one per file */
#include "trisycl/access.hpp"
#include "trisycl/accessor.hpp"
#include "trisycl/allocator.hpp"
#include "trisycl/address_space.hpp"
#include "trisycl/buffer.hpp"
#include "trisycl/context.hpp"
#include "trisycl/device.hpp"
#include "trisycl/device_runtime.hpp"
#include "trisycl/device_selector.hpp"
#include "trisycl/error_handler.hpp"
#include "trisycl/event.hpp"
#include "trisycl/exception.hpp"
#include "trisycl/group.hpp"
#include "trisycl/half.hpp"
#include "trisycl/handler.hpp"
#include "trisycl/h_item.hpp"
#include "trisycl/id.hpp"
#include "trisycl/image.hpp"
#include "trisycl/item.hpp"
#include "trisycl/math.hpp"
#include "trisycl/nd_item.hpp"
#include "trisycl/nd_range.hpp"
#include "trisycl/opencl_types.hpp"
#include "trisycl/parallelism.hpp"
#include "trisycl/pipe.hpp"
#include "trisycl/pipe_reservation.hpp"
#include "trisycl/platform.hpp"
#include "trisycl/program.hpp"
#include "trisycl/queue.hpp"
#include "trisycl/range.hpp"
#include "trisycl/static_pipe.hpp"
#include "trisycl/vec.hpp"
// Some includes at the end to break some dependencies
#include "trisycl/device_selector/detail/device_selector_tail.hpp"
#include "trisycl/context/detail/context_tail.hpp"
#include "trisycl/device/detail/device_tail.hpp"
#include "trisycl/queue/detail/queue_tail.hpp"
#ifdef TRISYCL_OPENCL
#include "trisycl/device/detail/opencl_device_tail.hpp"
#endif
#include "trisycl/platform/detail/platform_tail.hpp"
#include "trisycl/platform/detail/host_platform_tail.hpp"
#ifdef TRISYCL_OPENCL
#include "trisycl/platform/detail/opencl_platform_tail.hpp"
#endif
// Some include files for Xilinx-specific features
/// For Xilinx FPGA
#include "trisycl/vendor/Xilinx/fpga.hpp"
/// For Xilinx ACAP
#include "trisycl/vendor/Xilinx/acap.hpp"
// Xilinx-specific extension for some graphics support
#include "trisycl/vendor/Xilinx/graphics.hpp"
// An extension about constexpr host introspection API
//#include "trisycl/extension/ce/platform.hpp"
/*
# Some Emacs stuff:
### Local Variables:
### ispell-local-dictionary: "american"
### eval: (flyspell-prog-mode)
### End:
*/
#endif // TRISYCL_TRISYCL_HPP
| [
"andrew.gozillon@yahoo.com"
] | andrew.gozillon@yahoo.com |
d0fccc068789e40eda0f7988ebaea4cdc8182d7f | c3898910aa11a29b780758aaffbd5b686e206ab9 | /include/Dunjun/ShaderProgram.hpp | 3b9ca7c61a5b405a8d578047c7804b6c49afc384 | [] | no_license | rsvargas/dunjun | 2aebfd6888649c08cdde090e48557c2834d60e9b | db3fcda6150b85f18c29be02c0fafe9a6543eb0f | refs/heads/master | 2021-01-10T04:28:59.184006 | 2016-01-18T01:52:55 | 2016-01-18T01:52:55 | 49,845,468 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,383 | hpp | #ifndef DUNJUN_SHADERPROGRAM_HPP
#define DUNJUN_SHADERPROGRAM_HPP
#include <Dunjun/Common.hpp>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <string>
namespace Dunjun
{
enum class ShaderType
{
Vertex,
Fragment,
};
class ShaderProgram
{
public:
ShaderProgram();
virtual ~ShaderProgram();
bool attachShaderFromFile(ShaderType type, const std::string& filename);
bool attachShaderFromMemory(ShaderType type, const std::string& shader);
void use() const;
bool isInUse() const;
void stopUsing() const;
bool link();
bool isLinked();
void bindAttribLocation(GLuint location, const GLchar* name);
GLint getAttribLocation(const GLchar* name);
GLint getUniformLocation(const GLchar* name);
void setUniform(const GLchar* name, float x);
void setUniform(const GLchar* name, float x, float y);
void setUniform(const GLchar* name, float x, float y, float z);
void setUniform(const GLchar* name, float x, float y, float z, float w);
void setUniform(const GLchar* name, int x);
void setUniform(const GLchar* name, unsigned int x);
void setUniform(const GLchar* name, bool x);
inline GLuint object() const { return m_object; }
inline const std::string& errorLog() const { return m_errorLog; }
private:
GLuint m_object;
bool m_linked;
std::string m_errorLog;
};
}
#endif | [
"rsvargas@gmail.com"
] | rsvargas@gmail.com |
b5d6fde7346b9048f140ae5d2b067d1683b59000 | b410ebaf2a74822b387825465625bde72c08f96e | /src/qt/poriun/txviewholder.cpp | e56d951dac4ca0f71350520c13175e633204465f | [
"MIT"
] | permissive | freelancerstudio/PoriunCoin | 925c94558dc03d2f8310bde14ab4768a923fd44b | 7d675d4d163702eb7072cafda52e7a58ef6e169c | refs/heads/master | 2023-04-21T20:56:55.178694 | 2021-05-06T08:46:03 | 2021-05-06T08:46:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,273 | cpp | //Copyright (c) 2019 The PIVX developers
//Copyright (c) 2020 The Poriun Coin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/poriun/txviewholder.h"
#include "qt/poriun/qtutils.h"
#include "transactiontablemodel.h"
#include <QModelIndex>
#define ADDRESS_SIZE 12
QWidget* TxViewHolder::createHolder(int pos)
{
if (!txRow) txRow = new TxRow();
txRow->init(isLightTheme);
return txRow;
}
void TxViewHolder::init(QWidget* holder,const QModelIndex &index, bool isHovered, bool isSelected) const
{
TxRow *txRow = static_cast<TxRow*>(holder);
txRow->updateStatus(isLightTheme, isHovered, isSelected);
QModelIndex rIndex = (filter) ? filter->mapToSource(index) : index;
QDateTime date = rIndex.data(TransactionTableModel::DateRole).toDateTime();
qint64 amount = rIndex.data(TransactionTableModel::AmountRole).toLongLong();
QString amountText = BitcoinUnits::formatWithUnit(nDisplayUnit, amount, true, BitcoinUnits::separatorAlways);
QModelIndex indexType = rIndex.sibling(rIndex.row(),TransactionTableModel::Type);
QString label = indexType.data(Qt::DisplayRole).toString();
int type = rIndex.data(TransactionTableModel::TypeRole).toInt();
if (type != TransactionRecord::Other) {
QString address = rIndex.data(Qt::DisplayRole).toString();
if (address.length() > 20) {
address = address.left(ADDRESS_SIZE) + "..." + address.right(ADDRESS_SIZE);
}
label += " " + address;
} else if (type == TransactionRecord::Other) {
label += rIndex.data(Qt::DisplayRole).toString();
}
int status = rIndex.data(TransactionTableModel::StatusRole).toInt();
bool isUnconfirmed = (status == TransactionStatus::Unconfirmed) || (status == TransactionStatus::Immature)
|| (status == TransactionStatus::Conflicted) || (status == TransactionStatus::NotAccepted);
txRow->setDate(date);
txRow->setLabel(label);
txRow->setAmount(amountText);
txRow->setType(isLightTheme, type, !isUnconfirmed);
}
QColor TxViewHolder::rectColor(bool isHovered, bool isSelected)
{
return getRowColor(isLightTheme, isHovered, isSelected);
}
| [
"hello@poriun.com"
] | hello@poriun.com |
91cf172c9a9369cf3e83939fe5d019e94c68687e | 5b702c0311e041b2a04763be9dd69bfccc4bfe5a | /Tic-tac-toe/Player.cpp | 6475f20b1126147b9b5dc958a4325aa1a39fde17 | [] | no_license | locpk/Programming-I | 77769c7ee814b448a465e5268593f20a38adb802 | 66b00001f889a0bb4c44fa2198a806e60e6280aa | refs/heads/master | 2021-01-01T16:06:56.475314 | 2014-11-06T20:44:32 | 2014-11-06T20:44:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,412 | cpp | #include "Functions.h"
using namespace System;
using std::cout;
using std::cin;
using std::endl;
void PlayerMoves(int* iPlayerRow, int* iPlayerCol, size_t* iOffsetx, size_t* iOffsety)
{
Console::SetCursorPosition(*iOffsetx, ++*iOffsety);
//Player move
cout << "Which Row? (0 >> 2)";
cin >> *iPlayerRow;
//row input validation
while (ValidatingMoves(iPlayerRow))
{
cin.clear();
cin.ignore(LLONG_MAX, '\n');
Console::SetCursorPosition(*iOffsetx, ++*iOffsety);
cout << "Wrong input!!! Again!\n";
Console::SetCursorPosition(*iOffsetx, ++*iOffsety);
cout << "Which Row? (0 >> 2)";
cin >> *iPlayerRow;
}
Console::SetCursorPosition(*iOffsetx, ++*iOffsety);
cout << "Which Col? (0 >> 2)";
cin >> *iPlayerCol;
while (ValidatingMoves(iPlayerCol))
{
cin.clear();
cin.ignore(LLONG_MAX, '\n');
Console::SetCursorPosition(*iOffsetx, ++*iOffsety);
cout << "Wrong input!!! Again!\n";
Console::SetCursorPosition(*iOffsetx, ++*iOffsety);
cout << "Which Col? (0 >> 2)";
cin >> *iPlayerCol;
}
}
bool ValidatingMoves(int* iInput)
{
return (0 != *iInput && 1 != *iInput && 2 != *iInput);
}
bool Quit()
{
char cFlag = '0';
cout << "Wanna Quit? (Y/N)";
while (!(cin >> cFlag))
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Wanna Quit? (Y/N)";
}
cFlag = tolower(cFlag);
if (cFlag == 'y')
return true;
else
return false;
} | [
"locpk123@gmail.com"
] | locpk123@gmail.com |
8d0f23225f23b62020e114d1741edd960d41595b | fe430f8018fcf94f51903601b76be95d6a70119c | /sortings.cpp | 04f6538734450feb96d559bfc424f1004f8c0422 | [] | no_license | madiken/Autocomplete | 2ff0d5b9ced972d2aa65e2a0bb22edb539fa4f48 | 2cdd23e9aa51fdcb713db89b91b1a6e41e8d3e5b | refs/heads/master | 2021-01-10T07:44:53.820310 | 2015-09-27T08:39:56 | 2015-09-27T08:39:56 | 43,225,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,165 | cpp | #include <iostream>
#include <vector>
#include <iostream> // std::cout
#include <algorithm> // std::shuffle
#include <array> // std::array
#include <random> // std::default_random_engine
#include <chrono> // std::chrono::system_clock
using namespace std;
void insertionsort(vector<int> &v ){
for (int i = 1; i < v.size(); i++){
int j = i;
while((v[j-1] > v[j]) && (j > 0)){
int tmp = v[j];
v[j] = v[j-1];
v[j-1] = tmp;
j--;
}
}
}
void mergesort(vector<int> &v, int lo, int hi){
if (lo>=hi) return;
const int me = (lo + hi)/2;
mergesort(v, lo, me);
mergesort(v, me + 1, hi);
const int size = me - lo + 1;
int ar[size];
for(int i = 0; i < size; i++){
ar[i] = v[lo + i];
}
int i = 0;
int j = me + 1;
int k = lo;
while(i < size && j <=hi){
if (ar[i] > v[j]){
v[k++] = v[j++];
}
else {
v[k++] = ar[i++];
}
}
while (i < size){
v[k++] = ar[i++];
}
while(j < size){
v[k++] = v[j++];
}
}
template<class T>
void shuffle(vector<T> &v){
for (int i = 0; i < v.size(); i++){
int j = rand() % (i + 1);
T tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
}
void mergesort(vector<int> &v){
mergesort(v, 0 , v.size()-1);
}
template<class T>
void partition(vector<T> & v, int lo, int hi){
if (lo>=hi) return;
T p = v[lo];
int i = lo + 1;
int j = hi;
while(i < j){
if (v[i] <= p) {
i++;
continue;
}
if (v[j] > p){
j--;
continue;
}
T tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
if (v[i] <=p){
v[lo] = v[i];
v[i] = p;
partition(v, lo, i-1);
partition(v, i+1, hi);
}
else {
v[lo] = v[i-1];
v[i-1] = p;
partition(v, lo, i-2);
partition(v, i, hi);
}
}
template<class T>
T select(vector<T> & v, const int k, int lo, int hi){
if (lo>=hi)
if (lo == k)
return k;
T p = v[lo];
int i = lo + 1;
int j = hi;
while(i < j){
if (v[i] <= p) {
i++;
continue;
}
if (v[j] > p){
j--;
continue;
}
T tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
if (v[i] <=p){
v[lo] = v[i];
v[i] = p;
return i;
}
else {
v[lo] = v[i-1];
v[i-1] = p;
return i -1;
}
}
template<class T>
T select(vector<T> &v, const int k){
int lo = 0;
int hi = v.size() - 1;
int i;
while (lo < hi){
i = select(v, k, lo, hi);
if (k < i)
hi = i-1;
else if (i < k)
lo = i+1;
else return v[k];
}
return v[k];
}
template<class T>
void quickSort(vector<T> &v){
if (v.size() == 0 || v.size() == 1) return;
//shuffle(v);
partition(v, 0, v.size()-1);
}
void test(vector<int> &v){
for (int i = 0; i < v.size(); i++){
v[i] =0;
}
}
class Point{
int x;
int y;
public :
Point(int xx, int yy):x(xx), y(yy){
}
bool operator>(const Point& that){
return x>that.x;
}
bool operator<(const Point& that){
return x<that.x;
}
bool operator>=(const Point& that){
return x>=that.x;
}
bool operator<=(const Point& that){
return x<=that.x;
}
friend ostream &operator<<(ostream& os,const Point& p);
};
ostream &operator<<(ostream& os,const Point& p){
os <<" (" << p.x << ", " << p.y << ") ";
return os;
}
int main(){
srand(time(NULL));
vector<int> v;
for (int i = 0; i <=9; i++){
v.push_back(i);
}
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
shuffle(v.begin(), v.end(), std::default_random_engine(time(NULL)));
for (int i = 0; i < v.size(); i++)
cout << v[i] << " " ;
cout << endl;
for (int i = 0; i < v.size(); i++){
cout << select(v, i) << endl;
}
for (int i = 0; i < v.size(); i++)
cout << v[i] << " " ;
cout << endl;
/* vector<Point> v;
int j = 0;
for(int i = 0; i < 10; i++){
v.push_back(Point(j, i));
if (i % 2 == 0) j++;
}
shuffle(v);
for (int i = 0; i < v.size(); i++)
cout << v[i] << " " ;
cout << endl;
quickSort(v);
for (int i = 0; i < v.size(); i++)
cout << v[i] << " " ;
cout << endl;
*/
cout << endl;
return 0;
}
| [
"jane.echo90@gmail.com"
] | jane.echo90@gmail.com |
f949605733802205f78174ce824718bdd413e941 | d5897c93caf298bc69f514b9bf021f3562d51af5 | /tensorflow/compiler/xla/service/spmd/spmd_partitioner_test.cc | 10551fd797b3e98234c557cca5794684bd039ff7 | [
"Apache-2.0",
"MIT",
"BSD-2-Clause"
] | permissive | l30831/tensorflow | c3856c2fddb837294d9c0286174d8a172aaf64b2 | ca4ad064f994eb4577ee5391ecd471745d81476c | refs/heads/master | 2023-04-04T16:14:23.643803 | 2021-04-13T01:09:42 | 2021-04-13T01:14:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 318,463 | cc | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/spmd/spmd_partitioner.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_instructions.h"
#include "tensorflow/compiler/xla/service/hlo_matchers.h"
#include "tensorflow/compiler/xla/service/hlo_parser.h"
#include "tensorflow/compiler/xla/service/hlo_pass_pipeline.h"
#include "tensorflow/compiler/xla/service/hlo_verifier.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
namespace xla {
namespace spmd {
namespace {
using ::testing::_;
using ::testing::AllOf;
namespace op = xla::testing::opcode_matchers;
class SpmdPartitioningTest : public HloTestBase {
public:
StatusOr<std::unique_ptr<HloModule>> PartitionComputation(
absl::string_view hlo_module, int64 num_devices,
bool conv_halo_exchange_always_on_lhs = true,
bool choose_faster_windowed_einsum = false) {
// Some tests (BackpropFilter convs) set this flag false to test two
// different paths of the implementation.
SpmdPartitionerOptions options;
options.conv_halo_exchange_always_on_lhs = conv_halo_exchange_always_on_lhs;
options.allow_module_signature_change = true;
options.choose_faster_windowed_einsum_over_mem =
choose_faster_windowed_einsum;
auto collective_ops_creator =
GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1);
// Do not use all-gather for pattern-matching purpose, as the partitioner
// might create reshape/transposes around it.
collective_ops_creator.create_cross_partition_all_gather = nullptr;
TF_ASSIGN_OR_RETURN(auto module, ParseAndReturnVerifiedModule(
hlo_module, GetModuleConfigForTest()));
HloPassPipeline pass("spmd-partitioning");
pass.AddPass<HloVerifier>(/*layout_sensitive=*/false,
/*allow_mixed_precision=*/false);
pass.AddPass<SpmdPartitioner>(num_devices, /*num_replicas=*/1, options,
collective_ops_creator);
pass.AddPass<HloVerifier>(/*layout_sensitive=*/false,
/*allow_mixed_precision=*/false);
TF_RETURN_IF_ERROR(pass.Run(module.get()).status());
return StatusOr<std::unique_ptr<HloModule>>(std::move(module));
}
};
TEST_F(SpmdPartitioningTest, InvalidSharding) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
token0 = token[] after-all(), sharding={maximal device=0}
infeed = (f32[8,2]{1,0}, token[]) infeed(token0),
sharding={{devices=[2,1]0,1}, {maximal device=0}}
ROOT infeed.data = f32[8,2]{1,0} get-tuple-element(infeed), index=0,
sharding={maximal device=0}
})";
auto module_status = PartitionComputation(hlo_string, /*num_devices=*/4);
EXPECT_FALSE(module_status.status().ok());
EXPECT_THAT(module_status.status().ToString(),
::testing::HasSubstr(
"only supports tile sharding that includes all partitions"));
}
TEST_F(SpmdPartitioningTest, SingleDeviceToReplicated) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%constant = s32[2,3]{1,0} constant({{1,1,1},{1,1,1}}),
sharding={maximal device=0}
ROOT %copy = s32[2,3]{1,0} copy(%constant), sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Copy(op::AllReduce(
op::Select(op::Broadcast(op::Compare()),
op::Constant(), op::Broadcast()))),
op::Shape("s32[2,3]")));
}
TEST_F(SpmdPartitioningTest, SingleDeviceToSingleDevice) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%constant = s32[2,3]{1,0} constant({{1,1,1},{1,1,1}}),
sharding={maximal device=0}
ROOT %copy = s32[2,3]{1,0} copy(%constant), sharding={maximal device=1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
HloInstruction* root = module->entry_computation()->root_instruction();
VLOG(1) << module->ToString();
EXPECT_THAT(root, op::Copy(AllOf(op::Copy(op::AllReduce(op::Select(
op::Broadcast(op::Compare()),
op::Constant(), op::Broadcast()))),
op::Shape("s32[2,3]"))));
}
TEST_F(SpmdPartitioningTest, SingleDeviceToTiled) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%constant = s32[2,3]{1,0} constant({{1,1,1},{1,1,1}}),
sharding={maximal device=0}
ROOT %copy = s32[2,3]{1,0} copy(%constant),
sharding={devices=[2,1]1,0}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
AllOf(
op::Copy(op::DynamicSlice(
op::AllReduce(op::Select(
op::Broadcast(op::Compare(op::PartitionId(), op::Constant())),
op::Constant(), op::Broadcast())),
op::Reshape(op::DynamicSlice(op::Constant(), op::PartitionId())),
op::Constant())),
op::Shape("s32[1,3]")));
}
TEST_F(SpmdPartitioningTest, TiledToReplicated) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%constant = s32[2,3]{1,0} constant({{1,1,1},{1,1,1}}),
sharding={devices=[2,1]0,1}
ROOT %copy = s32[2,3]{1,0} copy(%constant), sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
op::Copy(op::AllReduce(AllOf(
op::DynamicUpdateSlice(
op::Broadcast(), AllOf(op::Constant(), op::Shape("s32[1,3]")),
op::Reshape(op::DynamicSlice(op::Constant(), op::PartitionId())),
op::Constant()),
op::Shape("s32[2,3]")))));
}
TEST_F(SpmdPartitioningTest, TiledToSingleDevice) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%constant = s32[2,3]{1,0} constant({{1,1,1},{1,1,1}}),
sharding={devices=[2,1]0,1}
ROOT %copy = s32[2,3]{1,0} copy(%constant), sharding={maximal device=0}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
op::Copy(op::Copy(op::AllReduce(AllOf(
op::DynamicUpdateSlice(
op::Broadcast(), AllOf(op::Constant(), op::Shape("s32[1,3]")),
op::Reshape(op::DynamicSlice(op::Constant(), op::PartitionId())),
op::Constant()),
op::Shape("s32[2,3]"))))));
}
TEST_F(SpmdPartitioningTest, TiledToTiledEven) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param= s32[8,2]{1,0} parameter(0), sharding={devices=[2,1]0,1}
ROOT %copy = s32[8,2]{1,0} copy(%param), sharding={devices=[1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
AllOf(op::Copy(op::Reshape(op::Transpose(op::AllToAll(AllOf(
op::Reshape(op::Parameter()), op::Shape("s32[4,2,1]")))))),
op::Shape("s32[8,1]")));
}
TEST_F(SpmdPartitioningTest, TiledToTiledUneven) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param= f32[7,31,128]{2,1,0} parameter(0), sharding={devices=[1,2,1]0,1}
ROOT %copy = f32[7,31,128]{2,1,0} copy(%param), sharding={devices=[2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
AllOf(op::Copy(op::Slice(op::Reshape(AllOf(op::Transpose(op::AllToAll(
op::Reshape(AllOf(op::Pad(), op::Shape("f32[8,16,128]")))))))))));
}
TEST_F(SpmdPartitioningTest, GetTupleElementSwapDevice) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param.0 = (f32[2,3]{1,0}, u32[]) parameter(0),
sharding={{maximal device=1}, {maximal device=1}}
%gte.0 = f32[2,3]{1,0} get-tuple-element(%param.0), index=0,
sharding={maximal device=0}
%gte.1 = u32[] get-tuple-element(%param.0), index=1,
sharding={maximal device=0}
ROOT %tuple = (f32[2,3]{1,0}, u32[]) tuple(%gte.0, %gte.1),
sharding={{maximal device=0},{maximal device=0}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
ASSERT_THAT(root, op::Tuple());
EXPECT_THAT(root->operand(0),
op::Copy(op::AllReduce(op::Select(
op::Broadcast(op::Compare(op::PartitionId(), op::Constant())),
op::GetTupleElement(op::Parameter()), op::Broadcast()))));
EXPECT_THAT(root->operand(1),
op::Copy(op::AllReduce(op::Select(
op::Broadcast(op::Compare(op::PartitionId(), op::Constant())),
op::GetTupleElement(op::Parameter()), op::Broadcast()))));
}
TEST_F(SpmdPartitioningTest, GetTupleElementTiled) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
param.0 = (f32[2,3]{1,0}, u32[2,3]{1,0}) parameter(0),
sharding={{replicated}, {replicated}}
gte.0 = f32[2,3]{1,0} get-tuple-element(param.0), index=0,
sharding={devices=[2,1]0,1}
gte.1 = u32[2,3]{1,0} get-tuple-element(param.0), index=1,
sharding={devices=[2,1]0,1}
ROOT %tuple = (f32[2,3]{1,0}, u32[2,3]{1,0}) tuple(gte.0, gte.1),
sharding={{devices=[2,1]0,1},{devices=[2,1]0,1}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
ASSERT_THAT(root, op::Tuple());
auto offset =
op::Reshape(op::DynamicSlice(op::Constant(), op::PartitionId()));
EXPECT_THAT(root->operand(0),
op::DynamicSlice(op::GetTupleElement(op::Parameter()), offset,
op::Constant()));
EXPECT_THAT(root->operand(1),
op::DynamicSlice(op::GetTupleElement(op::Parameter()), offset,
op::Constant()));
}
TEST_F(SpmdPartitioningTest, TiledInfeed) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
token0 = token[] after-all(), sharding={maximal device=0}
infeed = (f32[8,2]{1,0}, token[]) infeed(token0),
sharding={{devices=[2,1]0,1}, {maximal device=0}}
ROOT infeed.data = f32[8,2]{1,0} get-tuple-element(infeed), index=0,
sharding={maximal device=0}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
op::Copy(op::AllReduce(op::DynamicUpdateSlice(
op::Broadcast(),
op::GetTupleElement(
AllOf(op::Infeed(), op::Shape("(f32[4,2]{1,0}, token[])"))),
op::Reshape(op::DynamicSlice(op::Constant(), op::PartitionId())),
op::Constant()))));
}
TEST_F(SpmdPartitioningTest, UnevenTiledInfeed) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
token0 = token[] after-all(), sharding={maximal device=0}
infeed = (f32[9,2]{1,0}, token[]) infeed(token0),
sharding={{devices=[2,1]0,1}, {maximal device=0}}
ROOT infeed.data = f32[9,2]{1,0} get-tuple-element(infeed), index=0,
sharding={devices=[2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root, AllOf(op::Shape("f32[5,2]"), op::GetTupleElement(op::Conditional(
op::Convert(op::PartitionId()),
op::AfterAll(), op::AfterAll()))));
EXPECT_THAT(
root->operand(0)->called_computations()[0]->root_instruction(),
AllOf(op::Shape("(f32[5,2], token[])"), op::Infeed(op::Parameter())));
auto second_infeed =
AllOf(op::Shape("(f32[4,2], token[])"), op::Infeed(op::Parameter()));
EXPECT_THAT(root->operand(0)->called_computations()[1]->root_instruction(),
AllOf(op::Shape("(f32[5,2], token[])"),
op::Tuple(op::Pad(op::GetTupleElement(second_infeed),
op::Constant()),
op::GetTupleElement(second_infeed))));
}
TEST_F(SpmdPartitioningTest, UnevenTiledTupleInfeed) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
token0 = token[] after-all(), sharding={maximal device=0}
infeed = ((f32[9,2]{1,0}, f32[2]{0}), token[]) infeed(token0),
sharding={{devices=[2,1]0,1}, {replicated}, {maximal device=0}}
ROOT infeed.data = (f32[9,2]{1,0}, f32[2]{0}) get-tuple-element(infeed),
index=0, sharding={{devices=[2,1]0,1}, {replicated}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("(f32[5,2], f32[2])"),
op::GetTupleElement(op::Conditional(
op::Convert(op::PartitionId()), op::AfterAll(),
op::AfterAll()))));
EXPECT_THAT(root->operand(0)->called_computations()[0]->root_instruction(),
AllOf(op::Shape("((f32[5,2], f32[2]), token[])"),
op::Infeed(op::Parameter())));
auto second_infeed = AllOf(op::Shape("((f32[4,2], f32[2]), token[])"),
op::Infeed(op::Parameter()));
EXPECT_THAT(
root->operand(0)->called_computations()[1]->root_instruction(),
AllOf(op::Shape("((f32[5,2], f32[2]), token[])"),
op::Tuple(op::Tuple(op::Pad(op::GetTupleElement(
op::GetTupleElement(second_infeed)),
op::Constant()),
op::GetTupleElement(
op::GetTupleElement(second_infeed))),
op::GetTupleElement(second_infeed))));
}
TEST_F(SpmdPartitioningTest, MixedTupleInfeed) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
token0 = token[] after-all(), sharding={maximal device=0}
infeed = ((f32[9,2]{1,0}, f32[2]{0}), token[]) infeed(token0),
sharding={{maximal device=0}, {maximal device=1}, {maximal device=0}}
ROOT infeed.data = (f32[9,2]{1,0}, f32[2]{0}) get-tuple-element(infeed),
index=0, sharding={{maximal device=0}, {maximal device=1}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("(f32[9,2], f32[2])"),
op::GetTupleElement(op::Conditional(
op::Convert(op::PartitionId()), op::AfterAll(),
op::AfterAll()))));
auto first_infeed = AllOf(op::Shape("((f32[9,2], ()), token[])"),
op::Infeed(op::Parameter()));
EXPECT_THAT(root->operand(0)->called_computations()[0]->root_instruction(),
AllOf(op::Shape("((f32[9,2], f32[2]), token[])"),
op::Tuple(op::Tuple(op::GetTupleElement(
op::GetTupleElement(first_infeed)),
op::Broadcast(op::Constant())),
op::GetTupleElement(first_infeed))));
auto second_infeed =
AllOf(op::Shape("(((), f32[2]), token[])"), op::Infeed(op::Parameter()));
EXPECT_THAT(root->operand(0)->called_computations()[1]->root_instruction(),
AllOf(op::Shape("((f32[9,2], f32[2]), token[])"),
op::Tuple(op::Tuple(op::Broadcast(op::Constant()),
op::GetTupleElement(op::GetTupleElement(
second_infeed))),
op::GetTupleElement(second_infeed))));
}
TEST_F(SpmdPartitioningTest, TiledToReplicatedReduce) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
constant = f32[3,3]{1,0} constant({{1,1,1},{1,1,1},{1,1,1}}),
sharding={devices=[2,1]0,1}
constant.1 = f32[] constant(0), sharding={replicated}
ROOT reduce = f32[] reduce(constant, constant.1), dimensions={0,1},
to_apply=sum, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
op::AllReduce(op::Reduce(
op::Select(
op::Compare(op::Add(op::Iota(), op::Broadcast(op::Reshape())),
op::Broadcast(op::Constant())),
AllOf(op::Shape("f32[2,3]{1,0}"),
op::DynamicSlice(op::Pad(op::Constant(), op::Constant()),
op::Reshape(), op::Constant())),
op::Broadcast(op::Constant())),
op::Constant())));
}
TEST_F(SpmdPartitioningTest, TiledElementwise) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
constant = f32[3,3]{1,0} constant({{1,1,1},{1,1,1},{1,1,1}}),
sharding={devices=[2,1]0,1}
constant.1 = f32[3,3]{1,0} constant({{2,2,2},{2,2,2},{2,2,2}}),
sharding={replicated}
multiply = f32[3,3]{1,0} multiply(constant, constant.1),
sharding={devices=[2,1]0,1}
ROOT add = f32[3,3]{1,0} add(multiply, constant.1),
sharding={devices=[2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
AllOf(
op::Shape("f32[2,3]{1,0}"),
op::Add(op::Multiply(
op::DynamicSlice(op::Pad(op::Constant(), op::Constant()),
op::Reshape(), op::Constant()),
op::DynamicSlice(op::Pad(op::Constant(), op::Constant()),
op::Reshape(), op::Constant())),
op::DynamicSlice(op::Pad(op::Constant(), op::Constant()),
op::Reshape(), op::Constant()))));
}
TEST_F(SpmdPartitioningTest, TiledAllReduce) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
parameter = f32[3,3]{1,0} parameter(0), sharding={devices=[2,1]0,1}
ROOT all-reduce = f32[3,3]{1,0} all-reduce(parameter), to_apply=sum,
replica_groups={}, sharding={devices=[2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root, AllOf(op::Shape("f32[2,3]{1,0}"), op::AllReduce(op::Parameter(0))));
}
TEST_F(SpmdPartitioningTest, BroadcastOnlyNewDimsSharded) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
constant = f32[4,3]{1,0} constant({{1,1,1},{1,1,1},{1,1,1},{1,1,1}}),
sharding={replicated}
ROOT broadcast = f32[3,4,3]{2,1,0} broadcast(constant), dimensions={1,2},
sharding={devices=[2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[2,4,3]{2,1,0}"),
op::Broadcast(op::Constant())));
}
TEST_F(SpmdPartitioningTest, BroadcastOnlyOldDimsSharded) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
constant = f32[4,3]{1,0} constant({{1,1,1},{1,1,1},{1,1,1},{1,1,1}}),
sharding={replicated}
ROOT broadcast = f32[4,4,3]{2,1,0} broadcast(constant), dimensions={1,2},
sharding={devices=[1,2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[4,2,3]{2,1,0}"),
op::Broadcast(op::DynamicSlice(
op::Constant(), op::Reshape(), op::Constant()))));
}
TEST_F(SpmdPartitioningTest, BroadcastBothOldAndNewDimsSharded) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
constant = f32[4,3]{1,0} constant({{1,1,1},{1,1,1},{1,1,1},{1,1,1}}),
sharding={replicated}
ROOT broadcast = f32[4,4,3]{2,1,0} broadcast(constant), dimensions={1,2},
sharding={devices=[2,2,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
AllOf(op::Shape("f32[2,2,3]{2,1,0}"),
op::Broadcast(AllOf(op::Shape("f32[2,3]{1,0}"),
op::DynamicSlice(op::Constant(), op::Reshape(),
op::Constant())))));
}
TEST_F(SpmdPartitioningTest,
BroadcastBothOldAndNewDimsShardedPartiallySharded) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
param = f32[4,3] parameter(0),
sharding={devices=[1,2,4]0,1,4,5,2,3,6,7 last_tile_dim_replicate}
ROOT broadcast = f32[4,4,3] broadcast(param), dimensions={1,2},
sharding={devices=[2,1,2,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
AllOf(op::Shape("f32[2,4,2]"),
op::Broadcast(AllOf(op::Shape("f32[4,2]"), op::Parameter(0)))));
}
TEST_F(SpmdPartitioningTest,
ConvWithParallelDimAndNonParallelSpatialDimPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,12,12,24,32] parameter(0)
%lhs.copy = f32[32,12,12,24,32] copy(%lhs),
sharding={devices=[2,2,1,1,1]0,1,2,3}
%rhs = f32[32,6,6,16,32] parameter(1)
%rhs.copy = f32[32,6,6,16,32] copy(%rhs),
sharding={devices=[2,2,1,1,1]0,1,2,3}
ROOT %conv = f32[32,7,7,24,16] convolution(%lhs.copy, %rhs.copy),
dim_labels=012bf_012oi->012bf,
window={size=32x6x6 stride=31x1x1 lhs_dilate=32x1x1},
sharding={devices=[2,2,1,1,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(),
op::Reshape(), op::Constant(),
op::Constant(), op::Constant())),
op::Shape("f32[16,6,12,24,32]"));
auto rhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(),
op::Reshape(), op::Constant(),
op::Constant(), op::Constant())),
op::Shape("f32[16,3,6,16,32]"));
auto resharded_rhs =
AllOf(op::Shape("f32[16,6,6,16,32]"),
op::AllReduce(op::DynamicUpdateSlice(
op::Broadcast(), rhs, op::Constant(), op::Reshape(),
op::Constant(), op::Constant(), op::Constant())));
auto left_halo = AllOf(op::CollectivePermute(op::Slice(lhs)),
op::Shape("f32[16,2,12,24,32]"));
auto right_halo = AllOf(op::CollectivePermute(op::Slice(lhs)),
op::Shape("f32[16,3,12,24,32]"));
EXPECT_THAT(
root,
AllOf(op::Convolution(
op::Select(op::Compare(),
op::DynamicSlice(
op::Concatenate(left_halo, lhs, right_halo),
op::Constant(), op::Add(), op::Constant(),
op::Constant(), op::Constant()),
op::Broadcast()),
resharded_rhs),
op::Shape("f32[16,4,7,24,16]")));
}
TEST_F(SpmdPartitioningTest, BroadcastPropagateTiledSharding) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
constant = f32[4,3]{1,0} constant({{1,1,1},{1,4,1},{1,3,1},{1,2,1}}),
sharding={devices=[2,1]0,1}
ROOT broadcast = f32[4,4,3]{2,1,0} broadcast(constant), dimensions={1,2},
sharding={devices=[1,2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[4,2,3]{2,1,0}"),
op::Broadcast(op::DynamicSlice(
op::Constant(), op::Reshape(), op::Constant()))));
}
TEST_F(SpmdPartitioningTest, OutfeedSingleDevice) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
token.0 = token[] after-all()
data = f32[1024]{0} parameter(0), sharding={maximal device=0}
outfeed = token[] outfeed(data, token.0), sharding={maximal device=0}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("token[]"),
op::Conditional(
op::Compare(op::PartitionId(), op::Constant()),
op::Tuple(op::Parameter(0), op::AfterAll()),
op::Tuple(op::Parameter(0), op::AfterAll()))));
HloInstruction* root_b0 = root->branch_computation(0)->root_instruction();
EXPECT_THAT(root_b0,
AllOf(op::Shape("token[]"),
op::Outfeed(op::GetTupleElement(op::Parameter(), 0),
op::GetTupleElement(op::Parameter(), 1))));
HloInstruction* root_b1 = root->branch_computation(1)->root_instruction();
EXPECT_THAT(root_b1, AllOf(op::Shape("token[]"), op::AfterAll()));
}
TEST_F(SpmdPartitioningTest, OutfeedEvenlyTiled) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
token.0 = token[] after-all()
data = f32[1024]{0} parameter(0), sharding={devices=[2]0,1}
ROOT outfeed = token[] outfeed(data, token.0), sharding={devices=[2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("token[]"),
op::Outfeed(op::Parameter(), op::AfterAll())));
}
TEST_F(SpmdPartitioningTest, OutfeedTupleEvenlyTiled) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
token.0 = token[] after-all()
data = (f32[1024,2]{1,0}, f32[2]{0}) parameter(0), sharding={{devices=[2,1]0,1},
{devices=[2]0,1}}
ROOT outfeed = token[] outfeed(data, token.0),
outfeed_shape=(f32[1024,2]{0,1}, f32[2]{0}), sharding={{devices=[2,1]0,1},
{devices=[2]0,1}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("token[]"),
op::Outfeed(op::Parameter(), op::AfterAll())));
auto expected_layout0 = LayoutUtil::MakeLayout({0, 1});
auto expected_layout1 = LayoutUtil::MakeLayout({0});
EXPECT_TRUE(LayoutUtil::Equal(root->outfeed_shape().tuple_shapes(0).layout(),
expected_layout0));
EXPECT_TRUE(LayoutUtil::Equal(root->outfeed_shape().tuple_shapes(1).layout(),
expected_layout1));
}
TEST_F(SpmdPartitioningTest, OutfeedReplicated) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
token.0 = token[] after-all()
data = (f32[1024,2]{1,0}, f32[2]{0}) parameter(0), sharding={{devices=[2,1]0,1},
{replicated}}
ROOT outfeed = token[] outfeed(data, token.0), sharding={{devices=[2,1]0,1},
{replicated}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("token[]"),
op::Outfeed(op::Parameter(), op::AfterAll())));
}
TEST_F(SpmdPartitioningTest, OutfeedUnevenlyTiled) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
token.0 = token[] after-all()
data = (f32[1023,2]{1,0}, f32[3]{0}) parameter(0), sharding={{devices=[2,1]0,1},
{devices=[2]0,1}}
outfeed = token[] outfeed(data, token.0),
outfeed_shape=(f32[1023,2]{0,1}, f32[3]{0}), sharding={{devices=[2,1]0,1},
{devices=[2]0,1}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root, AllOf(op::Shape("token[]"),
op::Conditional(op::Convert(),
op::Tuple(op::Parameter(), op::AfterAll()),
op::Tuple(op::Parameter(), op::AfterAll()))));
auto first_outfeed =
AllOf(op::Shape("(f32[512,2], f32[2])"), op::GetTupleElement());
EXPECT_THAT(root->called_computations()[0]->root_instruction(),
AllOf(op::Shape("token[]"),
op::Outfeed(first_outfeed, op::GetTupleElement())));
auto second_outfeed = AllOf(op::Shape("(f32[511,2], f32[1])"), op::Tuple());
EXPECT_THAT(root->called_computations()[1]->root_instruction(),
AllOf(op::Shape("token[]"),
op::Outfeed(second_outfeed, op::GetTupleElement())));
auto expected_layout0 = LayoutUtil::MakeLayout({0, 1});
auto expected_layout1 = LayoutUtil::MakeLayout({0});
auto first_outfeed_instr = root->called_computations()[0]->root_instruction();
auto second_outfeed_instr =
root->called_computations()[1]->root_instruction();
EXPECT_TRUE(LayoutUtil::Equal(
first_outfeed_instr->outfeed_shape().tuple_shapes(0).layout(),
expected_layout0));
EXPECT_TRUE(LayoutUtil::Equal(
first_outfeed_instr->outfeed_shape().tuple_shapes(1).layout(),
expected_layout1));
EXPECT_TRUE(LayoutUtil::Equal(
second_outfeed_instr->outfeed_shape().tuple_shapes(0).layout(),
expected_layout0));
EXPECT_TRUE(LayoutUtil::Equal(
second_outfeed_instr->outfeed_shape().tuple_shapes(1).layout(),
expected_layout1));
}
TEST_F(SpmdPartitioningTest, ReduceWindowReplicatedInput) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
constant = f32[6,2]{1,0} constant({{1,1},{1,4},{2,1},{3,1},{1,2},{2,2}}),
sharding={replicated}
constant.1 = f32[] constant(0), sharding={replicated}
ROOT reduce-window = f32[3,2]{1,0} reduce-window(constant, constant.1),
window={size=3x1 stride=2x1 pad=1_0x0_0}, to_apply=sum,
sharding={devices=[2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
AllOf(op::Shape("f32[2,2]{1,0}"),
op::ReduceWindow(
op::DynamicSlice(AllOf(op::Shape("f32[9,2]{1,0}"),
op::Pad(op::Constant(), op::Constant())),
op::Multiply(op::Reshape(), op::Constant()),
op::Constant()),
op::Constant())));
}
TEST_F(SpmdPartitioningTest, ReduceWindowTiledNegativeLeftHalo) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
constant = f32[6,2]{1,0} constant({{1,1},{1,4},{2,1},{3,1},{1,2},{2,2}}),
sharding={devices=[2,1]0,1}
constant.1 = f32[] constant(0), sharding={replicated}
ROOT %reduce-window = f32[3,2]{1,0} reduce-window(%constant, %constant.1),
window={size=3x1 stride=2x1 pad=0_1x0_0}, to_apply=sum,
sharding={devices=[2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
auto sharded_input =
op::DynamicSlice(op::Constant(), op::Reshape(), op::Constant());
auto right_halo = AllOf(op::Shape("f32[2,2]{1,0}"),
op::CollectivePermute(op::Slice(sharded_input)));
auto pre_masking = op::DynamicSlice(
AllOf(
op::Shape("f32[6,2]{1,0}"),
op::Pad(op::Concatenate(sharded_input, right_halo), op::Constant())),
op::Reshape(), op::Constant());
auto index_in_padded = op::Add(
op::Iota(), op::Broadcast(op::Multiply(op::Reshape(), op::Constant())));
auto masked =
op::Select(op::Compare(index_in_padded, op::Broadcast(op::Constant())),
pre_masking, op::Broadcast(op::Constant()));
EXPECT_THAT(root, AllOf(op::Shape("f32[2,2]{1,0}"),
op::ReduceWindow(masked, op::Constant())));
}
TEST_F(SpmdPartitioningTest, ReduceWindowTiledOneSideHaloBeyondNeighbor) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
param = f32[9,2] parameter(0), sharding={devices=[5,1]0,1,2,3,4}
constant.1 = f32[] constant(0), sharding={replicated}
ROOT reduce-window = f32[5,2]{1,0} reduce-window(param, constant.1),
window={size=4x1 stride=2x1 pad=3_0x0_0}, to_apply=sum,
sharding={devices=[5,1]0,1,2,3,4}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/5));
VLOG(1) << module->ToString();
auto halo0 = AllOf(op::Shape("f32[1,2]"),
op::CollectivePermute(op::Slice(op::Parameter(0))));
auto halo1 =
AllOf(op::Shape("f32[2,2]"), op::CollectivePermute(op::Parameter(0)));
auto pre_mask =
AllOf(op::Shape("f32[4,2]"),
op::Concatenate(halo0, halo1, op::Slice(op::Parameter(0))));
auto masked =
op::Select(op::Compare(op::Add(op::Iota(), op::Broadcast(op::Multiply())),
op::Broadcast(op::Constant())),
pre_mask, op::Broadcast(op::Constant()));
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[1,2]{1,0}"),
op::ReduceWindow(masked, op::Constant())));
}
TEST_F(SpmdPartitioningTest, ReduceWindowTiledOneSideUnequalHalo) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
constant = f32[9,2]{1,0} constant(
{{1,1},{1,4},{2,1},{3,1},{1,2},{2,2},{4,1},{1,2},{2,1}}),
sharding={devices=[3,1]0,1,2}
constant.1 = f32[] constant(0), sharding={replicated}
ROOT reduce-window = f32[5,2]{1,0} reduce-window(constant, constant.1),
window={size=3x1 stride=2x1 pad=1_1x0_0}, to_apply=sum,
sharding={devices=[3,1]0,1,2}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/3));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
auto sharded_input =
op::DynamicSlice(op::Constant(), op::Reshape(), op::Constant());
auto right_halo = AllOf(op::Shape("f32[2,2]{1,0}"),
op::CollectivePermute(op::Slice(sharded_input)));
auto pre_masking = op::DynamicSlice(
AllOf(
op::Shape("f32[7,2]{1,0}"),
op::Pad(op::Concatenate(sharded_input, right_halo), op::Constant())),
op::Reshape(), op::Constant());
auto index_in_padded = op::Add(
op::Iota(), op::Broadcast(op::Multiply(op::Reshape(), op::Constant())));
auto masked = op::Select(
op::And(op::Compare(index_in_padded, op::Broadcast(op::Constant())),
op::Compare(index_in_padded, op::Broadcast(op::Constant()))),
pre_masking, op::Broadcast(op::Constant()));
EXPECT_THAT(root, AllOf(op::Shape("f32[2,2]{1,0}"),
op::ReduceWindow(masked, op::Constant())));
}
TEST_F(SpmdPartitioningTest, ReduceWindowTiledTwoSideHalo) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
constant = f32[4,2]{1,0} constant({{1,1},{1,4},{2,1},{3,1}}),
sharding={devices=[2,1]0,1}
constant.1 = f32[] constant(0), sharding={replicated}
ROOT reduce-window = f32[2,2]{1,0} reduce-window(constant, constant.1),
window={size=5x1 stride=3x1 pad=2_2x0_0}, to_apply=sum,
sharding={devices=[2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
auto sharded_input =
op::DynamicSlice(op::Constant(), op::Reshape(), op::Constant());
auto left_halo = AllOf(op::Shape("f32[1,2]{1,0}"),
op::CollectivePermute(op::Slice(sharded_input)));
auto right_halo = AllOf(op::Shape("f32[1,2]{1,0}"),
op::CollectivePermute(op::Slice(sharded_input)));
auto pre_masking = AllOf(
op::Shape("f32[5,2]{1,0}"),
op::DynamicSlice(
AllOf(op::Shape("f32[6,2]{1,0}"),
op::Pad(op::Concatenate(left_halo, sharded_input, right_halo),
op::Constant())),
op::Reshape(), op::Constant()));
auto index_in_padded = op::Add(
op::Iota(), op::Broadcast(op::Multiply(op::Reshape(), op::Constant())));
auto masked = op::Select(
op::And(op::Compare(index_in_padded, op::Broadcast(op::Constant())),
op::Compare(index_in_padded, op::Broadcast(op::Constant()))),
pre_masking, op::Broadcast(op::Constant()));
EXPECT_THAT(root, AllOf(op::Shape("f32[1,2]{1,0}"),
op::ReduceWindow(masked, op::Constant())));
}
TEST_F(SpmdPartitioningTest, ReduceWindowTiled2D) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
token0 = token[] after-all(), sharding={maximal device=0}
infeed = (f32[4,4,2,2]{3,2,1,0}, token[]) infeed(token0),
sharding={{devices=[2,2,1,1]0,1,2,3}, {maximal device=0}}
infeed.data = f32[4,4,2,2]{3,2,1,0} get-tuple-element(infeed), index=0,
sharding={devices=[2,2,1,1]0,1,2,3}
constant = f32[] constant(0), sharding={replicated}
ROOT reduce-window = f32[2,2,2,2]{3,2,1,0} reduce-window(infeed.data, constant),
window={size=5x5x1x1 stride=3x3x1x1 pad=2_2x2_2x0_0x0_0}, to_apply=sum,
sharding={devices=[2,2,1,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
auto sharded_input = AllOf(op::Shape("f32[2,2,2,2]{3,2,1,0}"),
op::GetTupleElement(op::Infeed()));
auto dim0_left_halo = AllOf(op::Shape("f32[1,2,2,2]{3,2,1,0}"),
op::CollectivePermute(op::Slice(sharded_input)));
auto dim0_right_halo = AllOf(op::Shape("f32[1,2,2,2]{3,2,1,0}"),
op::CollectivePermute(op::Slice(sharded_input)));
auto dim0_pre_masking = op::DynamicSlice(
AllOf(op::Shape("f32[6,2,2,2]{3,2,1,0}"),
op::Pad(
op::Concatenate(dim0_left_halo, sharded_input, dim0_right_halo),
op::Constant())),
op::Reshape(), op::Constant(), op::Constant(), op::Constant());
auto dim0_index_in_padded = op::Add(
op::Iota(), op::Broadcast(op::Multiply(op::Reshape(), op::Constant())));
auto dim0_masked = op::Select(
op::And(op::Compare(dim0_index_in_padded, op::Broadcast(op::Constant())),
op::Compare(dim0_index_in_padded, op::Broadcast(op::Constant()))),
dim0_pre_masking, op::Broadcast(op::Constant()));
auto dim0_resharded = AllOf(op::Shape("f32[5,2,2,2]{3,2,1,0}"), dim0_masked);
auto dim1_left_halo = AllOf(op::Shape("f32[5,1,2,2]{3,2,1,0}"),
op::CollectivePermute(op::Slice(dim0_resharded)));
auto dim1_right_halo =
AllOf(op::Shape("f32[5,1,2,2]{3,2,1,0}"),
op::CollectivePermute(op::Slice(dim0_resharded)));
auto dim1_pre_masking = op::DynamicSlice(
AllOf(op::Shape("f32[5,6,2,2]{3,2,1,0}"),
op::Pad(op::Concatenate(dim1_left_halo, dim0_resharded,
dim1_right_halo),
op::Constant())),
op::Constant(), op::Reshape(), op::Constant(), op::Constant());
auto dim1_index_in_padded = op::Add(
op::Iota(), op::Broadcast(op::Multiply(op::Reshape(), op::Constant())));
auto dim1_masked = op::Select(
op::And(op::Compare(dim1_index_in_padded, op::Broadcast(op::Constant())),
op::Compare(dim1_index_in_padded, op::Broadcast(op::Constant()))),
dim1_pre_masking, op::Broadcast(op::Constant()));
auto dim1_resharded = AllOf(op::Shape("f32[5,5,2,2]{3,2,1,0}"), dim1_masked);
EXPECT_THAT(root, AllOf(op::Shape("f32[1,1,2,2]{3,2,1,0}"),
op::ReduceWindow(dim1_resharded, op::Constant())));
}
TEST_F(SpmdPartitioningTest, ConvolutionLhsTiledRhsReplicated) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,224,224,3] parameter(0)
%lhs.copy = f32[128,224,224,3] copy(f32[128,224,224,3] %lhs),
sharding={devices=[1,2,1,1]0,1}
%rhs = f32[7,7,3,64] parameter(1)
%rhs.copy = f32[7,7,3,64] copy(f32[7,7,3,64] %rhs),
sharding={replicated}
ROOT %conv = f32[128,112,112,64] convolution(
f32[128,224,224,3] %lhs.copy,
f32[7,7,3,64] %rhs.copy),
window={size=7x7 stride=2x2 pad=3_3x3_3},
dim_labels=b01f_01io->b01f,
sharding={devices=[1,2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,112,224,3]"));
auto rhs = AllOf(op::Copy(op::Parameter()), op::Shape("f32[7,7,3,64]"));
auto left_halo = AllOf(op::CollectivePermute(op::Slice(lhs)),
op::Shape("f32[128,3,224,3]"));
auto right_halo = AllOf(op::CollectivePermute(op::Slice(lhs)),
op::Shape("f32[128,2,224,3]"));
EXPECT_THAT(root,
AllOf(op::Convolution(
op::Select(op::And(),
op::Concatenate(left_halo, lhs, right_halo),
op::Broadcast()),
rhs),
op::Shape("f32[128,56,112,64]")));
}
TEST_F(SpmdPartitioningTest, ConvolutionLhsTiledRhsReplicatedNeedReshard) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,224,224,3] parameter(0)
%lhs.copy = f32[128,224,224,3] copy(f32[128,224,224,3] %lhs),
sharding={devices=[2,1,1,1]0,1}
%rhs = f32[7,7,3,64] parameter(1)
%rhs.copy = f32[7,7,3,64] copy(f32[7,7,3,64] %rhs),
sharding={replicated}
ROOT %conv = f32[128,112,112,64] convolution(
f32[128,224,224,3] %lhs.copy,
f32[7,7,3,64] %rhs.copy),
window={size=7x7 stride=2x2 pad=3_3x3_3},
dim_labels=b01f_01io->b01f,
sharding={devices=[1,2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(), op::Constant(),
op::Constant(), op::Constant())),
op::Shape("f32[64,224,224,3]"));
auto all_to_all =
AllOf(op::AllToAll(op::Reshape(lhs)), op::Shape("f32[64,2,112,224,3]"));
auto reshard_lhs = AllOf(op::Reshape(op::Transpose(all_to_all)),
op::Shape("f32[128,112,224,3]"));
auto rhs = AllOf(op::Copy(op::Parameter()), op::Shape("f32[7,7,3,64]"));
auto left_halo = AllOf(op::CollectivePermute(op::Slice(reshard_lhs)),
op::Shape("f32[128,3,224,3]"));
auto right_halo = AllOf(op::CollectivePermute(op::Slice(reshard_lhs)),
op::Shape("f32[128,2,224,3]"));
EXPECT_THAT(
root,
AllOf(op::Convolution(
op::Select(op::And(),
op::Concatenate(left_halo, reshard_lhs, right_halo),
op::Broadcast()),
rhs),
op::Shape("f32[128,56,112,64]")));
}
TEST_F(SpmdPartitioningTest, ConvolutionLhsTiledRhsReplicatedReordered) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[224,224,3,128] parameter(0)
%lhs.copy = f32[224,224,3,128] copy(%lhs), sharding={devices=[2,1,1,1]0,1}
%rhs = f32[7,7,3,64] parameter(1)
%rhs.copy = f32[7,7,3,64] copy(%rhs), sharding={replicated}
ROOT %conv = f32[128,112,112,64] convolution(%lhs.copy, %rhs.copy),
window={size=7x7 stride=2x2 pad=3_3x3_3},
dim_labels=01fb_01io->b01f,
sharding={devices=[1,2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(), op::Constant(),
op::Constant(), op::Constant())),
op::Shape("f32[112,224,3,128]"));
auto rhs = AllOf(op::Copy(op::Parameter()), op::Shape("f32[7,7,3,64]"));
auto left_halo = AllOf(op::CollectivePermute(op::Slice(lhs)),
op::Shape("f32[3,224,3,128]"));
auto right_halo = AllOf(op::CollectivePermute(op::Slice(lhs)),
op::Shape("f32[2,224,3,128]"));
EXPECT_THAT(root,
AllOf(op::Convolution(
op::Select(op::And(),
op::Concatenate(left_halo, lhs, right_halo),
op::Broadcast()),
rhs),
op::Shape("f32[128,56,112,64]")));
}
// (stride * per_shard_window_count) % dilation == 0
TEST_F(SpmdPartitioningTest,
ConvolutionBaseDilationSameStartPatternLhsTiledRhsReplicated) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,7,7,512] parameter(0)
%lhs.copy = f32[128,7,7,512] copy(%lhs),
sharding={devices=[1,2,1,1]0,1}
%rhs = f32[3,3,512,512] parameter(1)
%rhs.copy = f32[3,3,512,512] copy(%rhs),
sharding={replicated}
ROOT %conv = f32[128,4,4,512] convolution(%lhs.copy, %rhs.copy),
window={size=3x3 stride=4x4 pad=1_1x1_1 lhs_dilate=2x2 rhs_reversal=1x1},
dim_labels=b01f_01io->b01f,
sharding={devices=[1,2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
// There is no halo exchange, and because the last element in the shard is not
// needed (stride == 4), the LHS will be just a slice.
auto sliced_lhs =
AllOf(op::Slice(op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Constant()))),
op::Shape("f32[128,3,7,512]"));
auto rhs = AllOf(op::Copy(op::Parameter()), op::Shape("f32[3,3,512,512]"));
EXPECT_THAT(root, AllOf(op::Convolution(sliced_lhs, rhs),
op::Shape("f32[128,2,4,512]")));
EXPECT_EQ(root->window().dimensions(0).padding_low(), 1);
EXPECT_EQ(root->window().dimensions(0).padding_high(), 1);
}
// (stride * per_shard_window_count) % dilation != 0 but stride == 1
TEST_F(SpmdPartitioningTest,
ConvolutionBaseDilationStride1LhsTiledRhsReplicated) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,7,7,512] parameter(0)
%lhs.copy = f32[128,7,7,512] copy(%lhs),
sharding={devices=[1,2,1,1]0,1}
%rhs = f32[3,3,512,512] parameter(1)
%rhs.copy = f32[3,3,512,512] copy(%rhs),
sharding={replicated}
ROOT %conv = f32[128,14,14,512] convolution(%lhs.copy, %rhs.copy),
window={size=3x3 pad=1_2x1_2 lhs_dilate=2x2 rhs_reversal=1x1},
dim_labels=b01f_01io->b01f,
sharding={devices=[1,2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Constant())),
op::Shape("f32[128,4,7,512]"));
auto rhs = AllOf(op::Copy(op::Parameter()), op::Shape("f32[3,3,512,512]"));
auto left_halo = AllOf(op::CollectivePermute(op::Slice(lhs)),
op::Shape("f32[128,1,7,512]"));
auto start_window = op::Multiply(op::Reshape(), op::Constant());
auto start_input_element = op::Divide(start_window, op::Constant());
auto dynamic_offset_for_padded_concat = op::Subtract(
op::Constant(), op::Subtract(op::Multiply(op::Reshape(), op::Constant()),
start_input_element));
auto pre_masking =
AllOf(op::Shape("f32[128,5,7,512]"),
op::DynamicSlice(
AllOf(op::Shape("f32[128,6,7,512]"),
op::Pad(op::Concatenate(left_halo, lhs), op::Constant())),
op::Constant(), dynamic_offset_for_padded_concat,
op::Constant(), op::Constant()));
auto masked = op::Select(
op::Compare(op::Add(op::Iota(), op::Broadcast(start_input_element)),
op::Broadcast(op::Constant())),
pre_masking, op::Broadcast(op::Constant()));
auto dynamic_offset_on_output = op::Subtract(
start_window, op::Multiply(start_input_element, op::Constant()));
EXPECT_THAT(root,
AllOf(op::DynamicSlice(AllOf(op::Convolution(masked, rhs),
op::Shape("f32[128,8,14,512]")),
op::Constant(), dynamic_offset_on_output,
op::Constant(), op::Constant()),
op::Shape("f32[128,7,14,512]")));
EXPECT_EQ(root->operand(0)->window().dimensions(0).padding_low(), 1);
EXPECT_EQ(root->operand(0)->window().dimensions(0).padding_high(), 0);
}
TEST_F(SpmdPartitioningTest, SelectAndScatterNoOverlap) {
absl::string_view hlo_string = R"(
HloModule module
ge {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT compare = pred[] compare(a, b), direction=GE
}
sum {
c = f32[] parameter(0)
d = f32[] parameter(1)
ROOT add = f32[] add(c, d)
}
ENTRY entry {
%param = f32[11,4]{1,0} parameter(0)
%param.copy = f32[11,4] copy(%param),
sharding={devices=[4,1]0,1,2,3}
constant = f32[4,2]{1,0} constant({{1,2},{3,4},{1,0},{2,8}}),
sharding={devices=[4,1]0,1,2,3}
constant.1 = f32[] constant(0), sharding={replicated}
ROOT select-and-scatter = f32[11,4]{1,0} select-and-scatter(param.copy,
constant, constant.1), window={size=3x2 stride=3x2 pad=0_1x0_0},
select=ge, scatter=sum, sharding={devices=[4,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto source =
AllOf(op::Shape("f32[1,2]{1,0}"),
op::DynamicSlice(op::Constant(), op::Reshape(), op::Constant()));
auto masked_data = AllOf(
op::Shape("f32[3,4]{1,0}"),
op::Select(
op::Compare(op::Add(op::Iota(), op::Broadcast(op::Multiply(
op::Reshape(), op::Constant()))),
op::Broadcast(op::Constant())),
op::Copy(op::DynamicSlice(op::Pad(op::Parameter(), op::Constant()),
op::Reshape(), op::Constant())),
op::Broadcast(op::Constant())));
EXPECT_THAT(root,
AllOf(op::SelectAndScatter(masked_data, source, op::Constant()),
op::Shape("f32[3,4]{1,0}")));
EXPECT_EQ(root->window().dimensions(0).padding_low(), 0);
EXPECT_EQ(root->window().dimensions(0).padding_high(), 0);
}
TEST_F(SpmdPartitioningTest, SelectAndScatterNoOverlapReshard) {
absl::string_view hlo_string = R"(
HloModule module
ge {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT compare = pred[] compare(a, b), direction=GE
}
sum {
c = f32[] parameter(0)
d = f32[] parameter(1)
ROOT add = f32[] add(c, d)
}
ENTRY entry {
%param = f32[11,4]{1,0} parameter(0)
%param.copy = f32[11,4] copy(%param),
sharding={devices=[1,4]0,1,2,3}
constant = f32[4,2]{1,0} constant({{1,2},{3,4},{1,0},{2,8}}),
sharding={devices=[4,1]0,1,2,3}
constant.1 = f32[] constant(0), sharding={replicated}
ROOT select-and-scatter = f32[11,4]{1,0} select-and-scatter(param.copy,
constant, constant.1), window={size=3x2 stride=3x2 pad=0_1x0_0},
select=ge, scatter=sum, sharding={devices=[4,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto source =
AllOf(op::Shape("f32[1,2]{1,0}"),
op::DynamicSlice(op::Constant(), op::Reshape(), op::Constant()));
auto operand = AllOf(op::Copy(op::DynamicSlice(
op::Parameter(0), op::Constant(), op::Reshape())),
op::Shape("f32[11,1]"));
auto reshard_operand = op::Reshape(op::Transpose(
op::AllToAll(op::Reshape(op::Pad(operand, op::Constant())))));
auto masked_data = AllOf(
op::Shape("f32[3,4]{1,0}"),
op::Select(
op::Compare(op::Add(op::Iota(), op::Broadcast(op::Multiply(
op::Reshape(), op::Constant()))),
op::Broadcast(op::Constant())),
reshard_operand, op::Broadcast(op::Constant())));
EXPECT_THAT(root,
AllOf(op::SelectAndScatter(masked_data, source, op::Constant()),
op::Shape("f32[3,4]{1,0}")));
EXPECT_EQ(root->window().dimensions(0).padding_low(), 0);
EXPECT_EQ(root->window().dimensions(0).padding_high(), 0);
}
TEST_F(SpmdPartitioningTest, SelectAndScatterWithOverlap) {
absl::string_view hlo_string = R"(
HloModule module
ge {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT compare = pred[] compare(a, b), direction=GE
}
sum {
c = f32[] parameter(0)
d = f32[] parameter(1)
ROOT add = f32[] add(c, d)
}
ENTRY entry {
%param = f32[11,4]{1,0} parameter(0)
%param.copy = f32[11,4] copy(%param),
sharding={devices=[4,1]0,1,2,3}
constant = f32[6,2]{1,0} constant({{1,2},{3,4},{1,0},{2,8},{6,6},{1,9}}),
sharding={devices=[4,1]0,1,2,3}
constant.1 = f32[] constant(0), sharding={replicated}
ROOT select-and-scatter = f32[11,4]{1,0} select-and-scatter(param.copy,
constant, constant.1), window={size=3x2 stride=2x2 pad=1_1x0_0},
select=ge, scatter=sum, sharding={devices=[4,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto source_shard =
AllOf(op::Shape("f32[2,2]{1,0}"),
op::DynamicSlice(op::Pad(), op::Reshape(), op::Constant()));
// Max halo size is the same as the shard size, so slice is not needed.
auto source_left_halo = op::CollectivePermute(source_shard);
auto required_source_shard_start =
op::Divide(op::Multiply(op::Reshape(), op::Constant()), op::Constant());
auto source_with_halo = op::DynamicSlice(
AllOf(op::Shape("f32[5,2]{1,0}"),
op::Pad(op::Concatenate(source_left_halo, source_shard),
op::Constant())),
op::Subtract(op::Constant(),
op::Subtract(op::Multiply(op::Reshape(), op::Constant()),
required_source_shard_start)),
op::Constant());
auto masked_source_with_halo = AllOf(
AllOf(op::Shape("f32[3,2]{1,0}")),
op::Select(
op::Compare(
op::Add(op::Iota(), op::Broadcast(required_source_shard_start)),
op::Broadcast(op::Constant())),
source_with_halo, op::Broadcast(op::Constant())));
auto data_shard =
AllOf(op::Shape("f32[3,4]{1,0}"),
op::Copy(op::DynamicSlice(op::Pad(op::Parameter(), op::Constant()),
op::Reshape(), op::Constant())));
auto data_left_halo = AllOf(op::Shape("f32[2,4]{1,0}"),
op::CollectivePermute(op::Slice(data_shard)));
auto data_right_halo = AllOf(op::Shape("f32[2,4]{1,0}"),
op::CollectivePermute(op::Slice(data_shard)));
auto required_data_start_on_padded =
op::Multiply(required_source_shard_start, op::Constant());
auto left_halo_size = op::Subtract(
op::Add(op::Multiply(op::Reshape(), op::Constant()), op::Constant()),
required_data_start_on_padded);
auto data_with_halo =
AllOf(op::Shape("f32[7,4]{1,0}"),
op::DynamicSlice(
AllOf(op::Shape("f32[8,4]{1,0}"),
op::Pad(op::Concatenate(data_left_halo, data_shard,
data_right_halo),
op::Constant())),
op::Subtract(op::Constant(), left_halo_size), op::Constant()));
auto index_on_padded =
op::Add(op::Iota(), op::Broadcast(required_data_start_on_padded));
auto masked_data_with_halo = op::Select(
op::And(op::Compare(index_on_padded, op::Broadcast(op::Constant())),
op::Compare(index_on_padded, op::Broadcast(op::Constant()))),
data_with_halo, op::Broadcast(op::Constant()));
EXPECT_THAT(
root, AllOf(op::DynamicSlice(op::SelectAndScatter(masked_data_with_halo,
masked_source_with_halo,
op::Constant()),
left_halo_size, op::Constant()),
op::Shape("f32[3,4]{1,0}")));
EXPECT_EQ(root->operand(0)->window().dimensions(0).padding_low(), 0);
EXPECT_EQ(root->operand(0)->window().dimensions(0).padding_high(), 0);
}
TEST_F(SpmdPartitioningTest, ConvolutionLhsTiledRhsTiled) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,56,56,64] parameter(0)
%lhs.copy = f32[128,56,56,64] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[128,56,56,256] parameter(1)
%rhs.copy = f32[128,56,56,256] copy(%rhs), sharding={devices=[1,2,1,1]0,1}
ROOT %conv = f32[1,1,64,256] convolution(%lhs.copy, %rhs.copy),
window={size=56x56}, dim_labels=f01b_i01o->01bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,28,56,64]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,28,56,256]"));
EXPECT_THAT(root, AllOf(op::AllReduce(op::Convolution(lhs, rhs)),
op::Shape("f32[1,1,64,256]")));
}
TEST_F(SpmdPartitioningTest, ConvolutionLhsTiledRhsTiledWindowReversal) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[5,128,64] parameter(0), sharding={devices=[2,1,1]0,1}
%rhs = f32[5,128,256] parameter(1), sharding={devices=[2,1,1]1,0}
ROOT %conv = f32[1,64,256] convolution(%lhs, %rhs),
window={size=5 rhs_reversal=1}, dim_labels=0fb_0io->0bf,
sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto lhs_masked =
AllOf(op::Shape("f32[3,128,64]"), op::Select(_, op::Parameter(0), _));
auto rhs_left_padded =
op::Concatenate(op::CollectivePermute(op::Slice(op::Parameter(1))),
op::Slice(op::Parameter(1)));
auto rhs_masked =
AllOf(op::Shape("f32[3,128,256]"), op::Select(_, rhs_left_padded, _));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root,
AllOf(op::AllReduce(op::Convolution(lhs_masked, rhs_masked)),
op::Shape("f32[1,64,256]")));
}
TEST_F(SpmdPartitioningTest, DotLhsTiledRhsTiledWithReshard) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,56,56,64] parameter(0)
%lhs.copy = f32[128,56,56,64] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[128,56,56,256] parameter(1)
%rhs.copy = f32[128,56,56,256] copy(%rhs), sharding={devices=[2,1,1,1]0,1}
ROOT %conv = f32[1,1,64,256] convolution(%lhs.copy, %rhs.copy),
window={size=56x56}, dim_labels=f01b_i01o->01bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,28,56,64]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(), op::Constant(),
op::Constant(), op::Constant())),
op::Shape("f32[64,56,56,256]"));
auto all_to_all =
AllOf(op::AllToAll(op::Reshape(lhs)), op::Shape("f32[2,64,28,56,64]"));
auto reshard = AllOf(op::Reshape(op::Transpose(all_to_all)));
EXPECT_THAT(root, AllOf(op::AllReduce(op::Convolution(reshard, rhs)),
op::Shape("f32[1,1,64,256]")));
}
TEST_F(SpmdPartitioningTest, ConvolutionLhsTiledRhsTiledWithReshard) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,56,56,512] parameter(0)
%lhs.copy = f32[128,56,56,512] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[128,28,28,64] parameter(1)
%rhs.copy = f32[128,28,28,64] copy(%rhs), sharding={devices=[2,1,1,1]0,1}
ROOT %conv = f32[1,1,512,64] convolution(%lhs.copy, %rhs.copy),
window={size=28x28 pad=0_-1x0_-1 rhs_dilate=2x2},
dim_labels=f01b_i01o->01bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,28,56,512]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(), op::Constant(),
op::Constant(), op::Constant())),
op::Shape("f32[64,28,28,64]"));
auto all_to_all =
AllOf(op::AllToAll(op::Reshape(rhs)), op::Shape("f32[64,2,14,28,64]"));
auto reshard = op::Reshape(op::Transpose(all_to_all));
EXPECT_THAT(root,
AllOf(op::AllReduce(op::Convolution(op::Slice(lhs), reshard)),
op::Shape("f32[1,1,512,64]")));
}
TEST_F(SpmdPartitioningTest,
ConvolutionLhsTiledRhsTiled_UnevenDilatedRHSPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[8,28,28,8] parameter(0)
%lhs.copy = f32[8,28,28,8] copy(%lhs), sharding={devices=[1,4,1,1]0,1,2,3}
%rhs = f32[8,14,14,64] parameter(1)
%rhs.copy = f32[8,14,14,64] copy(%rhs), sharding={devices=[1,4,1,1]0,1,2,3}
ROOT %conv = f32[1,1,8,64] convolution(%lhs.copy, %rhs.copy),
window={size=14x14 pad=0_-1x0_-1 rhs_dilate=2x2},
dim_labels=f01b_i01o->01bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[8,7,28,8]"));
auto rhs = AllOf(op::Pad(op::Parameter(), op::Constant()),
op::Shape("f32[8,16,14,64]"));
auto selected_rhs = AllOf(
op::Select(op::Compare(),
op::Copy(op::DynamicSlice(rhs, op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Broadcast()),
op::Shape("f32[8,4,14,64]"));
auto right_halo =
AllOf(op::CollectivePermute(op::Slice(lhs)), op::Shape("f32[8,2,28,8]"));
auto selected_lhs =
AllOf(op::DynamicSlice(
op::Pad(op::Concatenate(lhs, right_halo), op::Constant()),
op::Constant(), op::Reshape(), op::Constant(), op::Constant()),
op::Shape("f32[8,7,28,8]"));
EXPECT_THAT(root,
AllOf(op::AllReduce(op::Convolution(selected_lhs, selected_rhs)),
op::Shape("f32[1,1,8,64]")));
}
TEST_F(SpmdPartitioningTest, ConvolutionLhsTiledRhsTiledWithPadding) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,28,28,128] parameter(0)
%lhs.copy = f32[32,28,28,128] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[32,28,28,64] parameter(1)
%rhs.copy = f32[32,28,28,64] copy(%rhs), sharding={devices=[1,2,1,1]0,1}
ROOT %conv = f32[3,3,128,64] convolution(%lhs.copy, %rhs.copy),
window={size=28x28 pad=1_1x1_1}, dim_labels=f01b_i01o->01bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(
auto module,
PartitionComputation(hlo_string, /*num_devices=*/2,
/*conv_halo_exchange_always_on_lhs=*/false));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[32,14,28,128]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[32,14,28,64]"));
auto left_halo = AllOf(op::CollectivePermute(op::Slice(rhs)),
op::Shape("f32[32,1,28,64]"));
auto right_halo = AllOf(op::CollectivePermute(op::Slice(rhs)),
op::Shape("f32[32,1,28,64]"));
EXPECT_THAT(root,
AllOf(op::AllReduce(op::Convolution(
lhs, AllOf(op::Concatenate(left_halo, rhs, right_halo),
op::Shape("f32[32,16,28,64]")))),
op::Shape("f32[3,3,128,64]")));
}
TEST_F(SpmdPartitioningTest, ConvolutionLhsTiledRhsTiledWindowDilate) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,224,224,3] parameter(0)
%lhs.copy = f32[128,224,224,3] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[128,112,112,64] parameter(1)
%rhs.copy = f32[128,112,112,64] copy(%rhs), sharding={devices=[1,2,1,1]0,1}
ROOT %conv = f32[7,7,3,64] convolution(%lhs.copy, %rhs.copy),
window={size=112x112 pad=3_2x3_2 rhs_dilate=2x2}, dim_labels=f01b_i01o->01bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(
auto module,
PartitionComputation(hlo_string, /*num_devices=*/2,
/*conv_halo_exchange_always_on_lhs=*/false));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,112,224,3]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,56,112,64]"));
auto left_halo = AllOf(op::CollectivePermute(op::Slice(rhs)),
op::Shape("f32[128,2,112,64]"));
auto right_halo = AllOf(op::CollectivePermute(op::Slice(rhs)),
op::Shape("f32[128,2,112,64]"));
EXPECT_THAT(root,
AllOf(op::AllReduce(op::Convolution(
lhs, AllOf(op::Concatenate(left_halo, rhs, right_halo),
op::Shape("f32[128,60,112,64]")))),
op::Shape("f32[7,7,3,64]")));
}
TEST_F(SpmdPartitioningTest,
ConvolutionLhsTiledRhsTiledWindowDilateNegativeRhsPadding) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,56,56,256] parameter(0)
%lhs.copy = f32[128,56,56,256] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[128,28,28,512] parameter(1)
%rhs.copy = f32[128,28,28,512] copy(%rhs), sharding={devices=[1,2,1,1]0,1}
ROOT %conv = f32[1,1,256,512] convolution(%lhs.copy, %rhs.copy),
window={size=28x28 pad=0_-1x0_-1 rhs_dilate=2x2}, dim_labels=f01b_i01o->01bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(
auto module,
PartitionComputation(hlo_string, /*num_devices=*/2,
/*conv_halo_exchange_always_on_lhs=*/false));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,28,56,256]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,14,28,512]"));
EXPECT_THAT(root, AllOf(op::AllReduce(op::Convolution(lhs, rhs)),
op::Shape("f32[1,1,256,512]")));
}
TEST_F(SpmdPartitioningTest, ConvolutionLhsTiledRhsTiledWindowDilateUneven) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,14,14,512] parameter(0)
%lhs.copy = f32[128,14,14,512] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[128,7,7,512] parameter(1)
%rhs.copy = f32[128,7,7,512] copy(%rhs), sharding={devices=[1,2,1,1]0,1}
ROOT %conv = f32[3,3,512,512] convolution(%lhs.copy, %rhs.copy),
window={size=7x7 pad=1_0x1_0 rhs_dilate=2x2}, dim_labels=f01b_i01o->01bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(
auto module,
PartitionComputation(hlo_string, /*num_devices=*/2,
/*conv_halo_exchange_always_on_lhs=*/false));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,7,14,512]"));
auto rhs = AllOf(
op::Select(op::Compare(),
op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Constant())),
op::Broadcast()),
op::Shape("f32[128,4,7,512]"));
auto left_halo = AllOf(op::CollectivePermute(op::Slice(rhs)),
op::Shape("f32[128,1,7,512]"));
EXPECT_THAT(root,
AllOf(op::AllReduce(op::Convolution(
AllOf(op::DynamicSlice(op::Pad(lhs, op::Constant()),
op::Constant(), op::Subtract(),
op::Constant(), op::Constant()),
op::Shape("f32[128,10,14,512]")),
AllOf(op::Concatenate(left_halo, rhs),
op::Shape("f32[128,5,7,512]")))),
op::Shape("f32[3,3,512,512]")));
}
TEST_F(SpmdPartitioningTest, ConvolutionLhsTiledRhsTiledWithPadding_HaloOnLhs) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,28,28,128] parameter(0)
%lhs.copy = f32[32,28,28,128] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[32,28,28,64] parameter(1)
%rhs.copy = f32[32,28,28,64] copy(%rhs), sharding={devices=[1,2,1,1]0,1}
ROOT %conv = f32[3,3,128,64] convolution(%lhs.copy, %rhs.copy),
window={size=28x28 pad=1_1x1_1}, dim_labels=f01b_i01o->01bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[32,14,28,128]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[32,14,28,64]"));
auto left_halo = AllOf(op::CollectivePermute(op::Slice(lhs)),
op::Shape("f32[32,1,28,128]"));
auto right_halo = AllOf(op::CollectivePermute(op::Slice(lhs)),
op::Shape("f32[32,1,28,128]"));
EXPECT_THAT(root, AllOf(op::AllReduce(op::Convolution(
AllOf(op::Concatenate(left_halo, lhs, right_halo),
op::Shape("f32[32,16,28,128]")),
rhs)),
op::Shape("f32[3,3,128,64]")));
}
TEST_F(SpmdPartitioningTest,
ConvolutionLhsTiledRhsTiledWindowDilate_HaloOnLhs) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,224,224,3] parameter(0)
%lhs.copy = f32[128,224,224,3] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[128,112,112,64] parameter(1)
%rhs.copy = f32[128,112,112,64] copy(%rhs), sharding={devices=[1,2,1,1]0,1}
ROOT %conv = f32[7,7,3,64] convolution(%lhs.copy, %rhs.copy),
window={size=112x112 pad=3_2x3_2 rhs_dilate=2x2}, dim_labels=f01b_i01o->01bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,112,224,3]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,56,112,64]"));
auto left_halo = AllOf(op::CollectivePermute(op::Slice(lhs)),
op::Shape("f32[128,3,224,3]"));
auto right_halo = AllOf(op::CollectivePermute(op::Slice(lhs)),
op::Shape("f32[128,2,224,3]"));
EXPECT_THAT(root, AllOf(op::AllReduce(op::Convolution(
AllOf(op::Concatenate(left_halo, lhs, right_halo),
op::Shape("f32[128,117,224,3]")),
rhs)),
op::Shape("f32[7,7,3,64]")));
}
TEST_F(SpmdPartitioningTest,
ConvolutionLhsTiledRhsTiledWindowDilateNegativeRhsPadding_HaloOnLhs) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,56,56,256] parameter(0)
%lhs.copy = f32[128,56,56,256] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[128,28,28,512] parameter(1)
%rhs.copy = f32[128,28,28,512] copy(%rhs), sharding={devices=[1,2,1,1]0,1}
ROOT %conv = f32[1,1,256,512] convolution(%lhs.copy, %rhs.copy),
window={size=28x28 pad=0_-1x0_-1 rhs_dilate=2x2}, dim_labels=f01b_i01o->01bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,28,56,256]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,14,28,512]"));
EXPECT_THAT(root, AllOf(op::AllReduce(op::Convolution(op::Slice(lhs), rhs)),
op::Shape("f32[1,1,256,512]")));
}
TEST_F(SpmdPartitioningTest,
ConvolutionLhsTiledRhsTiledWindowDilateUneven_HaloOnLhs) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,14,14,512] parameter(0)
%lhs.copy = f32[128,14,14,512] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[128,7,7,512] parameter(1)
%rhs.copy = f32[128,7,7,512] copy(%rhs), sharding={devices=[1,2,1,1]0,1}
ROOT %conv = f32[3,3,512,512] convolution(%lhs.copy, %rhs.copy),
window={size=7x7 pad=1_0x1_0 rhs_dilate=2x2}, dim_labels=f01b_i01o->01bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[128,7,14,512]"));
auto rhs = AllOf(
op::Select(op::Compare(),
op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Constant())),
op::Broadcast()),
op::Shape("f32[128,4,7,512]"));
auto right_halo = AllOf(op::CollectivePermute(op::Slice(lhs)),
op::Shape("f32[128,1,14,512]"));
EXPECT_THAT(
root, AllOf(op::AllReduce(op::Convolution(
AllOf(op::DynamicSlice(
AllOf(op::Pad(op::Concatenate(lhs, right_halo),
op::Constant()),
op::Shape("f32[128,10,14,512]")),
op::Constant(), op::Reshape(), op::Constant(),
op::Constant()),
op::Shape("f32[128,9,14,512]")),
rhs)),
op::Shape("f32[3,3,512,512]")));
}
TEST_F(SpmdPartitioningTest, ConcatenateAlongNonPartitionedDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[14,257] parameter(0)
%param0.copy = f32[14,257] copy(%param0), sharding={devices=[2,1]0,1}
%param1 = f32[14,116] parameter(1)
%param1.copy = f32[14,116] copy(%param1), sharding={devices=[2,1]0,1}
ROOT %concatenate = f32[14,373] concatenate(%param0.copy, %param1.copy),
dimensions={1}, sharding={devices=[2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(),
op::Constant())),
op::Shape("f32[7,257]"));
auto param1 = AllOf(op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(),
op::Constant())),
op::Shape("f32[7,116]"));
EXPECT_THAT(root,
AllOf(op::Concatenate(param0, param1), op::Shape("f32[7,373]")));
}
TEST_F(SpmdPartitioningTest, ConcatenateAlongPartitionedDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[14,257] parameter(0)
%param0.copy = f32[14,257] copy(%param0), sharding={devices=[1,2]0,1}
%param1 = f32[14,116] parameter(1)
%param1.copy = f32[14,116] copy(%param1), sharding={devices=[1,2]0,1}
ROOT %concatenate = f32[14,373] concatenate(%param0.copy, %param1.copy),
dimensions={1}, sharding={devices=[1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 =
AllOf(op::Copy(op::DynamicSlice(op::Pad(op::Parameter(), op::Constant()),
op::Constant(), op::Reshape())),
op::Shape("f32[14,129]"));
auto param1 = AllOf(op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(),
op::Reshape())),
op::Shape("f32[14,58]"));
EXPECT_THAT(root, AllOf(op::DynamicSlice(
AllOf(op::AllReduce(op::DynamicUpdateSlice(
op::DynamicUpdateSlice(
op::Broadcast(), param0,
op::Constant(), op::Multiply()),
param1, op::Constant(), op::Add())),
op::Shape("f32[14,374]")),
op::Constant(), op::Multiply()),
op::Shape("f32[14,187]")));
}
TEST_F(SpmdPartitioningTest, ConcatenateAlongBothDimensions) {
const char* const hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[14,257] parameter(0), sharding={devices=[2,2]0,1,2,3}
%param1 = f32[14,116] parameter(1), sharding={devices=[2,2]0,1,2,3}
ROOT %concatenate = f32[14,373] concatenate(%param0, %param1),
dimensions={1}, sharding={devices=[2,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Parameter(0), op::Shape("f32[7,129]"));
auto param1 = AllOf(op::Parameter(1), op::Shape("f32[7,58]"));
EXPECT_THAT(root, AllOf(op::DynamicSlice(
AllOf(op::AllReduce(op::DynamicUpdateSlice(
op::DynamicUpdateSlice(
op::Broadcast(), param0,
op::Constant(), op::Multiply()),
param1, op::Constant(), op::Add())),
op::Shape("f32[7,374]")),
op::Constant(), op::Multiply()),
op::Shape("f32[7,187]")));
}
TEST_F(SpmdPartitioningTest, PadAlongNonPartitionedDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[128,14,257] parameter(0), sharding={devices=[1,1,2]0,1}
%const = f32[] constant(0)
ROOT %pad = f32[128,17,257] pad(%param0, %const), padding=0_0x1_2x0_0,
sharding={devices=[1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Parameter(), op::Shape("f32[128,14,129]"));
EXPECT_THAT(root, AllOf(op::Pad(param0, op::Constant()),
op::Shape("f32[128,17,129]")));
}
TEST_F(SpmdPartitioningTest, PadAlongPartitionedDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[14,257] parameter(0), sharding={devices=[1,2]0,1}
%const = f32[] constant(0)
ROOT %pad = f32[14,259] pad(%param0, %const), padding=0_0x0_2,
sharding={devices=[1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Parameter(), op::Shape("f32[14,129]"));
auto after_halo_exchange =
AllOf(op::Shape("f32[14,130]"),
op::Concatenate(param0, op::CollectivePermute(op::Slice(param0))));
auto pad = AllOf(op::Shape("f32[14,131]"),
op::Pad(after_halo_exchange, op::Constant()));
EXPECT_THAT(root, op::Select(_, op::DynamicSlice(pad, op::Constant(), _), _));
}
TEST_F(SpmdPartitioningTest, PadAlongPartitionedDimensionWithInteriorPadding) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[7] parameter(0), sharding={devices=[2]0,1}
%param1 = f32[] parameter(1), sharding={replicated}
ROOT %pad = f32[22] pad(%param0, %param1), padding=2_1_2,
sharding={devices=[2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Parameter(), op::Shape("f32[4]"));
auto after_halo_exchange = AllOf(
op::Shape("f32[4]"),
op::DynamicSlice(
AllOf(op::Shape("f32[5]"),
op::Pad(AllOf(op::Shape("f32[4]"),
op::Concatenate(
op::CollectivePermute(op::Slice(param0)),
op::Slice(param0))),
op::Parameter(1))),
_));
auto pad = op::Pad(after_halo_exchange, op::Parameter(1));
EXPECT_THAT(root, op::DynamicSlice(pad, _));
}
TEST_F(SpmdPartitioningTest, PartialReplicatePad) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[11,7] parameter(0),
sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
%param1 = f32[] parameter(1), sharding={replicated}
ROOT %pad = f32[27,22] pad(%param0, %param1), padding=2_4_1x2_1_2,
sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Parameter(), op::Shape("f32[11,4]"));
auto after_halo_exchange = AllOf(
op::Shape("f32[11,4]"),
op::DynamicSlice(
AllOf(op::Shape("f32[11,5]"),
op::Pad(AllOf(op::Shape("f32[11,4]"),
op::Concatenate(
op::CollectivePermute(op::Slice(param0)),
op::Slice(param0))),
op::Parameter(1))),
op::Constant(), _));
auto pad = op::Pad(after_halo_exchange, op::Parameter(1));
EXPECT_THAT(root, AllOf(op::DynamicSlice(pad, op::Constant(), _),
op::Shape("f32[27,11]")));
}
TEST_F(SpmdPartitioningTest, SliceAlongNonPartitionedDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[128,14,257] parameter(0)
%param0.copy = f32[128,14,257] copy(%param0), sharding={devices=[1,1,2]0,1}
ROOT %slice = f32[128,11,257] slice(%param0.copy),
slice={[0:128:1], [2:13:1], [0:257:1]}, sharding={devices=[1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(
op::Copy(op::DynamicSlice(op::Pad(op::Parameter(), op::Constant()),
op::Constant(), op::Constant(), op::Reshape())),
op::Shape("f32[128,14,129]"));
EXPECT_THAT(root, AllOf(op::Slice(param0), op::Shape("f32[128,11,129]")));
}
TEST_F(SpmdPartitioningTest, SliceAlongPartitionedDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[128,14,257] parameter(0), sharding={devices=[1,1,2]0,1}
ROOT %slice = f32[63,14,251] slice(%param0),
slice={[2:128:2], [0:14:1], [5:256:1]}, sharding={devices=[1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Parameter(0), op::Shape("f32[128,14,129]"));
EXPECT_THAT(
root,
AllOf(op::Slice(AllOf(
op::DynamicSlice(
AllOf(op::Concatenate(
op::Slice(param0),
AllOf(op::CollectivePermute(op::Slice(param0)),
op::Shape("f32[128,14,2]"))),
op::Shape("f32[128,14,129]")),
op::Constant(), op::Constant(), op::Add()),
op::Shape("f32[128,14,126]"))),
op::Shape("f32[63,14,126]")));
}
TEST_F(SpmdPartitioningTest, SliceAlongPartitionedDimension2) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[4] parameter(0), sharding={devices=[4]0,1,2,3}
ROOT %slice = f32[1] slice(%param0),
slice={[3:4]}, sharding={devices=[4]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Parameter(0), op::Shape("f32[1]"));
EXPECT_THAT(root, AllOf(op::Copy(op::CollectivePermute(param0)),
op::Shape("f32[1]")));
}
TEST_F(SpmdPartitioningTest, MergedPadThenSliceShiftRight) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[4] parameter(0), sharding={devices=[4]0,1,2,3}
%init = f32[] constant(2.0)
%pad = f32[5] pad(%param0, %init), padding=1_0, sharding={devices=[4]0,1,2,3}
%copy = f32[5] copy(%pad), sharding={devices=[4]0,1,2,3}
%copy.1 = f32[5] copy(%copy), sharding={devices=[4]0,1,2,3}
ROOT %slice = f32[4] slice(%copy.1), slice={[0:4]}, sharding={devices=[4]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Parameter(0), op::Shape("f32[1]"));
EXPECT_THAT(root, AllOf(op::Select(_, op::CollectivePermute(param0), _),
op::Shape("f32[1]")));
}
// Same as above except that it uses zero padding, so there is no need for
// masking.
TEST_F(SpmdPartitioningTest, MergedPadThenSliceShiftRightNoMasking) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[4] parameter(0), sharding={devices=[4]0,1,2,3}
%init = f32[] constant(0)
%pad = f32[5] pad(%param0, %init), padding=1_0, sharding={devices=[4]0,1,2,3}
%copy = f32[5] copy(%pad), sharding={devices=[4]0,1,2,3}
%copy.1 = f32[5] copy(%copy), sharding={devices=[4]0,1,2,3}
ROOT %slice = f32[4] slice(%copy.1), slice={[0:4]}, sharding={devices=[4]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Parameter(0), op::Shape("f32[1]"));
EXPECT_THAT(root, AllOf(op::CollectivePermute(param0), op::Shape("f32[1]")));
}
TEST_F(SpmdPartitioningTest,
PartialReplicateSliceAlongNonPartitionedDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[128,14,257] parameter(0), sharding={devices=[1,1,2,2]0,1,2,3 last_tile_dim_replicate}
ROOT %slice = f32[128,11,257] slice(%param0),
slice={[0:128:1], [2:13:1], [0:257:1]}, sharding={devices=[1,1,2,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Parameter(), op::Shape("f32[128,14,129]"));
EXPECT_THAT(root, AllOf(op::Slice(param0), op::Shape("f32[128,11,129]")));
}
TEST_F(SpmdPartitioningTest, PartialReplicateSliceAlongPartitionedDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[128,14,257] parameter(0), sharding={devices=[1,1,2,2]0,1,2,3 last_tile_dim_replicate}
ROOT %slice = f32[63,14,251] slice(%param0),
slice={[2:128:2], [0:14:1], [5:256:1]}, sharding={devices=[1,1,2,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Parameter(), op::Shape("f32[128,14,129]"));
EXPECT_THAT(
root,
AllOf(
op::Slice(AllOf(
op::DynamicSlice(
AllOf(op::Concatenate(
op::Slice(param0),
AllOf(op::CollectivePermute(op::Slice(param0)),
op::Shape("f32[128,14,2]"))),
op::Shape("f32[128,14,129]")),
op::Constant(), op::Constant(),
op::Add(op::Multiply(op::Reshape(op::DynamicSlice(
op::Constant(), op::PartitionId())),
op::Constant()),
op::Constant())),
op::Shape("f32[128,14,126]"))),
op::Shape("f32[63,14,126]")));
}
TEST_F(SpmdPartitioningTest, SortAlongNonPartitionedDimension) {
absl::string_view hlo_string = R"(
HloModule module
ge {
p.0.lhs.1247 = f32[]{:T(256)} parameter(0), sharding={replicated}
bitcast-convert = s32[]{:T(256)} bitcast-convert(p.0.lhs.1247), sharding={replicated}
constant = s32[]{:T(256)} constant(0), sharding={replicated}
compare = pred[]{:T(256)E(32)} compare(bitcast-convert, constant), direction=LT, sharding={replicated}
constant.1 = u32[]{:T(256)} constant(2147483647), sharding={replicated}
bitcast-convert.1 = u32[]{:T(256)} bitcast-convert(p.0.lhs.1247), sharding={replicated}
subtract = u32[]{:T(256)} subtract(constant.1, bitcast-convert.1), sharding={replicated}
bitcast-convert.2 = s32[]{:T(256)} bitcast-convert(subtract), sharding={replicated}
select = s32[]{:T(256)} select(compare, bitcast-convert.2, bitcast-convert), sharding={replicated}
p.0.rhs.1248 = f32[]{:T(256)} parameter(1), sharding={replicated}
bitcast-convert.3 = s32[]{:T(256)} bitcast-convert(p.0.rhs.1248), sharding={replicated}
compare.1 = pred[]{:T(256)E(32)} compare(bitcast-convert.3, constant), direction=LT, sharding={replicated}
bitcast-convert.4 = u32[]{:T(256)} bitcast-convert(p.0.rhs.1248), sharding={replicated}
subtract.1 = u32[]{:T(256)} subtract(constant.1, bitcast-convert.4), sharding={replicated}
bitcast-convert.5 = s32[]{:T(256)} bitcast-convert(subtract.1), sharding={replicated}
select.1 = s32[]{:T(256)} select(compare.1, bitcast-convert.5, bitcast-convert.3), sharding={replicated}
compare.2 = pred[]{:T(256)E(32)} compare(select, select.1), direction=GT, sharding={replicated}
compare.258 = pred[]{:T(256)E(32)} compare(select.1, select), direction=GT, sharding={replicated}
compare.259 = pred[]{:T(256)E(32)} compare(compare.2, compare.258), direction=EQ, sharding={replicated}
p.1.lhs.1249 = s32[]{:T(256)} parameter(2), sharding={replicated}
p.1.rhs.1250 = s32[]{:T(256)} parameter(3), sharding={replicated}
compare.260 = pred[]{:T(256)E(32)} compare(p.1.lhs.1249, p.1.rhs.1250), direction=LT, sharding={replicated}
ROOT select.86 = pred[]{:T(256)E(32)} select(compare.259, compare.260, compare.2), sharding={replicated}
}
ENTRY entry {
%param0 = f32[128,14,257] parameter(0)
%param0.copy = f32[128,14,257] copy(%param0), sharding={devices=[1,2,1]0,1}
%param1 = s32[128,14,257] parameter(1)
%param1.copy = s32[128,14,257] copy(%param1), sharding={devices=[1,2,1]0,1}
ROOT %sort.6 = (f32[128,14,257]{2,1,0:T(8,128)}, s32[128,14,257]{2,1,0:T(8,128)})
sort(%param0.copy, %param1.copy), dimensions={2}, is_stable=true,
to_apply=%ge, sharding={{devices=[1,2,1]0,1},{devices=[1,2,1]0,1}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 =
AllOf(op::Copy(op::DynamicSlice(op::Parameter(0), op::Constant(),
op::Reshape(), op::Constant())),
op::Shape("f32[128,7,257]"));
auto param1 =
AllOf(op::Copy(op::DynamicSlice(op::Parameter(1), op::Constant(),
op::Reshape(), op::Constant())),
op::Shape("s32[128,7,257]"));
EXPECT_THAT(root, AllOf(op::Sort(param0, param1),
op::Shape("(f32[128,7,257], s32[128,7,257])")));
}
TEST_F(SpmdPartitioningTest, PartitionCustomCall) {
absl::string_view hlo_string = R"(
HloModule cluster_2013453984438090939__.47
ENTRY %cluster_2013453984438090939__.47
(arg_tuple.1: ()) -> (bf16[2,2000], s32[2,2000]) {
%arg_tuple.1 = bf16[2,209664] parameter(0)
%copy.arg_tuple.1 = bf16[2,209664] copy(%arg_tuple.1), sharding={devices=[1,2]0,1}
%custom-call = (bf16[2,2000]{1,0}, s32[2,2000]{1,0})
custom-call(bf16[2,209664]{1,0} %copy.arg_tuple.1), custom_call_target="TopK"
%get-tuple-element = bf16[2,2000]{1,0}
get-tuple-element((bf16[2,2000]{1,0}, s32[2,2000]{1,0}) %custom-call),
index=0, sharding={replicated}
%get-tuple-element.1 = s32[2,2000]{1,0} get-tuple-element((bf16[2,2000]{1,0},
s32[2,2000]{1,0}) %custom-call), index=1, sharding={replicated}
ROOT %tuple.46 = (bf16[2,2000]{1,0}, s32[2,2000]{1,0})
tuple(bf16[2,2000]{1,0} %get-tuple-element, s32[2,2000]{1,0}
%get-tuple-element.1), sharding={{replicated}, {replicated}},
metadata={op_name="XLA_Retvals"}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto custom_call = FindInstruction(module.get(), "custom-call.1");
EXPECT_EQ(custom_call->operand(0)->shape().dimensions(1), 104832);
auto sort = FindInstruction(module.get(), "sort");
EXPECT_EQ(sort->operand(0)->shape().dimensions(1), 4000);
EXPECT_EQ(sort->operand(1)->shape().dimensions(1), 4000);
}
TEST_F(SpmdPartitioningTest, PartitionCustomCall_TwoPartitionedDims) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[8,32128] parameter(0)
%copy.0 = f32[8,32128] copy(%param0),
sharding={devices=[4,2]0,1,2,3,4,5,6,7}
%custom-call = (f32[8,2]{1,0}, s32[8,2]{1,0})
custom-call(%copy.0), custom_call_target="TopK"
%get-tuple-element = f32[8,2]{1,0}
get-tuple-element((f32[8,2]{1,0}, s32[8,2]{1,0}) %custom-call), index=0,
sharding={devices=[4,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
%get-tuple-element.1 = s32[8,2]{1,0}
get-tuple-element((f32[8,2]{1,0}, s32[8,2]{1,0}) %custom-call), index=1,
sharding={devices=[4,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %tuple = (f32[8,2]{1,0}, s32[8,2]{1,0})
tuple(%get-tuple-element, %get-tuple-element.1),
sharding={{replicated}, {replicated}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto custom_call = FindInstruction(module.get(), "custom-call.1");
EXPECT_EQ(custom_call->operand(0)->shape().dimensions(1), 16064);
auto sort = FindInstruction(module.get(), "sort");
EXPECT_EQ(sort->operand(0)->shape().dimensions(0), 2);
EXPECT_EQ(sort->operand(0)->shape().dimensions(1), 4);
EXPECT_EQ(sort->operand(1)->shape().dimensions(0), 2);
EXPECT_EQ(sort->operand(1)->shape().dimensions(1), 4);
}
TEST_F(SpmdPartitioningTest, PartitionSortInTopK) {
absl::string_view hlo_string = R"(
HloModule module
%compare-greater-than.8 (p.0.lhs.9: bf16[], p.0.rhs.10: bf16[], p.1.lhs.11:
s32[], p.1.rhs.12: s32[]) -> pred[] {
%p.1.lhs.11 = s32[] parameter(2)
%p.1.rhs.12 = s32[] parameter(3)
%p.0.lhs.9 = bf16[] parameter(0)
%convert.13 = f32[] convert(bf16[] %p.0.lhs.9)
%bitcast-convert.16 = s32[] bitcast-convert(f32[] %convert.13)
%constant.20 = s32[] constant(0)
%compare.21 = pred[] compare(s32[] %bitcast-convert.16, s32[] %constant.20),
direction=LT
%constant.15 = u32[] constant(2147483647)
%bitcast-convert.17 = u32[] bitcast-convert(f32[] %convert.13)
%subtract.18 = u32[] subtract(u32[] %constant.15, u32[] %bitcast-convert.17)
%bitcast-convert.19 = s32[] bitcast-convert(u32[] %subtract.18)
%select.22 = s32[] select(pred[] %compare.21, s32[] %bitcast-convert.19, s32[]
%bitcast-convert.16)
%p.0.rhs.10 = bf16[] parameter(1)
%convert.14 = f32[] convert(bf16[] %p.0.rhs.10)
%bitcast-convert.24 = s32[] bitcast-convert(f32[] %convert.14)
%constant.28 = s32[] constant(0)
%compare.29 = pred[] compare(s32[] %bitcast-convert.24, s32[] %constant.28),
direction=LT
%constant.23 = u32[] constant(2147483647)
%bitcast-convert.25 = u32[] bitcast-convert(f32[] %convert.14)
%subtract.26 = u32[] subtract(u32[] %constant.23, u32[] %bitcast-convert.25)
%bitcast-convert.27 = s32[] bitcast-convert(u32[] %subtract.26)
%select.30 = s32[] select(pred[] %compare.29, s32[] %bitcast-convert.27, s32[]
%bitcast-convert.24)
ROOT %compare.31 = pred[] compare(s32[] %select.22, s32[] %select.30),
direction=GT
}
ENTRY entry
(arg_tuple.1: ()) -> (bf16[2,2000], s32[2,2000]) {
%arg_tuple.1 = bf16[2,209664] parameter(0)
%copy.arg_tuple.1 = bf16[2,209664] copy(%arg_tuple.1), sharding={devices=[1,2]0,1}
%iota.7 = s32[2,209664] iota(), iota_dimension=1,
metadata={op_type="TopKV2" op_name="TopKV2"}
%sort.32 = (bf16[2,209664], s32[2,209664])
sort(bf16[2,209664] %copy.arg_tuple.1, s32[2,209664] %iota.7),
dimensions={1}, is_stable=true, to_apply=%compare-greater-than.8,
metadata={op_type="TopKV2" op_name="TopKV2"}
%get-tuple-element.33 = bf16[2,209664]
get-tuple-element((bf16[2,209664], s32[2,209664]) %sort.32),
index=0, metadata={op_type="TopKV2" op_name="TopKV2"}
%slice.34 = bf16[2,2000] slice(bf16[2,209664]
%get-tuple-element.33), slice={[0:2], [0:2000]},
metadata={op_type="TopKV2" op_name="TopKV2"}
%get-tuple-element.35 = s32[2,209664]
get-tuple-element((bf16[2,209664], s32[2,209664]) %sort.32),
index=1, metadata={op_type="TopKV2" op_name="TopKV2"}
%slice.36 = s32[2,2000] slice(s32[2,209664]
%get-tuple-element.35), slice={[0:2], [0:2000]},
metadata={op_type="TopKV2" op_name="TopKV2"}
ROOT %tuple.46 = (bf16[2,2000], s32[2,2000])
tuple(bf16[2,2000] %slice.34, s32[2,2000]
%slice.36), sharding={{replicated}, {replicated}},
metadata={op_name="XLA_Retvals"}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto sort = FindInstruction(module.get(), "sort");
EXPECT_EQ(sort->operand(0)->shape().dimensions(1), 104832);
EXPECT_EQ(sort->operand(1)->shape().dimensions(1), 104832);
auto final_sort = FindInstruction(module.get(), "sort.1");
EXPECT_EQ(final_sort->operand(0)->shape().dimensions(1), 4000);
EXPECT_EQ(final_sort->operand(1)->shape().dimensions(1), 4000);
}
TEST_F(SpmdPartitioningTest, PartitionSortInTopKWhenComparisonWithSelect) {
absl::string_view hlo_string = R"(
HloModule module
%compare-greater-than.8 (p.0.lhs.2566: bf16[],
p.0.rhs.2567: bf16[], p.1.lhs.2586: s32[], p.1.rhs.2587: s32[]) -> pred[] {
%p.0.lhs.2566 = bf16[] parameter(0)
%convert.164 = f32[] convert(bf16[] %p.0.lhs.2566)
%bitcast-convert.48 = s32[] bitcast-convert(f32[] %convert.164)
%constant.285 = s32[] constant(0)
%compare.84 = pred[] compare(s32[] %bitcast-convert.48, s32[] %constant.285),
direction=LT
%constant.286 = u32[] constant(2147483647)
%bitcast-convert.49 = u32[] bitcast-convert(f32[] %convert.164)
%subtract.84 = u32[] subtract(u32[] %constant.286, u32[] %bitcast-convert.49)
%bitcast-convert.50 = s32[] bitcast-convert(u32[] %subtract.84)
%select.40 = s32[] select(pred[] %compare.84, s32[] %bitcast-convert.50,
s32[] %bitcast-convert.48)
%p.0.rhs.2567 = bf16[] parameter(1)
%convert.165 = f32[] convert(bf16[] %p.0.rhs.2567)
%bitcast-convert.51 = s32[] bitcast-convert(f32[] %convert.165)
%compare.85 = pred[] compare(s32[] %bitcast-convert.51, s32[] %constant.285),
direction=LT
%bitcast-convert.52 = u32[] bitcast-convert(f32[] %convert.165)
%subtract.85 = u32[] subtract(u32[] %constant.286, u32[] %bitcast-convert.52)
%bitcast-convert.53 = s32[] bitcast-convert(u32[] %subtract.85)
%select.41 = s32[] select(pred[] %compare.85, s32[] %bitcast-convert.53,
s32[] %bitcast-convert.51)
%compare.86 = pred[] compare(s32[] %select.40, s32[] %select.41), direction=GT
%compare.1645 = pred[] compare(s32[] %select.41, s32[] %select.40), direction=GT
%compare.1646 = pred[] compare(pred[] %compare.86, pred[] %compare.1645),
direction=EQ
%p.1.lhs.2586 = s32[] parameter(2)
%p.1.rhs.2587 = s32[] parameter(3)
%compare.1647 = pred[] compare(s32[] %p.1.lhs.2586, s32[] %p.1.rhs.2587),
direction=LT
ROOT %select.1054 = pred[] select(pred[] %compare.1646, pred[] %compare.1647,
pred[] %compare.86)
}
ENTRY entry
(arg_tuple.1: ()) -> (bf16[2,2000], s32[2,2000]) {
%arg_tuple.1 = bf16[2,209664] parameter(0)
%copy.arg_tuple.1 = bf16[2,209664] copy(%arg_tuple.1), sharding={devices=[1,2]0,1}
%iota.7 = s32[2,209664] iota(), iota_dimension=1,
metadata={op_type="TopKV2" op_name="TopKV2"}
%sort.32 = (bf16[2,209664], s32[2,209664])
sort(bf16[2,209664] %copy.arg_tuple.1, s32[2,209664] %iota.7),
dimensions={1}, is_stable=true, to_apply=%compare-greater-than.8,
metadata={op_type="TopKV2" op_name="TopKV2"}
%get-tuple-element.33 = bf16[2,209664]
get-tuple-element((bf16[2,209664], s32[2,209664]) %sort.32),
index=0, metadata={op_type="TopKV2" op_name="TopKV2"}
%slice.34 = bf16[2,2000] slice(bf16[2,209664]
%get-tuple-element.33), slice={[0:2], [0:2000]},
metadata={op_type="TopKV2" op_name="TopKV2"}
%get-tuple-element.35 = s32[2,209664]
get-tuple-element((bf16[2,209664], s32[2,209664]) %sort.32),
index=1, metadata={op_type="TopKV2" op_name="TopKV2"}
%slice.36 = s32[2,2000] slice(s32[2,209664]
%get-tuple-element.35), slice={[0:2], [0:2000]},
metadata={op_type="TopKV2" op_name="TopKV2"}
ROOT %tuple.46 = (bf16[2,2000], s32[2,2000])
tuple(bf16[2,2000] %slice.34, s32[2,2000]
%slice.36), sharding={{replicated}, {replicated}},
metadata={op_name="XLA_Retvals"}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto sort = FindInstruction(module.get(), "sort");
EXPECT_EQ(sort->operand(0)->shape().dimensions(1), 104832);
EXPECT_EQ(sort->operand(1)->shape().dimensions(1), 104832);
auto final_sort = FindInstruction(module.get(), "sort.1");
EXPECT_EQ(final_sort->operand(0)->shape().dimensions(1), 4000);
EXPECT_EQ(final_sort->operand(1)->shape().dimensions(1), 4000);
}
TEST_F(SpmdPartitioningTest, NoPartitionSortInTopKWhenSecondOperandIsNotIota) {
absl::string_view hlo_string = R"(
HloModule module
%compare-greater-than.8 (p.0.lhs.2566: bf16[],
p.0.rhs.2567: bf16[], p.1.lhs.2586: s32[], p.1.rhs.2587: s32[]) -> pred[] {
%p.0.lhs.2566 = bf16[] parameter(0)
%convert.164 = f32[] convert(bf16[] %p.0.lhs.2566)
%bitcast-convert.48 = s32[] bitcast-convert(f32[] %convert.164)
%constant.285 = s32[] constant(0)
%compare.84 = pred[] compare(s32[] %bitcast-convert.48, s32[] %constant.285),
direction=LT
%constant.286 = u32[] constant(2147483647)
%bitcast-convert.49 = u32[] bitcast-convert(f32[] %convert.164)
%subtract.84 = u32[] subtract(u32[] %constant.286, u32[] %bitcast-convert.49)
%bitcast-convert.50 = s32[] bitcast-convert(u32[] %subtract.84)
%select.40 = s32[] select(pred[] %compare.84, s32[] %bitcast-convert.50,
s32[] %bitcast-convert.48)
%p.0.rhs.2567 = bf16[] parameter(1)
%convert.165 = f32[] convert(bf16[] %p.0.rhs.2567)
%bitcast-convert.51 = s32[] bitcast-convert(f32[] %convert.165)
%compare.85 = pred[] compare(s32[] %bitcast-convert.51, s32[] %constant.285),
direction=LT
%bitcast-convert.52 = u32[] bitcast-convert(f32[] %convert.165)
%subtract.85 = u32[] subtract(u32[] %constant.286, u32[] %bitcast-convert.52)
%bitcast-convert.53 = s32[] bitcast-convert(u32[] %subtract.85)
%select.41 = s32[] select(pred[] %compare.85, s32[] %bitcast-convert.53,
s32[] %bitcast-convert.51)
%compare.86 = pred[] compare(s32[] %select.40, s32[] %select.41), direction=GT
%compare.1645 = pred[] compare(s32[] %select.41, s32[] %select.40), direction=GT
%compare.1646 = pred[] compare(pred[] %compare.86, pred[] %compare.1645),
direction=EQ
%p.1.lhs.2586 = s32[] parameter(2)
%p.1.rhs.2587 = s32[] parameter(3)
%compare.1647 = pred[] compare(s32[] %p.1.lhs.2586, s32[] %p.1.rhs.2587),
direction=LT
ROOT %select.1054 = pred[] select(pred[] %compare.1646, pred[] %compare.1647,
pred[] %compare.86)
}
ENTRY entry {
%arg_tuple.1 = bf16[2,209664] parameter(0)
%arg_tuple.2 = s32[2,209664] parameter(1)
%copy.arg_tuple.1 = bf16[2,209664] copy(%arg_tuple.1), sharding={devices=[1,2]0,1}
%sort.32 = (bf16[2,209664], s32[2,209664])
sort(bf16[2,209664] %copy.arg_tuple.1, s32[2,209664] %arg_tuple.2),
dimensions={1}, is_stable=true, to_apply=%compare-greater-than.8,
metadata={op_type="TopKV2" op_name="TopKV2"}
%get-tuple-element.33 = bf16[2,209664]
get-tuple-element((bf16[2,209664], s32[2,209664]) %sort.32),
index=0, metadata={op_type="TopKV2" op_name="TopKV2"}
%slice.34 = bf16[2,2000] slice(bf16[2,209664]
%get-tuple-element.33), slice={[0:2], [0:2000]},
metadata={op_type="TopKV2" op_name="TopKV2"}
%get-tuple-element.35 = s32[2,209664]
get-tuple-element((bf16[2,209664], s32[2,209664]) %sort.32),
index=1, metadata={op_type="TopKV2" op_name="TopKV2"}
%slice.36 = s32[2,2000] slice(s32[2,209664]
%get-tuple-element.35), slice={[0:2], [0:2000]},
metadata={op_type="TopKV2" op_name="TopKV2"}
ROOT %tuple.46 = (bf16[2,2000], s32[2,2000])
tuple(bf16[2,2000] %slice.34, s32[2,2000]
%slice.36), sharding={{replicated}, {replicated}},
metadata={op_name="XLA_Retvals"}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto sort = FindInstruction(module.get(), "sort");
EXPECT_EQ(sort->operand(0)->shape().dimensions(1), 209664);
EXPECT_EQ(sort->operand(1)->shape().dimensions(1), 209664);
}
TEST_F(SpmdPartitioningTest, NoPartitionSortInTopKWhenNoPartitionInSortDim) {
absl::string_view hlo_string = R"(
HloModule module
%compare-greater-than.8 (p.0.lhs.2566: bf16[],
p.0.rhs.2567: bf16[], p.1.lhs.2586: s32[], p.1.rhs.2587: s32[]) -> pred[] {
%p.0.lhs.2566 = bf16[] parameter(0)
%convert.164 = f32[] convert(bf16[] %p.0.lhs.2566)
%bitcast-convert.48 = s32[] bitcast-convert(f32[] %convert.164)
%constant.285 = s32[] constant(0)
%compare.84 = pred[] compare(s32[] %bitcast-convert.48, s32[] %constant.285),
direction=LT
%constant.286 = u32[] constant(2147483647)
%bitcast-convert.49 = u32[] bitcast-convert(f32[] %convert.164)
%subtract.84 = u32[] subtract(u32[] %constant.286, u32[] %bitcast-convert.49)
%bitcast-convert.50 = s32[] bitcast-convert(u32[] %subtract.84)
%select.40 = s32[] select(pred[] %compare.84, s32[] %bitcast-convert.50,
s32[] %bitcast-convert.48)
%p.0.rhs.2567 = bf16[] parameter(1)
%convert.165 = f32[] convert(bf16[] %p.0.rhs.2567)
%bitcast-convert.51 = s32[] bitcast-convert(f32[] %convert.165)
%compare.85 = pred[] compare(s32[] %bitcast-convert.51, s32[] %constant.285),
direction=LT
%bitcast-convert.52 = u32[] bitcast-convert(f32[] %convert.165)
%subtract.85 = u32[] subtract(u32[] %constant.286, u32[] %bitcast-convert.52)
%bitcast-convert.53 = s32[] bitcast-convert(u32[] %subtract.85)
%select.41 = s32[] select(pred[] %compare.85, s32[] %bitcast-convert.53,
s32[] %bitcast-convert.51)
%compare.86 = pred[] compare(s32[] %select.40, s32[] %select.41), direction=GT
%compare.1645 = pred[] compare(s32[] %select.41, s32[] %select.40), direction=GT
%compare.1646 = pred[] compare(pred[] %compare.86, pred[] %compare.1645),
direction=EQ
%p.1.lhs.2586 = s32[] parameter(2)
%p.1.rhs.2587 = s32[] parameter(3)
%compare.1647 = pred[] compare(s32[] %p.1.lhs.2586, s32[] %p.1.rhs.2587),
direction=LT
ROOT %select.1054 = pred[] select(pred[] %compare.1646, pred[] %compare.1647,
pred[] %compare.86)
}
ENTRY entry
(arg_tuple.1: ()) -> (bf16[2,2000], s32[2,2000]) {
%arg_tuple.1 = bf16[2,209664] parameter(0)
%copy.arg_tuple.1 = bf16[2,209664] copy(%arg_tuple.1), sharding={devices=[2,1]0,1}
%iota.7 = s32[2,209664] iota(), iota_dimension=1,
metadata={op_type="TopKV2" op_name="TopKV2"}
%sort.32 = (bf16[2,209664], s32[2,209664])
sort(bf16[2,209664] %copy.arg_tuple.1, s32[2,209664] %iota.7),
dimensions={1}, is_stable=true, to_apply=%compare-greater-than.8,
metadata={op_type="TopKV2" op_name="TopKV2"}
%get-tuple-element.33 = bf16[2,209664]
get-tuple-element((bf16[2,209664], s32[2,209664]) %sort.32),
index=0, metadata={op_type="TopKV2" op_name="TopKV2"}
%slice.34 = bf16[2,2000] slice(bf16[2,209664]
%get-tuple-element.33), slice={[0:2], [0:2000]},
metadata={op_type="TopKV2" op_name="TopKV2"}
%get-tuple-element.35 = s32[2,209664]
get-tuple-element((bf16[2,209664], s32[2,209664]) %sort.32),
index=1, metadata={op_type="TopKV2" op_name="TopKV2"}
%slice.36 = s32[2,2000] slice(s32[2,209664]
%get-tuple-element.35), slice={[0:2], [0:2000]},
metadata={op_type="TopKV2" op_name="TopKV2"}
ROOT %tuple.46 = (bf16[2,2000], s32[2,2000])
tuple(bf16[2,2000] %slice.34, s32[2,2000]
%slice.36), sharding={{replicated}, {replicated}},
metadata={op_name="XLA_Retvals"}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto sort = FindInstruction(module.get(), "sort");
EXPECT_EQ(sort->operand(0)->shape().dimensions(1), 209664);
EXPECT_EQ(sort->operand(1)->shape().dimensions(1), 209664);
}
TEST_F(SpmdPartitioningTest, NoPartitionSortInTopKWhenSliceInOtherDim) {
absl::string_view hlo_string = R"(
HloModule module
%compare-greater-than.8 (p.0.lhs.2566: bf16[],
p.0.rhs.2567: bf16[], p.1.lhs.2586: s32[], p.1.rhs.2587: s32[]) -> pred[] {
%p.0.lhs.2566 = bf16[] parameter(0)
%convert.164 = f32[] convert(bf16[] %p.0.lhs.2566)
%bitcast-convert.48 = s32[] bitcast-convert(f32[] %convert.164)
%constant.285 = s32[] constant(0)
%compare.84 = pred[] compare(s32[] %bitcast-convert.48, s32[] %constant.285),
direction=LT
%constant.286 = u32[] constant(2147483647)
%bitcast-convert.49 = u32[] bitcast-convert(f32[] %convert.164)
%subtract.84 = u32[] subtract(u32[] %constant.286, u32[] %bitcast-convert.49)
%bitcast-convert.50 = s32[] bitcast-convert(u32[] %subtract.84)
%select.40 = s32[] select(pred[] %compare.84, s32[] %bitcast-convert.50,
s32[] %bitcast-convert.48)
%p.0.rhs.2567 = bf16[] parameter(1)
%convert.165 = f32[] convert(bf16[] %p.0.rhs.2567)
%bitcast-convert.51 = s32[] bitcast-convert(f32[] %convert.165)
%compare.85 = pred[] compare(s32[] %bitcast-convert.51, s32[] %constant.285),
direction=LT
%bitcast-convert.52 = u32[] bitcast-convert(f32[] %convert.165)
%subtract.85 = u32[] subtract(u32[] %constant.286, u32[] %bitcast-convert.52)
%bitcast-convert.53 = s32[] bitcast-convert(u32[] %subtract.85)
%select.41 = s32[] select(pred[] %compare.85, s32[] %bitcast-convert.53,
s32[] %bitcast-convert.51)
%compare.86 = pred[] compare(s32[] %select.40, s32[] %select.41), direction=GT
%compare.1645 = pred[] compare(s32[] %select.41, s32[] %select.40), direction=GT
%compare.1646 = pred[] compare(pred[] %compare.86, pred[] %compare.1645),
direction=EQ
%p.1.lhs.2586 = s32[] parameter(2)
%p.1.rhs.2587 = s32[] parameter(3)
%compare.1647 = pred[] compare(s32[] %p.1.lhs.2586, s32[] %p.1.rhs.2587),
direction=LT
ROOT %select.1054 = pred[] select(pred[] %compare.1646, pred[] %compare.1647,
pred[] %compare.86)
}
ENTRY entry {
%arg_tuple.1 = bf16[2,209664] parameter(0)
%copy.arg_tuple.1 = bf16[2,209664] copy(%arg_tuple.1), sharding={devices=[1,2]0,1}
%iota.7 = s32[2,209664] iota(), iota_dimension=1,
metadata={op_type="TopKV2" op_name="TopKV2"}
%sort.32 = (bf16[2,209664], s32[2,209664])
sort(bf16[2,209664] %copy.arg_tuple.1, s32[2,209664] %iota.7),
dimensions={1}, is_stable=true, to_apply=%compare-greater-than.8,
metadata={op_type="TopKV2" op_name="TopKV2"}
%get-tuple-element.33 = bf16[2,209664]
get-tuple-element((bf16[2,209664], s32[2,209664]) %sort.32),
index=0, metadata={op_type="TopKV2" op_name="TopKV2"}
%slice.34 = bf16[1,209664] slice(bf16[2,209664]
%get-tuple-element.33), slice={[0:1], [0:209664]},
metadata={op_type="TopKV2" op_name="TopKV2"}
%get-tuple-element.35 = s32[2,209664]
get-tuple-element((bf16[2,209664], s32[2,209664]) %sort.32),
index=1, metadata={op_type="TopKV2" op_name="TopKV2"}
%slice.36 = s32[1,209664] slice(s32[2,209664]
%get-tuple-element.35), slice={[0:1], [0:209664]},
metadata={op_type="TopKV2" op_name="TopKV2"}
ROOT %tuple.46 = (bf16[1,209664], s32[1,209664])
tuple(bf16[1,209664] %slice.34, s32[1,209664]
%slice.36), sharding={{replicated}, {replicated}},
metadata={op_name="XLA_Retvals"}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto sort = FindInstruction(module.get(), "sort");
EXPECT_EQ(sort->operand(0)->shape().dimensions(1), 209664);
EXPECT_EQ(sort->operand(1)->shape().dimensions(1), 209664);
}
TEST_F(SpmdPartitioningTest, ShardableTranspose) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[16,38,38,4] parameter(0)
%param0.copy = f32[16,38,38,4] copy(%param0), sharding={devices=[1,2,1,1]0,1}
ROOT %transpose = f32[16,4,38,38] transpose(%param0.copy),
dimensions={0,3,1,2}, sharding={devices=[1,1,2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[16,19,38,4]"));
EXPECT_THAT(root, AllOf(op::Transpose(param0), op::Shape("f32[16,4,19,38]")));
}
TEST_F(SpmdPartitioningTest, MultiDimensionShardedTranspose) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[16,38,38,4] parameter(0)
%param0.copy = f32[16,38,38,4] copy(%param0),
sharding={devices=[4,2,1,1]0,1,2,3,4,5,6,7}
ROOT %transpose = f32[38,4,16,38] transpose(%param0.copy),
dimensions={1,3,0,2}, sharding={devices=[2,1,4,1]0,2,4,6,1,3,5,7}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[4,19,38,4]"));
EXPECT_THAT(root, AllOf(op::Transpose(param0), op::Shape("f32[19,4,4,38]")));
}
TEST_F(SpmdPartitioningTest, NonShardableTranspose) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[16,38,38,4] parameter(0)
%param0.copy = f32[16,38,38,4] copy(%param0), sharding={devices=[1,2,1,1]0,1}
ROOT %transpose = f32[16,4,38,38] transpose(%param0.copy),
dimensions={0,3,1,2}, sharding={devices=[1,2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto resahrd = AllOf(op::Reshape(op::Transpose(op::Reshape(op::AllToAll()))),
op::Shape("f32[16,38,38,2]"));
EXPECT_THAT(root, AllOf(op::Transpose(), op::Shape("f32[16,2,38,38]")));
}
TEST_F(SpmdPartitioningTest, PartialReplicateShardableTranspose) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[16,38,38,4] parameter(0)
%param0.copy = f32[16,38,38,4] copy(%param0),
sharding={devices=[1,2,1,1,2]0,1,2,3 last_tile_dim_replicate}
ROOT %transpose = f32[16,4,38,38] transpose(%param0.copy),
dimensions={0,3,1,2},
sharding={devices=[1,1,2,1,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[16,19,38,4]"));
EXPECT_THAT(root, AllOf(op::Transpose(param0), op::Shape("f32[16,4,19,38]")));
}
TEST_F(SpmdPartitioningTest, PartialReplicateNonShardableTranspose) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[16,38,38,4] parameter(0)
%param0.copy = f32[16,38,38,4] copy(%param0),
sharding={devices=[1,2,1,1,2]0,1,2,3 last_tile_dim_replicate}
ROOT %transpose = f32[16,4,38,38] transpose(%param0.copy),
dimensions={0,3,1,2},
sharding={devices=[1,2,1,1,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto resahrd = AllOf(op::Reshape(op::Transpose(op::Reshape(op::AllToAll()))),
op::Shape("f32[16,38,38,2]"));
EXPECT_THAT(root, AllOf(op::Transpose(), op::Shape("f32[16,2,38,38]")));
}
TEST_F(SpmdPartitioningTest, PartialReplicateMultiDimensionShardedTranspose) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[16,38,38,4] parameter(0)
%param0.copy = f32[16,38,38,4] copy(%param0),
sharding={devices=[2,2,1,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %transpose = f32[38,4,16,38] transpose(%param0.copy),
dimensions={1,3,0,2},
sharding={devices=[2,1,2,1,2]0,1,4,5,2,3,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[8,19,38,4]"));
EXPECT_THAT(root, AllOf(op::Transpose(param0), op::Shape("f32[19,4,8,38]")));
}
TEST_F(SpmdPartitioningTest, ShardableReshape) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[38,38,324] parameter(0)
%param0.copy = f32[38,38,324] copy(%param0), sharding={devices=[2,1,1]0,1}
ROOT %reshape = f32[38,38,4,81] reshape(%param0.copy),
sharding={devices=[2,1,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 =
AllOf(op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[19,38,324]"));
EXPECT_THAT(root, AllOf(op::Reshape(param0), op::Shape("f32[19,38,4,81]")));
}
TEST_F(SpmdPartitioningTest, ReshapeWithReshard) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[38,38,324] parameter(0), sharding={devices=[2,1,1]0,1}
ROOT %reshape = f32[38,38,4,81] reshape(%param0),
sharding={devices=[1,2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto input_reshard =
op::Reshape(op::Transpose(op::AllToAll(op::Reshape(op::Parameter(0)))));
EXPECT_THAT(root,
AllOf(op::Reshape(input_reshard), op::Shape("f32[38,19,4,81]")));
}
TEST_F(SpmdPartitioningTest, ReshapeWithReshard2) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[38,38,324] parameter(0), sharding={devices=[2,1,1]0,1}
ROOT %reshape = f32[38,38,2,162] reshape(%param0),
sharding={devices=[1,1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto local_reshape =
AllOf(op::Reshape(op::Parameter(0)), op::Shape("f32[19,38,2,162]"));
EXPECT_THAT(root, AllOf(op::Shape("f32[38,38,2,81]"),
op::Reshape(op::Transpose(
op::AllToAll(op::Reshape(local_reshape))))));
}
TEST_F(SpmdPartitioningTest, PartialReplicateShardableReshape) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[38,38,324] parameter(0)
%param0.copy = f32[38,38,324] copy(%param0),
sharding={devices=[2,1,1,2]0,1,2,3 last_tile_dim_replicate}
ROOT %reshape = f32[38,38,4,81] reshape(%param0.copy),
sharding={devices=[2,1,1,1,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 =
AllOf(op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[19,38,324]"));
EXPECT_THAT(root, AllOf(op::Reshape(param0), op::Shape("f32[19,38,4,81]")));
}
TEST_F(SpmdPartitioningTest, ReshapeMergeDimsWithHaloExchange) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%input = s32[2,3,7,10] parameter(0), sharding={devices=[1,1,2,1]0,1}
ROOT %reshape = s32[3,2,1,14,5] reshape(%input),
sharding={devices=[1,1,1,2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto reshape =
AllOf(op::Reshape(op::Parameter(0)), op::Shape("s32[3,2,1,8,5]"));
auto halo = op::CollectivePermute(op::Slice(reshape));
auto exchanged = op::DynamicSlice(op::Concatenate(halo, op::Slice(reshape)),
_, _, _, _, _);
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(exchanged, op::Shape("s32[3,2,1,7,5]")));
}
TEST_F(SpmdPartitioningTest, PartialReplicateReshapeMergeDimsWithHaloExchange) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%input = s32[2,3,7,10] parameter(0),
sharding={devices=[1,1,2,1,2]0,1,2,3 last_tile_dim_replicate}
ROOT %reshape = s32[3,2,1,14,5] reshape(%input),
sharding={devices=[1,1,1,2,1,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto reshape =
AllOf(op::Reshape(op::Parameter(0)), op::Shape("s32[3,2,1,8,5]"));
auto halo = op::CollectivePermute(op::Slice(reshape));
auto exchanged = op::DynamicSlice(op::Concatenate(halo, op::Slice(reshape)),
_, _, _, _, _);
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(exchanged, op::Shape("s32[3,2,1,7,5]")));
}
// Produces an invalid module after transformation.
TEST_F(SpmdPartitioningTest, InceptionV3_4_way_ReduceWindowDilated) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
%param0 = f32[128,5,5,768] parameter(0)
%param0.copy = f32[128,5,5,768] copy(%param0),
sharding={devices=[1,4,1,1]0,1,2,3}
%constant.1 = f32[] constant(0), sharding={replicated}
ROOT %rw = f32[128,17,17,768] reduce-window(%param0.copy, %constant.1),
window={size=1x5x5x1 pad=0_0x4_4x4_4x0_0 lhs_dilate=1x3x3x1},
to_apply=sum, sharding={devices=[1,4,1,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto input_shard = op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(0), op::Constant()), op::Constant(), op::Reshape(),
op::Constant(), op::Constant()));
auto id_mul4_add1 =
op::Add(op::Multiply(op::Reshape(), op::Constant()), op::Constant());
auto id_mul5 = op::Multiply(op::Reshape(), op::Constant());
auto id_mul5_add1_div3 =
op::Divide(op::Add(id_mul5, op::Constant()), op::Constant());
auto before_masking = AllOf(
op::Shape("f32[128,3,5,768]"),
op::DynamicSlice(
AllOf(
op::Shape("f32[128,4,5,768]"),
op::Concatenate(op::CollectivePermute(input_shard), input_shard)),
op::Constant(),
op::Subtract(op::Constant(),
op::Subtract(id_mul4_add1, id_mul5_add1_div3)),
op::Constant(), op::Constant()));
auto masked = op::Select(
op::And(op::Compare(op::Add(op::Iota(), op::Broadcast(id_mul5_add1_div3)),
op::Broadcast(op::Constant())),
op::Compare(op::Add(op::Iota(), op::Broadcast(id_mul5_add1_div3)),
op::Broadcast(op::Constant()))),
before_masking, op::Broadcast(op::Constant()));
auto rw = AllOf(op::Shape("f32[128,7,17,768]"),
op::ReduceWindow(masked, op::Constant()));
auto final_slice_index = op::Subtract(
id_mul5,
op::Add(op::Multiply(id_mul5_add1_div3, op::Constant()), op::Constant()));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root,
AllOf(op::Shape("f32[128,5,17,768]"),
op::DynamicSlice(rw, op::Constant(), final_slice_index,
op::Constant(), op::Constant())));
}
TEST_F(SpmdPartitioningTest, TiledToTiledReduce) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
%param0 = f32[4,32,32,128] parameter(0)
%param0.copy = f32[4,32,32,128] copy(%param0),
sharding={devices=[1,1,1,2]0,1}
%constant.1 = f32[] constant(0), sharding={replicated}
%reduce = f32[128] reduce(%param0.copy, %constant.1), dimensions={0,1,2},
to_apply=%sum, sharding={devices=[2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[4,32,32,64]"));
EXPECT_THAT(root,
AllOf(op::Reduce(param0, op::Constant()), op::Shape("f32[64]")));
}
TEST_F(SpmdPartitioningTest, PartialTiledToPartialTiledReduce) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
%param0 = f32[4,4] parameter(0),
sharding={devices=[2,2,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
%constant.1 = f32[] constant(0), sharding={replicated}
ROOT %reduce = f32[4] reduce(%param0, %constant.1), dimensions={0},
to_apply=%sum,
sharding={devices=[2,4]0,1,4,5,2,3,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root,
AllOf(op::AllReduce(op::Reduce(op::Parameter(0), op::Constant())),
op::Shape("f32[2]")));
}
TEST_F(SpmdPartitioningTest, TiledToTiledTupleReduce) {
absl::string_view hlo_string = R"(
HloModule module
%minmax_func {
%lhs_value = f32[] parameter(0)
%rhs_value = f32[] parameter(2)
%compare.2 = pred[] compare(%lhs_value, %rhs_value), direction=GT
%select.4 = f32[] select(%compare.2, %lhs_value, %rhs_value)
%lhs_index = s32[] parameter(1)
%rhs_index = s32[] parameter(3)
%select.5 = s32[] select(%compare.2, %lhs_index, %rhs_index)
ROOT %tuple.2 = (f32[], s32[]) tuple(%select.4, %select.5)
}
ENTRY %main {
%param0 = f32[28,10] parameter(0), sharding={devices=[2,1]0,1}
%param1 = s32[28,10] parameter(1), sharding={devices=[2,1]0,1}
%init0 = f32[] parameter(2)
%init1 = s32[] parameter(3)
ROOT %reduce = (f32[28], s32[28]) reduce(%param0, %param1, %init0, %init1),
dimensions={1}, to_apply=%minmax_func,
sharding={{devices=[2]0,1}, {devices=[2]0,1}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Reduce(op::Parameter(0), op::Parameter(1),
op::Parameter(2), op::Parameter(3)),
op::Shape("(f32[14], s32[14])")));
}
TEST_F(SpmdPartitioningTest, TiledToPartiallyTiledTupleReduce) {
absl::string_view hlo_string = R"(
HloModule module
%minmax_func {
%lhs_value = f32[] parameter(0)
%rhs_value = f32[] parameter(2)
%compare.2 = pred[] compare(%lhs_value, %rhs_value), direction=GT
%select.4 = f32[] select(%compare.2, %lhs_value, %rhs_value)
%lhs_index = s32[] parameter(1)
%rhs_index = s32[] parameter(3)
%select.5 = s32[] select(%compare.2, %lhs_index, %rhs_index)
ROOT %tuple.2 = (f32[], s32[]) tuple(%select.4, %select.5)
}
ENTRY %main {
%param0 = f32[28,12] parameter(0), sharding={devices=[2,4]0,1,2,3,4,5,6,7}
%param1 = s32[28,12] parameter(1), sharding={devices=[2,4]0,1,2,3,4,5,6,7}
%init0 = f32[] parameter(2)
%init1 = s32[] parameter(3)
ROOT %reduce = (f32[28], s32[28]) reduce(%param0, %param1, %init0, %init1),
dimensions={1}, to_apply=%minmax_func,
sharding={{devices=[2,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate},
{devices=[2,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[14,3]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("s32[14,3]"), op::Parameter(1));
auto local_reduce =
AllOf(op::Reduce(lhs, rhs, op::Parameter(2), op::Parameter(3)),
op::Shape("(f32[14], s32[14])"));
auto reshape_l = AllOf(op::Reshape(op::GetTupleElement(local_reduce)),
op::Shape("f32[14,1]"));
auto reshape_r = AllOf(op::Reshape(op::GetTupleElement(local_reduce)),
op::Shape("s32[14,1]"));
auto broadcast_l =
AllOf(op::AllReduce(op::DynamicUpdateSlice(_, reshape_l, _, _)),
op::Shape("f32[14,4]"));
auto broadcast_r =
AllOf(op::AllReduce(op::DynamicUpdateSlice(_, reshape_r, _, _)),
op::Shape("s32[14,4]"));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Reduce(broadcast_l, broadcast_r, op::Parameter(2),
op::Parameter(3)),
op::Shape("(f32[14], s32[14])")));
}
TEST_F(SpmdPartitioningTest, TiledToTiledReduceOutputReshard) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
%param0 = f32[4,32,32,128] parameter(0)
%param0.copy = f32[4,32,32,128] copy(%param0),
sharding={devices=[1,2,1,1]0,1}
%constant.1 = f32[] constant(0), sharding={replicated}
%reduce = f32[128] reduce(%param0.copy, %constant.1), dimensions={0,1,2},
to_apply=%sum, sharding={devices=[2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param0 = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[4,16,32,128]"));
EXPECT_THAT(root,
AllOf(op::DynamicSlice(
AllOf(op::AllReduce(op::Reduce(param0, op::Constant())),
op::Shape("f32[128]")),
op::Reshape()),
op::Shape("f32[64]")));
}
TEST_F(SpmdPartitioningTest, IotaAlongNonTileDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
ROOT %iota = s32[16,80,91] iota(), iota_dimension=1,
sharding={devices=[1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Iota(), op::Shape("s32[16,80,46]")));
}
TEST_F(SpmdPartitioningTest, IotaAlongTileDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
ROOT %iota = s32[16,80,91] iota(), iota_dimension=2,
sharding={devices=[1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Add(op::Iota(), op::Broadcast()),
op::Shape("s32[16,80,46]")));
}
TEST_F(SpmdPartitioningTest, U32IotaAlongTileDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
ROOT %iota = u32[16,80,91] iota(), iota_dimension=2,
sharding={devices=[1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Add(op::Iota(), op::Broadcast()),
op::Shape("u32[16,80,46]")));
}
TEST_F(SpmdPartitioningTest, Conditional) {
absl::string_view hlo_string = R"(
HloModule module
Negate {
x = f32[4,5] parameter(0), sharding={replicated}
ROOT negate = f32[4,5] negate(x), sharding={replicated}
}
Identity {
y = f32[4,5] parameter(0), sharding={devices=[2,1]0,1}
ROOT copy = f32[4,5] copy(y), sharding={devices=[2,1]0,1}
}
ENTRY entry {
%param.0 = pred[] parameter(0)
%param.0.copy = pred[] copy(%param.0), sharding={maximal device=0}
%param.1 = f32[4,5] parameter(1)
%param.1.copy = f32[4,5] copy(%param.1), sharding={replicated}
%param.2 = f32[4,5] parameter(2)
%param.2.copy = f32[4,5] copy(%param.2), sharding={devices=[2,1]0,1}
ROOT cond = f32[4,5] conditional(%param.0.copy, %param.1.copy, %param.2.copy),
true_computation=Negate, false_computation=Identity,
sharding={devices=[2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto param0 = AllOf(op::Copy(op::Copy(op::Parameter()), op::Shape("pred[]")));
auto param1 = AllOf(op::Copy(op::Parameter()), op::Shape("f32[4,5]"));
auto param2 = AllOf(op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(),
op::Constant())),
op::Shape("f32[2,5]"));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Conditional(op::AllReduce(), param1, param2),
op::Shape("f32[2,5]")));
auto then_branch_root = root->branch_computation(0)->root_instruction();
EXPECT_THAT(then_branch_root,
AllOf(op::DynamicSlice(op::Negate(op::Parameter()), op::Reshape(),
op::Constant()),
op::Shape("f32[2,5]")));
auto else_branch_root = root->branch_computation(1)->root_instruction();
EXPECT_THAT(else_branch_root,
AllOf(op::Copy(op::Parameter()), op::Shape("f32[2,5]")));
}
TEST_F(SpmdPartitioningTest, SelectAndScatter_RetinaNet) {
absl::string_view hlo_string = R"(
HloModule module
ge {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT compare = pred[] compare(a, b), direction=GE
}
sum {
c = f32[] parameter(0)
d = f32[] parameter(1)
ROOT add = f32[] add(c, d)
}
ENTRY entry {
%param.0 = f32[32,128,384,64] parameter(0)
%param.0.copy = f32[32,128,384,64] copy(%param.0),
sharding={devices=[1,8,1,1]0,1,2,3,4,5,6,7}
%param.1 = f32[32,64,192,64] parameter(1)
%param.1.copy = f32[32,64,192,64] copy(%param.1),
sharding={devices=[1,8,1,1]0,1,2,3,4,5,6,7}
constant.1 = f32[] constant(0), sharding={replicated}
ROOT select-and-scatter = f32[32,128,384,64] select-and-scatter(param.0.copy,
%param.1.copy, constant.1), window={size=1x1x1x1 stride=1x2x2x1},
select=ge, scatter=sum, sharding={devices=[1,8,1,1]0,1,2,3,4,5,6,7}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto source = AllOf(
op::Shape("f32[32,8,192,64]"),
op::Copy(op::DynamicSlice(op::Parameter(1), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())));
auto data = AllOf(
op::Shape("f32[32,16,384,64]"),
op::Copy(op::DynamicSlice(op::Parameter(0), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())));
EXPECT_THAT(root, op::SelectAndScatter(data, source, op::Constant()));
EXPECT_EQ(root->window().dimensions(0).padding_low(), 0);
EXPECT_EQ(root->window().dimensions(0).padding_high(), 0);
}
TEST_F(SpmdPartitioningTest, TiledDot) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,64] parameter(0)
%lhs.copy = f32[128,64] copy(%lhs), sharding={devices=[1,2]0,1}
%rhs = f32[64,256] parameter(1)
%rhs.copy = f32[64,256] copy(%rhs), sharding={devices=[2,1]0,1}
ROOT %conv = f32[128,256] convolution(%lhs.copy, %rhs.copy),
dim_labels=bf_io->bf, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(
auto module,
PartitionComputation(hlo_string, /*num_devices=*/2,
/*conv_halo_exchange_always_on_lhs=*/false));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(),
op::Reshape())),
op::Shape("f32[128,32]"));
auto rhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(),
op::Constant())),
op::Shape("f32[32,256]"));
EXPECT_THAT(root, AllOf(op::AllReduce(op::Convolution(lhs, rhs)),
op::Shape("f32[128,256]")));
}
TEST_F(SpmdPartitioningTest, TiledDotOutputTiled) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,64] parameter(0)
%lhs.copy = f32[128,64] copy(%lhs), sharding={devices=[1,2]0,1}
%rhs = f32[64,256] parameter(1)
%rhs.copy = f32[64,256] copy(%rhs), sharding={devices=[2,1]0,1}
ROOT %conv = f32[128,256] convolution(%lhs.copy, %rhs.copy),
dim_labels=bf_io->bf, sharding={devices=[1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(),
op::Reshape())),
op::Shape("f32[128,32]"));
auto rhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(),
op::Constant())),
op::Shape("f32[32,256]"));
EXPECT_THAT(root, AllOf(op::DynamicSlice(
AllOf(op::AllReduce(op::Convolution(lhs, rhs)),
op::Shape("f32[128,256]")),
op::Constant(), op::Reshape()),
op::Shape("f32[128,128]")));
}
TEST_F(SpmdPartitioningTest, BatchPartitionedConvolution) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,256,256] parameter(0)
%lhs.copy = f32[128,256,256] copy(%lhs), sharding={devices=[1,2,1]0,1}
%rhs = f32[256,8,1] parameter(1)
%rhs.copy = f32[256,8,1] copy(%rhs), sharding={replicated}
ROOT %conv = f32[128,256,8] convolution(%lhs.copy, %rhs.copy),
window={size=1}, dim_labels=0bf_io0->0bf, sharding={devices=[1,2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(0), op::Constant(),
op::Reshape(), op::Constant())),
op::Shape("f32[128,128,256]"));
auto rhs = AllOf(op::Copy(op::Parameter(1)), op::Shape("f32[256,8,1]"));
EXPECT_THAT(root,
AllOf(op::Convolution(lhs, rhs), op::Shape("f32[128,128,8]")));
}
TEST_F(SpmdPartitioningTest, DotOutputFeaturePartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[24,64] parameter(0)
%lhs.copy = f32[24,64] copy(%lhs), sharding={replicated}
%rhs = f32[39296,64] parameter(1)
%rhs.copy = f32[39296,64] copy(%rhs), sharding={devices=[2,1]0,1}
ROOT %dot = f32[24,39296] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={1}, rhs_contracting_dims={1},
sharding={devices=[1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::Parameter(0)), op::Shape("f32[24,64]"));
auto rhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(1), op::Reshape(),
op::Constant())),
op::Shape("f32[19648,64]"));
EXPECT_THAT(root, AllOf(op::Dot(lhs, rhs), op::Shape("f32[24,19648]")));
}
TEST_F(SpmdPartitioningTest, DotPartialDeviceOrder) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,256,4096] parameter(0), sharding={devices=[1,1,2,2]1,3,0,2 last_tile_dim_replicate}
%rhs = f32[4096,2048] parameter(1), sharding={devices=[2,2]3,1,2,0}
ROOT %dot = f32[16,256,2048] dot(%lhs, %rhs),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={2}, rhs_contracting_dims={0},
sharding={devices=[1,1,2,2]2,3,0,1 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Parameter(0), op::Shape("f32[16,256,2048]"));
auto rhs = AllOf(op::Parameter(1), op::Shape("f32[2048,1024]"));
EXPECT_THAT(root, AllOf(op::AllReduce(op::Dot(lhs, rhs)),
op::Shape("f32[16,256,1024]")));
}
TEST_F(SpmdPartitioningTest, EinsumBatchPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,24,64] parameter(0)
%lhs.copy = f32[32,24,64] copy(%lhs), sharding={devices=[2,1,1]0,1}
%rhs = f32[32,39296,64] parameter(1)
%rhs.copy = f32[32,39296,64] copy(%rhs), sharding={devices=[2,1,1]0,1}
ROOT %dot = f32[32,24,39296] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2}, rhs_contracting_dims={2},
sharding={devices=[2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(0), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[16,24,64]"));
auto rhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(1), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[16,39296,64]"));
EXPECT_THAT(root, AllOf(op::Dot(lhs, rhs), op::Shape("f32[16,24,39296]")));
}
TEST_F(SpmdPartitioningTest, EinsumLHSandOutputBatchPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,24,64] parameter(0)
%lhs.copy = f32[32,24,64] copy(%lhs), sharding={devices=[2,1,1]0,1}
%rhs = f32[32,39296,64] parameter(1)
%rhs.copy = f32[32,39296,64] copy(%rhs), sharding={replicated}
ROOT %dot = f32[32,24,39296] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2}, rhs_contracting_dims={2},
sharding={devices=[2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(0), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[16,24,64]"));
auto rhs = AllOf(op::Copy(op::Parameter(1)), op::Shape("f32[32,39296,64]"));
EXPECT_THAT(root, AllOf(op::Dot(lhs, op::DynamicSlice(rhs, op::Reshape(),
op::Constant(),
op::Constant())),
op::Shape("f32[16,24,39296]")));
}
TEST_F(SpmdPartitioningTest, EinsumRHSandOutputBatchPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,24,64] parameter(0)
%lhs.copy = f32[32,24,64] copy(%lhs), sharding={devices=[1,2,1]0,1}
%rhs = f32[32,39296,64] parameter(1)
%rhs.copy = f32[32,39296,64] copy(%rhs), sharding={devices=[2,1,1]0,1}
ROOT %dot = f32[32,24,39296] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2}, rhs_contracting_dims={2},
sharding={devices=[2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(0), op::Constant(),
op::Reshape(), op::Constant())),
op::Shape("f32[32,12,64]"));
auto rhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(1), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[16,39296,64]"));
auto lhs_reshard = op::Reshape(op::Transpose(op::AllToAll(op::Reshape(lhs))));
EXPECT_THAT(root,
AllOf(op::Dot(lhs_reshard, rhs), op::Shape("f32[16,24,39296]")));
}
TEST_F(SpmdPartitioningTest, EinsumOutputBatchPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,24,64] parameter(0)
%lhs.copy = f32[32,24,64] copy(%lhs), sharding={replicated}
%rhs = f32[32,39296,64] parameter(1)
%rhs.copy = f32[32,39296,64] copy(%rhs), sharding={replicated}
ROOT %dot = f32[32,24,39296] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2}, rhs_contracting_dims={2},
sharding={devices=[2,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs_slice =
AllOf(op::DynamicSlice(op::Copy(op::Parameter(0)), op::Reshape(),
op::Constant(), op::Constant()),
op::Shape("f32[16,24,64]"));
auto rhs_slice =
AllOf(op::DynamicSlice(op::Copy(op::Parameter(1)), op::Reshape(),
op::Constant(), op::Constant()),
op::Shape("f32[16,39296,64]"));
EXPECT_THAT(root, AllOf(op::Dot(lhs_slice, rhs_slice),
op::Shape("f32[16,24,39296]")));
}
TEST_F(SpmdPartitioningTest, EinsumContractingDimsPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,24,64,128] parameter(0)
%lhs.copy = f32[32,24,64,128] copy(%lhs), sharding={devices=[1,1,2,2]0,1,2,3}
%rhs = f32[32,39296,64,128] parameter(1)
%rhs.copy = f32[32,39296,64,128] copy(%rhs), sharding={devices=[1,1,2,2]0,1,2,3}
ROOT %dot = f32[32,24,39296] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2,3}, rhs_contracting_dims={2,3},
sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(0), op::Constant(),
op::Constant(), op::Reshape(), op::Reshape())),
op::Shape("f32[32,24,32,64]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(1), op::Constant(),
op::Constant(), op::Reshape(), op::Reshape())),
op::Shape("f32[32,39296,32,64]"));
EXPECT_THAT(root, AllOf(op::AllReduce(op::AllReduce(op::Dot(lhs, rhs))),
op::Shape("f32[32,24,39296]")));
}
TEST_F(SpmdPartitioningTest, EinsumLHSNonContractingDimsPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,24,64,128] parameter(0)
%lhs.copy = f32[32,24,64,128] copy(%lhs), sharding={devices=[1,2,1,2]0,1,2,3}
%rhs = f32[32,39296,64] parameter(1)
%rhs.copy = f32[32,39296,64] copy(%rhs), sharding={replicated}
ROOT %dot = f32[32,24,128,39296] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2}, rhs_contracting_dims={2},
sharding={devices=[1,2,2,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(0), op::Constant(), op::Reshape(),
op::Constant(), op::Reshape())),
op::Shape("f32[32,12,64,64]"));
auto rhs = AllOf(op::Copy(op::Parameter(1)), op::Shape("f32[32,39296,64]"));
EXPECT_THAT(root, AllOf(op::Dot(lhs, rhs), op::Shape("f32[32,12,64,39296]")));
}
TEST_F(SpmdPartitioningTest, EinsumRHSNonContractingDimsPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,24,64] parameter(0)
%lhs.copy = f32[32,24,64] copy(%lhs), sharding={replicated}
%rhs = f32[32,39296,64,128] parameter(1)
%rhs.copy = f32[32,39296,64,128] copy(%rhs), sharding={devices=[1,2,1,2]0,1,2,3}
ROOT %dot = f32[32,24,39296,128] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2}, rhs_contracting_dims={2},
sharding={devices=[1,1,2,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::Parameter(0)), op::Shape("f32[32,24,64]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(1), op::Constant(), op::Reshape(),
op::Constant(), op::Reshape())),
op::Shape("f32[32,19648,64,64]"));
EXPECT_THAT(root, AllOf(op::Dot(lhs, rhs), op::Shape("f32[32,24,19648,64]")));
}
TEST_F(SpmdPartitioningTest, EinsumOutputLHSNonContractingDimPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,24,64,128] parameter(0)
%lhs.copy = f32[32,24,64,128] copy(%lhs), sharding={replicated}
%rhs = f32[32,39296,64,128] parameter(1)
%rhs.copy = f32[32,39296,64,128] copy(%rhs), sharding={replicated}
ROOT %dot = f32[32,24,39296] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2,3}, rhs_contracting_dims={2,3},
sharding={devices=[1,2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::Parameter(0)), op::Shape("f32[32,24,64,128]"));
auto rhs =
AllOf(op::Copy(op::Parameter(1)), op::Shape("f32[32,39296,64,128]"));
EXPECT_THAT(
root,
AllOf(op::Dot(AllOf(op::DynamicSlice(lhs, op::Constant(), op::Reshape(),
op::Constant(), op::Constant()),
op::Shape("f32[32,12,64,128]")),
rhs),
op::Shape("f32[32,12,39296]")));
}
TEST_F(SpmdPartitioningTest, EinsumOutputRHSNonContractingDimPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,24,64,128] parameter(0)
%lhs.copy = f32[32,24,64,128] copy(%lhs), sharding={replicated}
%rhs = f32[32,39296,64,128] parameter(1)
%rhs.copy = f32[32,39296,64,128] copy(%rhs), sharding={replicated}
ROOT %dot = f32[32,24,39296] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2,3}, rhs_contracting_dims={2,3},
sharding={devices=[1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::Parameter(0)), op::Shape("f32[32,24,64,128]"));
auto rhs =
AllOf(op::Copy(op::Parameter(1)), op::Shape("f32[32,39296,64,128]"));
EXPECT_THAT(root,
AllOf(op::Dot(lhs, AllOf(op::DynamicSlice(
rhs, op::Constant(), op::Reshape(),
op::Constant(), op::Constant()),
op::Shape("f32[32,19648,64,128]"))),
op::Shape("f32[32,24,19648]")));
}
TEST_F(SpmdPartitioningTest,
EinsumRHSWindowedInContractingOutNonContractingPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[320,25,64,128] parameter(0)
%lhs.copy = f32[320,25,64,128] copy(%lhs), sharding={devices=[1,1,4,1]0,1,2,3}
%rhs = f32[320,39296,64,128] parameter(1)
%rhs.copy = f32[320,39296,64,128] copy(%rhs),
sharding={devices=[1,1,4,1]0,1,2,3}
ROOT %dot = f32[320,25,39296] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2,3}, rhs_contracting_dims={2,3},
sharding={devices=[1,4,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(0), op::Constant(),
op::Constant(), op::Reshape(), op::Constant())),
op::Shape("f32[320,25,16,128]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(1), op::Constant(),
op::Constant(), op::Reshape(), op::Constant())),
op::Shape("f32[320,39296,16,128]"));
EXPECT_THAT(
root,
AllOf(op::GetTupleElement(op::While(op::Tuple(
lhs, rhs, op::Broadcast(), op::Broadcast(), op::Constant()))),
op::Shape("f32[320,7,39296]")));
auto while_loop = root->operand(0);
// Check loop condition.
EXPECT_THAT(
while_loop->while_condition()->root_instruction(),
op::Compare(op::GetTupleElement(op::Parameter(0)), op::Constant()));
// Check loop body.
auto next_i = op::Add(op::GetTupleElement(op::Parameter(0)), op::Constant());
auto ds =
AllOf(op::DynamicSlice(
op::Pad(op::GetTupleElement(op::Parameter(0)), op::Constant()),
op::Constant(), op::Reshape(), op::Constant(), op::Constant()),
op::Shape("f32[320,7,16,128]"));
auto partial_output =
AllOf(op::Add(op::GetTupleElement(op::Parameter(0)),
op::Dot(ds, op::GetTupleElement(op::Parameter(0)))),
op::Shape("f32[320,7,39296]"));
auto window = op::Conditional(op::Compare(next_i, op::Constant()),
partial_output, partial_output);
EXPECT_THAT(while_loop->while_body()->root_instruction(),
op::Tuple(op::GetTupleElement(op::Parameter(0)),
op::GetTupleElement(op::Parameter(0)), window,
op::GetTupleElement(op::Parameter(0)), next_i));
// Check the conditional that contains the collective permute.
auto cp_conditional =
while_loop->while_body()->root_instruction()->operand(2);
EXPECT_THAT(cp_conditional->true_computation()->root_instruction(),
op::CollectivePermute(op::Parameter(0)));
EXPECT_THAT(cp_conditional->false_computation()->root_instruction(),
op::Parameter(0));
}
TEST_F(SpmdPartitioningTest,
EinsumRHSWindowedInContractingOutNonContractingFromBroadcast) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%constant.1 = f32[] constant(2)
%broadcast = f32[32,25,64,128] broadcast(%constant.1), dimensions={},
sharding={devices=[1,1,4,1]0,1,2,3}
%add = f32[32,25,64,128] add(%broadcast, %broadcast),
sharding={devices=[1,1,4,1]0,1,2,3}
%rhs = f32[32,39296,64,128] parameter(0)
%rhs.copy = f32[32,39296,64,128] copy(%rhs),
sharding={devices=[1,1,4,1]0,1,2,3}
ROOT %dot = f32[32,25,39296] dot(%add, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2,3}, rhs_contracting_dims={2,3},
sharding={devices=[1,4,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module, PartitionComputation(hlo_string,
/*num_devices=*/4));
VLOG(1) << module->ToString();
// Involves loop code motion, skips pattern matching.
}
TEST_F(SpmdPartitioningTest,
EinsumLHSWindowedInContractingOutNonContractingPartitioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,1024,16384] parameter(0)
%lhs.copy = f32[16,1024,16384] copy(%lhs),
sharding={devices=[2,1,4]0,1,2,3,4,5,6,7}
%rhs = f32[16384,67,128] parameter(1)
%rhs.copy = f32[16384,67,128] copy(%rhs),
sharding={devices=[4,1,1,2]0,4,1,5,2,6,3,7 last_tile_dim_replicate}
ROOT %dot = f32[16,1024,67,128] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={2}, rhs_contracting_dims={0},
sharding={devices=[2,1,4,1]0,1,2,3,4,5,6,7}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(0), op::Reshape(),
op::Constant(), op::Reshape())),
op::Shape("f32[8,1024,4096]"));
auto rhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(1), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[4096,67,128]"));
EXPECT_THAT(
root,
AllOf(op::GetTupleElement(op::While(op::Tuple(
lhs, rhs, op::Broadcast(), op::Broadcast(), op::Constant()))),
op::Shape("f32[8,1024,17,128]")));
auto while_loop = root->operand(0);
// Check loop condition.
EXPECT_THAT(
while_loop->while_condition()->root_instruction(),
op::Compare(op::GetTupleElement(op::Parameter(0)), op::Constant()));
// Check loop body.
auto next_i = op::Add(op::GetTupleElement(op::Parameter(0)), op::Constant());
auto ds =
AllOf(op::DynamicSlice(
op::Pad(op::GetTupleElement(op::Parameter(0)), op::Constant()),
op::Constant(), op::Reshape(), op::Constant()),
op::Shape("f32[4096,17,128]"));
auto partial_output =
AllOf(op::Add(op::GetTupleElement(op::Parameter(0)),
op::Dot(op::GetTupleElement(op::Parameter(0)), ds)),
op::Shape("f32[8,1024,17,128]"));
auto window = op::Conditional(op::Compare(next_i, op::Constant()),
partial_output, partial_output);
EXPECT_THAT(while_loop->while_body()->root_instruction(),
op::Tuple(op::GetTupleElement(op::Parameter(0)),
op::GetTupleElement(op::Parameter(0)), window,
op::GetTupleElement(op::Parameter(0)), next_i));
// Check the conditional that contains the collective permute.
auto cp_conditional =
while_loop->while_body()->root_instruction()->operand(2);
EXPECT_THAT(cp_conditional->true_computation()->root_instruction(),
op::CollectivePermute(op::Parameter(0)));
EXPECT_THAT(cp_conditional->false_computation()->root_instruction(),
op::Parameter(0));
}
TEST_F(SpmdPartitioningTest,
EinsumLHSWindowedInContractingOutNonContractingPartitioned2) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,1024,16384] parameter(0)
%lhs.copy = f32[16,1024,16384] copy(%lhs),
sharding={devices=[2,1,4]0,1,2,3,4,5,6,7}
%rhs = f32[16384,2,33,128] parameter(1)
%rhs.copy = f32[16384,2,33,128] copy(%rhs),
sharding={devices=[4,1,1,1,2]0,4,1,5,2,6,3,7 last_tile_dim_replicate}
ROOT %dot = f32[16,1024,2,33,128] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={2}, rhs_contracting_dims={0},
sharding={devices=[2,1,2,2,1]0,1,2,3,4,5,6,7}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(op::Parameter(0), op::Reshape(),
op::Constant(), op::Reshape())),
op::Shape("f32[8,1024,4096]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(1), op::Reshape(), op::Constant(),
op::Constant(), op::Constant())),
op::Shape("f32[4096,2,33,128]"));
EXPECT_THAT(
root,
AllOf(op::GetTupleElement(op::While(op::Tuple(
lhs, rhs, op::Broadcast(), op::Broadcast(), op::Constant()))),
op::Shape("f32[8,1024,1,17,128]")));
auto while_loop = root->operand(0);
// Check loop condition.
EXPECT_THAT(
while_loop->while_condition()->root_instruction(),
op::Compare(op::GetTupleElement(op::Parameter(0)), op::Constant()));
// Check loop body.
auto next_i = op::Add(op::GetTupleElement(op::Parameter(0)), op::Constant());
auto ds =
AllOf(op::DynamicSlice(
op::Pad(op::GetTupleElement(op::Parameter(0)), op::Constant()),
op::Constant(), op::Reshape(), op::Reshape(), op::Constant()),
op::Shape("f32[4096,1,17,128]"));
auto partial_output =
AllOf(op::Add(op::GetTupleElement(op::Parameter(0)),
op::Dot(op::GetTupleElement(op::Parameter(0)), ds)),
op::Shape("f32[8,1024,1,17,128]"));
auto window = op::Conditional(op::Compare(next_i, op::Constant()),
partial_output, partial_output);
EXPECT_THAT(while_loop->while_body()->root_instruction(),
op::Tuple(op::GetTupleElement(op::Parameter(0)),
op::GetTupleElement(op::Parameter(0)), window,
op::GetTupleElement(op::Parameter(0)), next_i));
// Check the conditional that contains the collective permute.
auto cp_conditional =
while_loop->while_body()->root_instruction()->operand(2);
EXPECT_THAT(cp_conditional->true_computation()->root_instruction(),
op::CollectivePermute(op::Parameter(0)));
EXPECT_THAT(cp_conditional->false_computation()->root_instruction(),
op::Parameter(0));
}
TEST_F(SpmdPartitioningTest, EinsumRHSWindowedNonContracting) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,24,64,128] parameter(0)
%lhs.copy = f32[32,24,64,128] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[32,39295,64,128] parameter(1)
%rhs.copy = f32[32,39295,64,128] copy(%rhs), sharding={devices=[1,2,1,1]0,1}
ROOT %dot = f32[32,24,39295] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2,3}, rhs_contracting_dims={2,3},
sharding={devices=[1,2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module, PartitionComputation(hlo_string,
/*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(0), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[32,12,64,128]"));
auto rhs =
AllOf(op::Copy(op::DynamicSlice(op::Pad(op::Parameter(1), op::Constant()),
op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[32,19648,64,128]"));
EXPECT_THAT(root,
AllOf(op::Slice(AllOf(op::GetTupleElement(op::While(op::Tuple(
lhs, rhs, op::Broadcast(),
op::Broadcast(), op::Constant()))),
op::Shape("f32[32,12,39296]"))),
op::Shape("f32[32,12,39295]")));
auto while_loop = root->operand(0)->operand(0);
// Check loop condition.
EXPECT_THAT(
while_loop->while_condition()->root_instruction(),
op::Compare(op::GetTupleElement(op::Parameter(0)), op::Constant()));
// Check loop body.
auto next_i = op::Add(op::GetTupleElement(op::Parameter(0)), op::Constant());
auto window = op::Conditional(op::Compare(next_i, op::Constant()),
op::GetTupleElement(op::Parameter(0)),
op::GetTupleElement(op::Parameter(0)));
auto partial_output = op::Dot(op::GetTupleElement(op::Parameter(0)),
op::GetTupleElement(op::Parameter(0)));
EXPECT_THAT(
while_loop->while_body()->root_instruction(),
op::Tuple(op::GetTupleElement(op::Parameter(0)), window,
op::DynamicUpdateSlice(op::GetTupleElement(op::Parameter(0)),
partial_output, op::Constant(),
op::Constant(), op::Reshape()),
op::GetTupleElement(op::Parameter(0)), next_i));
// Check the conditional that contains the collective permute.
auto cp_conditional =
while_loop->while_body()->root_instruction()->operand(1);
EXPECT_THAT(cp_conditional->true_computation()->root_instruction(),
op::CollectivePermute(op::Parameter(0)));
EXPECT_THAT(cp_conditional->false_computation()->root_instruction(),
op::Parameter(0));
}
TEST_F(SpmdPartitioningTest, EinsumRHSWindowedContracting) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,24,63,128] parameter(0)
%lhs.copy = f32[32,24,63,128] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[32,39296,63,128] parameter(1)
%rhs.copy = f32[32,39296,63,128] copy(%rhs), sharding={devices=[1,1,2,1]0,1}
ROOT %dot = f32[32,24,39296] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2,3}, rhs_contracting_dims={2,3},
sharding={devices=[1,2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module, PartitionComputation(hlo_string,
/*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(0), op::Constant(), op::Reshape(),
op::Constant(), op::Constant())),
op::Shape("f32[32,12,63,128]"));
auto rhs =
AllOf(op::Copy(op::DynamicSlice(op::Pad(op::Parameter(1), op::Constant()),
op::Constant(), op::Constant(),
op::Reshape(), op::Constant())),
op::Shape("f32[32,39296,32,128]"));
auto masked_rhs =
op::Select(op::Compare(), rhs, op::Broadcast(op::Constant()));
EXPECT_THAT(root, AllOf(op::GetTupleElement(op::While(
op::Tuple(lhs, masked_rhs, op::Broadcast(),
op::Broadcast(), op::Constant()))),
op::Shape("f32[32,12,39296]")));
auto while_loop = root->operand(0);
// Check loop condition.
EXPECT_THAT(
while_loop->while_condition()->root_instruction(),
op::Compare(op::GetTupleElement(op::Parameter(0)), op::Constant()));
// Check loop body.
auto next_i = op::Add(op::GetTupleElement(op::Parameter(0)), op::Constant());
auto window = op::Conditional(op::Compare(next_i, op::Constant()),
op::GetTupleElement(op::Parameter(0)),
op::GetTupleElement(op::Parameter(0)));
auto partial_output = op::Dot(
op::DynamicSlice(
op::Pad(op::GetTupleElement(op::Parameter(0)), op::Constant()),
op::Constant(), op::Constant(), op::Reshape(), op::Constant()),
op::GetTupleElement(op::Parameter(0)));
EXPECT_THAT(
while_loop->while_body()->root_instruction(),
op::Tuple(op::GetTupleElement(op::Parameter(0)), window,
op::Add(op::GetTupleElement(op::Parameter(0)), partial_output),
op::GetTupleElement(op::Parameter(0)), next_i));
// Check the conditional that contains the collective permute.
auto cp_conditional =
while_loop->while_body()->root_instruction()->operand(1);
EXPECT_THAT(cp_conditional->true_computation()->root_instruction(),
op::CollectivePermute(op::Parameter(0)));
EXPECT_THAT(cp_conditional->false_computation()->root_instruction(),
op::Parameter(0));
}
TEST_F(SpmdPartitioningTest, EinsumRHSWindowedNonContractingReduce1) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
%lhs = f32[32,24,64,128] parameter(0)
%lhs.copy = f32[32,24,64,128] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[32,39295,64,128] parameter(1)
%rhs.copy = f32[32,39295,64,128] copy(%rhs), sharding={devices=[1,2,1,1]0,1}
%dot = f32[32,24,39295] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2,3}, rhs_contracting_dims={2,3},
sharding={devices=[1,2,1]0,1}
%constant = f32[] constant(0)
%constant.1 = f32[] constant(2)
%broadcast = f32[32,24,39295] broadcast(%constant.1), dimensions={},
sharding={devices=[1,2,1]0,1}
%multiply = f32[32,24,39295] multiply(%dot, %broadcast),
sharding={devices=[1,2,1]0,1}
ROOT %reduce = f32[32,24] reduce(%multiply, %constant), dimensions={2},
to_apply=sum, sharding={devices=[1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module, PartitionComputation(hlo_string,
/*num_devices=*/2));
VLOG(1) << module->ToString();
// Involves loop code motion, skips pattern matching.
}
TEST_F(SpmdPartitioningTest, EinsumRHSWindowedNonContractingReduce2) {
absl::string_view hlo_string = R"(
HloModule module
sum {
a = f32[] parameter(0)
b = f32[] parameter(1)
ROOT add = f32[] add(a, b)
}
ENTRY entry {
%lhs = f32[32,24,64,128] parameter(0)
%lhs.copy = f32[32,24,64,128] copy(%lhs), sharding={devices=[1,2,1,1]0,1}
%rhs = f32[32,39295,64,128] parameter(1)
%rhs.copy = f32[32,39295,64,128] copy(%rhs), sharding={devices=[1,2,1,1]0,1}
%dot = f32[32,24,39295] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2,3}, rhs_contracting_dims={2,3},
sharding={devices=[1,2,1]0,1}
%constant = f32[] constant(0)
%constant.1 = f32[] constant(2)
%broadcast = f32[32,24,39295] broadcast(%constant.1), dimensions={},
sharding={devices=[1,2,1]0,1}
%multiply = f32[32,24,39295] multiply(%dot, %broadcast),
sharding={devices=[1,2,1]0,1}
ROOT %reduce = f32[32,39295] reduce(%multiply, %constant), dimensions={1},
to_apply=sum, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module, PartitionComputation(hlo_string,
/*num_devices=*/2));
VLOG(1) << module->ToString();
// Involves loop code motion, skips pattern matching.
}
TEST_F(SpmdPartitioningTest, EinsumRHSWindowedContractingFromBroadcast) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%rhs = f32[32,39296,63,128] parameter(0)
%rhs.copy = f32[32,39296,63,128] copy(%rhs), sharding={devices=[1,1,2,1]0,1}
%constant.1 = f32[] constant(2)
%broadcast = f32[32,24,63,128] broadcast(%constant.1), dimensions={},
sharding={devices=[1,2,1,1]0,1}
%add = f32[32,24,63,128] add(%broadcast, %broadcast),
sharding={devices=[1,2,1,1]0,1}
ROOT %dot = f32[32,24,39296] dot(%add, %rhs.copy),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2,3}, rhs_contracting_dims={2,3},
sharding={devices=[1,2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module, PartitionComputation(hlo_string,
/*num_devices=*/2));
VLOG(1) << module->ToString();
// Involves loop code motion, skips pattern matching.
}
TEST_F(SpmdPartitioningTest, ReplicatedRng) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = s32[] parameter(0)
%lhs.copy = s32[] copy(%lhs), sharding={replicated}
%rhs = s32[] parameter(1)
%rhs.copy = s32[] copy(%rhs), sharding={replicated}
ROOT %rng = s32[4]{0} rng(%lhs.copy, %rhs.copy),
distribution=rng_uniform, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::Parameter(0)), op::Shape("s32[]"));
auto rhs = AllOf(op::Copy(op::Parameter(1)), op::Shape("s32[]"));
EXPECT_THAT(
root,
AllOf(op::AllReduce(op::Select(
op::Broadcast(op::Compare(op::PartitionId(), op::Constant())),
op::Rng(), op::Broadcast(op::Constant()))),
op::Shape("s32[4]")));
}
TEST_F(SpmdPartitioningTest, PartitionedRng) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = s32[] parameter(0)
%lhs.copy = s32[] copy(%lhs), sharding={replicated}
%rhs = s32[] parameter(1)
%rhs.copy = s32[] copy(%rhs), sharding={maximal device=1}
ROOT %rng = s32[4]{0} rng(%lhs.copy, %rhs.copy),
distribution=rng_uniform, sharding={devices=[2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::Parameter(0)), op::Shape("s32[]"));
auto rhs = AllOf(op::Copy(op::Copy(op::Parameter(1))), op::Shape("s32[]"));
EXPECT_THAT(root, AllOf(op::Rng(lhs, op::AllReduce(op::Select(
op::Broadcast(op::Compare()), rhs,
op::Broadcast(op::Constant())))),
op::Shape("s32[2]")));
}
TEST_F(SpmdPartitioningTest, PartialReplicatedRng) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = s32[] parameter(0), sharding={replicated}
%rhs = s32[] parameter(1), sharding={replicated}
ROOT %rng = s32[8]{0} rng(%lhs, %rhs),
distribution=rng_uniform,
sharding={devices=[2,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Parameter(0), op::Shape("s32[]"));
auto rhs = AllOf(op::Parameter(1), op::Shape("s32[]"));
auto partition_id =
AllOf(op::Reshape(op::DynamicSlice(op::Constant(), op::PartitionId())),
op::Shape("u32[]"));
EXPECT_THAT(
root, AllOf(op::AllReduce(op::Select(
op::Broadcast(op::Compare(partition_id, op::Constant())),
op::Rng(lhs, rhs), op::Broadcast(op::Constant()))),
op::Shape("s32[4]")));
}
TEST_F(SpmdPartitioningTest, DynamicSliceAlongNonPartitionedDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%input = s32[128,64] parameter(0)
%input.copy = s32[128,64] copy(%input), sharding={devices=[2,1]0,1}
%index = s32[] parameter(1)
%constant = s32[] constant(0)
ROOT %dynamic-slice = s32[128,2] dynamic-slice(%input.copy, %constant, %index),
dynamic_slice_sizes={128,2}, sharding={devices=[2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto input = AllOf(op::Copy(op::DynamicSlice(op::Parameter(0), op::Reshape(),
op::Constant())),
op::Shape("s32[64,64]"));
EXPECT_THAT(root,
AllOf(op::DynamicSlice(input, op::Constant(), op::Parameter(1)),
op::Shape("s32[64,2]")));
}
TEST_F(SpmdPartitioningTest, DynamicUpdateSliceAlongNonPartitionedDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%input = s32[128,64] parameter(0)
%input.copy = s32[128,64] copy(%input), sharding={devices=[2,1]0,1}
%index = s32[] parameter(1)
%constant = s32[] constant(0)
%update = s32[128,2] parameter(2)
%update.copy = s32[128,2] copy(%update), sharding={devices=[2,1]0,1}
ROOT %dynamic-update-slice = s32[128,64]
dynamic-update-slice(%input.copy, %update.copy, %constant, %index),
sharding={devices=[2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto input = AllOf(op::Copy(op::DynamicSlice(op::Parameter(0), op::Reshape(),
op::Constant())),
op::Shape("s32[64,64]"));
auto update = AllOf(op::Copy(op::DynamicSlice(op::Parameter(2), op::Reshape(),
op::Constant())),
op::Shape("s32[64,2]"));
EXPECT_THAT(root, AllOf(op::DynamicUpdateSlice(input, update, op::Constant(),
op::Parameter(1)),
op::Shape("s32[64,64]")));
}
TEST_F(SpmdPartitioningTest, DynamicUpdateSliceAlongPartitionedDimension) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%input = s32[128,64] parameter(0)
%input.copy = s32[128,64] copy(%input), sharding={devices=[1,2]0,1}
%index = s32[] parameter(1)
%constant = s32[] constant(60)
%update = s32[128,2] parameter(2)
%update.copy = s32[128,2] copy(%update), sharding={devices=[1,2]0,1}
ROOT %dynamic-update-slice = s32[128,64]
dynamic-update-slice(%input.copy, %update.copy, %index, %constant),
sharding={devices=[1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto input = AllOf(op::Copy(op::DynamicSlice(op::Parameter(0), op::Constant(),
op::Reshape())),
op::Shape("s32[128,32]"));
auto update = AllOf(op::AllReduce(op::DynamicUpdateSlice(
op::Broadcast(),
op::Copy(op::DynamicSlice(
op::Parameter(2), op::Constant(), op::Reshape())),
op::Constant(), op::Reshape())),
op::Shape("s32[128,2]"));
EXPECT_THAT(
root, AllOf(op::Select(op::Broadcast(),
op::DynamicUpdateSlice(
input, update, op::Parameter(1), op::Select()),
input),
op::Shape("s32[128,32]")));
}
TEST_F(SpmdPartitioningTest, DynamicUpdateSlicePartitionSliceAndNonSliceDims) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%input = s32[128,64] parameter(0)
%input.copy = s32[128,64] copy(%input), sharding={devices=[2,2]0,1,2,3}
%constant.0 = s32[] constant(0)
%constant.1 = s32[] constant(60)
%update = s32[128,2] parameter(1)
%update.copy = s32[128,2] copy(%update), sharding={devices=[2,2]0,1,2,3}
ROOT %dynamic-update-slice = s32[128,64]
dynamic-update-slice(%input.copy, %update.copy, %constant.0, %constant.1),
sharding={devices=[2,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto input = AllOf(op::Copy(op::DynamicSlice(op::Parameter(0), op::Reshape(),
op::Reshape())),
op::Shape("s32[64,32]"));
auto update = AllOf(op::AllReduce(op::DynamicUpdateSlice(
op::Broadcast(),
op::Copy(op::DynamicSlice(
op::Parameter(1), op::Reshape(), op::Reshape())),
op::Constant(), op::Reshape())),
op::Shape("s32[64,2]"));
EXPECT_THAT(root,
AllOf(op::Select(op::Broadcast(),
op::DynamicUpdateSlice(
input, update, op::Constant(), op::Select()),
input),
op::Shape("s32[64,32]")));
}
TEST_F(SpmdPartitioningTest, PassthroughGather) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%input = f32[2,9] parameter(0), sharding={devices=[1,2]0,1}
%indices = s32[3] parameter(1), sharding={replicated}
ROOT %gather = f32[3,9] gather(%input, %indices), offset_dims={1},
collapsed_slice_dims={0}, start_index_map={0}, index_vector_dim=1,
slice_sizes={1,9}, sharding={devices=[1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Gather(op::Parameter(0), op::Parameter(1)),
op::Shape("f32[3,5]")));
}
TEST_F(SpmdPartitioningTest, PassthroughGather_PartialReplicate) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%input = f32[2,9] parameter(0),
sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
%indices = s32[3] parameter(1), sharding={replicated}
ROOT %gather = f32[3,9] gather(%input, %indices), offset_dims={1},
collapsed_slice_dims={0}, start_index_map={0}, index_vector_dim=1,
slice_sizes={1,9}, sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Gather(op::Parameter(0), op::Parameter(1)),
op::Shape("f32[3,5]")));
}
TEST_F(SpmdPartitioningTest, IndexPassthroughGather) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%input = f32[2,9,8] parameter(0), sharding={replicated}
%indices = s32[4,2,4] parameter(1), sharding={devices=[2,1,2]0,1,2,3}
ROOT %gather = f32[8,4,4] gather(%input, %indices), offset_dims={0},
collapsed_slice_dims={0,1}, start_index_map={0,1}, index_vector_dim=1,
slice_sizes={1,1,8}, sharding={devices=[1,2,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Gather(op::Parameter(0), op::Parameter(1)),
op::Shape("f32[8,2,2]")));
}
TEST_F(SpmdPartitioningTest, IndexPassthroughGather_PartialReplicate) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%input = f32[2,9,8] parameter(0), sharding={replicated}
%indices = s32[4,2,4] parameter(1),
sharding={devices=[2,1,2,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %gather = f32[8,4,4] gather(%input, %indices), offset_dims={0},
collapsed_slice_dims={0,1}, start_index_map={0,1}, index_vector_dim=1,
slice_sizes={1,1,8},
sharding={devices=[1,2,2,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Gather(op::Parameter(0), op::Parameter(1)),
op::Shape("f32[8,2,2]")));
}
TEST_F(SpmdPartitioningTest, GatherPartitionedOnTrivialSliceDims) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%input = f32[17,9] parameter(0), sharding={devices=[2,1]0,1}
%indices = s32[2,3] parameter(1), sharding={replicated}
ROOT %gather = f32[2,3,9] gather(%input, %indices), offset_dims={2},
collapsed_slice_dims={0}, start_index_map={0}, index_vector_dim=2,
slice_sizes={1,9}, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto offset =
op::Reshape(op::DynamicSlice(op::Constant(), op::PartitionId()));
auto min = AllOf(op::Broadcast(offset), op::Shape("s32[2,3]"));
auto max = AllOf(op::Broadcast(op::Add(offset, op::Constant())),
op::Shape("s32[2,3]"));
auto clamp = op::Clamp(min, op::Parameter(1), max);
auto gather = op::Gather(op::Parameter(0), op::Subtract(clamp, min));
auto mask =
op::Or(op::Lt(op::Parameter(1), min), op::Gt(op::Parameter(1), max));
auto masked =
op::Select(op::Broadcast(mask), op::Broadcast(op::Constant()), gather);
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::AllReduce(masked), op::Shape("f32[2,3,9]")));
}
TEST_F(SpmdPartitioningTest,
GatherPartitionedOnTrivialSliceDims_PartialReplicate) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%input = f32[17,9] parameter(0),
sharding={devices=[2,1,2]0,1,2,3 last_tile_dim_replicate}
%indices = s32[2,3] parameter(1), sharding={replicated}
ROOT %gather = f32[2,3,9] gather(%input, %indices), offset_dims={2},
collapsed_slice_dims={0}, start_index_map={0}, index_vector_dim=2,
slice_sizes={1,9}, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto offset =
op::Reshape(op::DynamicSlice(op::Constant(), op::PartitionId()));
auto min = AllOf(op::Broadcast(offset), op::Shape("s32[2,3]"));
auto max = AllOf(op::Broadcast(op::Add(offset, op::Constant())),
op::Shape("s32[2,3]"));
auto clamp = op::Clamp(min, op::Parameter(1), max);
auto gather = op::Gather(op::Parameter(0), op::Subtract(clamp, min));
auto mask =
op::Or(op::Lt(op::Parameter(1), min), op::Gt(op::Parameter(1), max));
auto masked =
op::Select(op::Broadcast(mask), op::Broadcast(op::Constant()), gather);
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::AllReduce(masked), op::Shape("f32[2,3,9]")));
}
TEST_F(SpmdPartitioningTest, PassthroughScatter) {
absl::string_view hlo_string = R"(
HloModule module
add (lhs: f32[], rhs: f32[]) -> f32[] {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT sum = f32[] add(lhs, rhs)
}
ENTRY entry {
%input = f32[2,9] parameter(0), sharding={devices=[1,2]0,1}
%indices = s32[3] parameter(1), sharding={replicated}
%updates = f32[3,9] parameter(2), sharding={devices=[1,2]0,1}
ROOT %scatter = f32[2,9] scatter(%input, %indices, %updates),
to_apply=add,
update_window_dims={1},
inserted_window_dims={0},
scatter_dims_to_operand_dims={0},
index_vector_dim=1, sharding={devices=[1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Scatter(op::Parameter(0), op::Parameter(1),
op::Parameter(2)),
op::Shape("f32[2,5]")));
}
TEST_F(SpmdPartitioningTest, PassthroughScatter_PartialReplicate) {
absl::string_view hlo_string = R"(
HloModule module
add (lhs: f32[], rhs: f32[]) -> f32[] {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT sum = f32[] add(lhs, rhs)
}
ENTRY entry {
%input = f32[2,9] parameter(0),
sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
%indices = s32[3] parameter(1), sharding={replicated}
%updates = f32[3,9] parameter(2),
sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
ROOT %scatter = f32[2,9] scatter(%input, %indices, %updates),
to_apply=add,
update_window_dims={1},
inserted_window_dims={0},
scatter_dims_to_operand_dims={0},
index_vector_dim=1,
sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Scatter(op::Parameter(0), op::Parameter(1),
op::Parameter(2)),
op::Shape("f32[2,5]")));
}
TEST_F(SpmdPartitioningTest, IndexPassthroughScatter) {
absl::string_view hlo_string = R"(
HloModule module
add (lhs: f32[], rhs: f32[]) -> f32[] {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT sum = f32[] add(lhs, rhs)
}
ENTRY entry {
%input = f32[2,9,8] parameter(0), sharding={replicated}
%indices = s32[4,2,4] parameter(1), sharding={devices=[2,1,2]0,1,2,3}
%updates = f32[4,4,8] parameter(2), sharding={devices=[2,2,1]0,1,2,3}
ROOT %scatter = f32[2,9,8] scatter(%input, %indices, %updates),
to_apply=add,
update_window_dims={2},
inserted_window_dims={0,1},
scatter_dims_to_operand_dims={0,1},
index_vector_dim=1, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
AllOf(op::AllReduce(op::AllReduce(op::Scatter(
op::Select(op::Broadcast(op::Convert(op::PartitionId())),
op::Broadcast(op::Constant()), op::Parameter(0)),
op::Parameter(1), op::Parameter(2)))),
op::Shape("f32[2,9,8]")));
}
TEST_F(SpmdPartitioningTest, IndexPassthroughScatter_PartialReplicate) {
absl::string_view hlo_string = R"(
HloModule module
add (lhs: f32[], rhs: f32[]) -> f32[] {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT sum = f32[] add(lhs, rhs)
}
ENTRY entry {
%input = f32[2,9,8] parameter(0), sharding={replicated}
%indices = s32[4,2,4] parameter(1),
sharding={devices=[2,1,2,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
%updates = f32[4,4,8] parameter(2),
sharding={devices=[2,2,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %scatter = f32[2,9,8] scatter(%input, %indices, %updates),
to_apply=add,
update_window_dims={2},
inserted_window_dims={0,1},
scatter_dims_to_operand_dims={0,1},
index_vector_dim=1, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
AllOf(op::AllReduce(op::AllReduce(op::Scatter(
op::Select(op::Broadcast(op::Convert(op::Reshape())),
op::Broadcast(op::Constant()), op::Parameter(0)),
op::Parameter(1), op::Parameter(2)))),
op::Shape("f32[2,9,8]")));
}
TEST_F(SpmdPartitioningTest, IndexPassthroughScatter_Min) {
absl::string_view hlo_string = R"(
HloModule module
min (lhs: f32[], rhs: f32[]) -> f32[] {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT min = f32[] minimum(lhs, rhs)
}
ENTRY entry {
%input = f32[2,9,8] parameter(0), sharding={replicated}
%indices = s32[4,2,4] parameter(1), sharding={devices=[2,1,2]0,1,2,3}
%updates = f32[4,4,8] parameter(2), sharding={devices=[2,2,1]0,1,2,3}
ROOT %scatter = f32[2,9,8] scatter(%input, %indices, %updates),
to_apply=min,
update_window_dims={2},
inserted_window_dims={0,1},
scatter_dims_to_operand_dims={0,1},
index_vector_dim=1, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
AllOf(op::AllReduce(op::AllReduce(op::Scatter(
op::Select(op::Broadcast(op::Convert(op::PartitionId())),
op::Broadcast(op::Constant()), op::Parameter(0)),
op::Parameter(1), op::Parameter(2)))),
op::Shape("f32[2,9,8]")));
}
TEST_F(SpmdPartitioningTest, ScatterPartitionedOnTrivialSliceDims) {
absl::string_view hlo_string = R"(
HloModule module
add (lhs: f32[], rhs: f32[]) -> f32[] {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT sum = f32[] add(lhs, rhs)
}
ENTRY entry {
%input = f32[17,9] parameter(0), sharding={devices=[2,1]0,1}
%indices = s32[2,3] parameter(1), sharding={replicated}
%updates = f32[2,3,9] parameter(2), sharding={replicated}
ROOT %scatter = f32[17,9] scatter(%input, %indices, %updates),
to_apply=add,
update_window_dims={2},
inserted_window_dims={0},
scatter_dims_to_operand_dims={0},
index_vector_dim=2, sharding={devices=[2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto offset =
op::Reshape(op::DynamicSlice(op::Constant(), op::PartitionId()));
auto indices = op::Subtract(
op::Parameter(1), AllOf(op::Broadcast(offset), op::Shape("s32[2,3]")));
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root,
AllOf(op::Scatter(op::Parameter(0), indices, op::Parameter(2)),
op::Shape("f32[9,9]")));
}
TEST_F(SpmdPartitioningTest,
ScatterPartitionedOnTrivialSliceDims_PartialReplicate) {
absl::string_view hlo_string = R"(
HloModule module
add (lhs: f32[], rhs: f32[]) -> f32[] {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT sum = f32[] add(lhs, rhs)
}
ENTRY entry {
%input = f32[17,9] parameter(0),
sharding={devices=[2,1,2]0,1,2,3 last_tile_dim_replicate}
%indices = s32[2,3] parameter(1), sharding={replicated}
%updates = f32[2,3,9] parameter(2), sharding={replicated}
ROOT %scatter = f32[17,9] scatter(%input, %indices, %updates),
to_apply=add,
update_window_dims={2},
inserted_window_dims={0},
scatter_dims_to_operand_dims={0},
index_vector_dim=2,
sharding={devices=[2,1,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto offset =
op::Reshape(op::DynamicSlice(op::Constant(), op::PartitionId()));
auto indices = op::Subtract(
op::Parameter(1), AllOf(op::Broadcast(offset), op::Shape("s32[2,3]")));
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root,
AllOf(op::Scatter(op::Parameter(0), indices, op::Parameter(2)),
op::Shape("f32[9,9]")));
}
TEST_F(SpmdPartitioningTest, TiledReversePassthrough) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
constant = f32[3,3]{1,0} constant({{1,1,1},{1,1,1},{1,1,1}}),
sharding={devices=[2,1]0,1}
ROOT reverse = f32[3,3]{1,0} reverse(constant), dimensions={1},
sharding={devices=[2,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[2,3]{1,0}"),
op::Reverse(op::DynamicSlice(
op::Pad(op::Constant(), op::Constant()),
op::Reshape(), op::Constant()))));
}
TEST_F(SpmdPartitioningTest, TiledReversePassthroughViaReversedSharding) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
param = f32[4] parameter(0), sharding={devices=[2]0,1}
ROOT reverse = f32[4] reverse(param), dimensions={0},
sharding={devices=[2]1,0}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[2]"), op::Reverse(op::Parameter(0))));
}
TEST_F(SpmdPartitioningTest, TiledReverseSwapShards) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
param = f32[4] parameter(0), sharding={devices=[2]0,1}
ROOT reverse = f32[4] reverse(param), dimensions={0},
sharding={devices=[2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
EXPECT_THAT(root,
AllOf(op::Shape("f32[2]"),
op::Reverse(op::CollectivePermute(op::Parameter(0)))));
}
TEST_F(SpmdPartitioningTest, TiledReverseHaloExchange) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
param = f32[3] parameter(0), sharding={devices=[2]0,1}
ROOT reverse = f32[3] reverse(param), dimensions={0},
sharding={devices=[2]1,0}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
auto halo_exchange_concat =
op::Concatenate(AllOf(op::Shape("f32[1]"),
op::CollectivePermute(op::Slice(op::Parameter(0)))),
op::Slice(op::Parameter(0)));
EXPECT_THAT(root,
AllOf(op::Shape("f32[2]"), op::Reverse(halo_exchange_concat)));
}
TEST_F(SpmdPartitioningTest, MixWithManualPartitioning) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
param = (f32[8,2], f32[4,2]) parameter(0), sharding={{devices=[2,1]0,1},{manual}}
param0 = f32[8,2] get-tuple-element(param), index=0, sharding={devices=[2,1]0,1}
param1 = f32[4,2] get-tuple-element(param), index=1, sharding={manual}
to_shard = f32[4,2] custom-call(param0), custom_call_target="SPMDFullToShardShape", sharding={manual}
add = f32[4,2] add(to_shard, param1), sharding={manual}
to_full = f32[8,2] custom-call(add), custom_call_target="SPMDShardToFullShape", sharding={devices=[2,1]0,1}
mul = f32[8,2] multiply(to_full, param0), sharding={devices=[2,1]0,1}
to_shard2 = f32[4,2] custom-call(mul), custom_call_target="SPMDFullToShardShape", sharding={manual}
ROOT tuple = (f32[4,2]) tuple(to_shard2), sharding={{manual}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
HloInstruction* root = module->entry_computation()->root_instruction();
auto p0 = op::GetTupleElement(op::Parameter(0));
auto to_shard = op::Copy(p0);
auto p1 = op::GetTupleElement(op::Parameter(0));
auto mul = AllOf(op::Shape("f32[4,2]"),
op::Multiply(op::Copy(op::Add(to_shard, p1)), p0));
EXPECT_THAT(root, op::Tuple(op::Copy(mul)));
}
TEST_F(SpmdPartitioningTest, SubgroupAllToAllReshard) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[8,8,8,8] parameter(0),
sharding={devices=[2,2,1,2]0,1,2,3,4,5,6,7}
ROOT %copy = f32[8,8,8,8] copy(%param0),
sharding={devices=[1,2,2,2]0,1,4,5,2,3,6,7}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto reshape =
AllOf(op::Shape("f32[4,4,2,4,4]"), op::Reshape(op::Parameter(0)));
auto all_to_all = AllOf(op::Shape("f32[4,4,2,4,4]"), op::AllToAll(reshape));
auto xpose = AllOf(op::Shape("f32[2,4,4,4,4]"), op::Transpose(all_to_all));
EXPECT_THAT(root,
op::Copy(AllOf(op::Reshape(xpose), op::Shape("f32[8,4,4,4]"))));
EXPECT_EQ(root->operand(0)->operand(0)->operand(0)->replica_groups().size(),
4);
}
TEST_F(SpmdPartitioningTest, SubgroupAllToAllReshard2) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[8,8] parameter(0),
sharding={devices=[2,4]0,1,2,3,4,5,6,7}
ROOT %copy = f32[8,8] copy(%param0),
sharding={devices=[4,2]0,1,4,5,2,3,6,7}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto all_to_all = op::AllToAll(
AllOf(op::Shape("f32[2,2,2]"), op::Reshape(op::Parameter(0))));
auto reshape =
AllOf(op::Shape("f32[2,4]"), op::Reshape(op::Transpose(all_to_all)));
EXPECT_THAT(root, op::Copy(op::CollectivePermute(reshape)));
}
TEST_F(SpmdPartitioningTest, SubgroupAllToAllReshard3) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[8,8,8] parameter(0),
sharding={devices=[2,4,1]0,1,2,3,4,5,6,7}
ROOT %copy = f32[8,8,8] copy(%param0),
sharding={devices=[1,2,4]0,1,4,5,2,3,6,7}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto all_to_all = op::AllToAll(
AllOf(op::Shape("f32[4,2,4,2]"), op::Reshape(op::Parameter(0))));
auto reshape =
AllOf(op::Shape("f32[4,8,2]"), op::Reshape(op::Transpose(all_to_all)));
auto all_to_all2 =
op::AllToAll(AllOf(op::Shape("f32[4,2,4,2]"), op::Reshape(reshape)));
auto reshape2 =
AllOf(op::Shape("f32[8,4,2]"), op::Reshape(op::Transpose(all_to_all2)));
EXPECT_THAT(root, op::Copy(op::CollectivePermute(reshape2)));
}
TEST_F(SpmdPartitioningTest, Dot2DPartitionedNonContractingAndContracting0) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[48,12] parameter(0), sharding={devices=[2,2]0,1,2,3}
%rhs = f32[32,12] parameter(1), sharding={devices=[2,2]0,2,1,3}
ROOT %dot = f32[48,32] dot(%lhs, %rhs),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={1}, rhs_contracting_dims={1},
sharding={devices=[2,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[24,6]"), op::Parameter(0));
auto partial_replicated_lhs =
AllOf(op::Shape("f32[24,12]"),
op::AllReduce(op::DynamicUpdateSlice(_, lhs, _, _)));
auto rhs = AllOf(op::Shape("f32[16,6]"), op::Parameter(1));
auto partial_replicated_rhs =
AllOf(op::Shape("f32[16,12]"),
op::AllReduce(op::DynamicUpdateSlice(_, rhs, _, _)));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root,
AllOf(op::Dot(partial_replicated_lhs, partial_replicated_rhs),
op::Shape("f32[24,16]")));
}
TEST_F(SpmdPartitioningTest, Dot2DPartitionedNonContractingAndContracting1) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[48,100] parameter(0), sharding={devices=[2,2]0,1,2,3}
%rhs = f32[32,100] parameter(1), sharding={devices=[2,2]0,1,2,3}
ROOT %dot = f32[48,32] dot(%lhs, %rhs),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={1}, rhs_contracting_dims={1},
sharding={devices=[2,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[24,50]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[16,50]"), op::Parameter(1));
auto partial_replicated_rhs =
AllOf(op::Shape("f32[32,50]"),
op::AllReduce(op::DynamicUpdateSlice(_, rhs, _, _)));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root, AllOf(op::Shape("f32[24,16]"),
op::DynamicSlice(
op::AllReduce(AllOf(op::Dot(lhs, partial_replicated_rhs),
op::Shape("f32[24,32]"))),
_, _)));
}
TEST_F(SpmdPartitioningTest, Dot2DPartitionedNonContractingAndContracting2) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[48,100] parameter(0), sharding={replicated}
%rhs = f32[32,100] parameter(1), sharding={devices=[2,2]0,1,2,3}
ROOT %dot = f32[48,32] dot(%lhs, %rhs),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={1}, rhs_contracting_dims={1},
sharding={devices=[2,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[48,100]"), op::Parameter(0));
auto lhs_slice = AllOf(op::Shape("f32[24,100]"), op::DynamicSlice(lhs, _, _));
auto rhs = AllOf(op::Shape("f32[16,50]"), op::Parameter(1));
auto partial_replicated_rhs = AllOf(
op::Shape("f32[16,100]"), op::AllReduce(op::DynamicUpdateSlice(
_, op::CollectivePermute(rhs), _, _)));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[24,16]"),
op::Dot(lhs_slice, partial_replicated_rhs)));
}
TEST_F(SpmdPartitioningTest, Dot2DPartitionedNoncontractingAndContracting3) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[23,24] parameter(0), sharding={devices=[2,1,2]0,1,2,3 last_tile_dim_replicate}
%rhs = f32[23,32] parameter(1), sharding={devices=[2,2]0,1,2,3}
ROOT %dot = f32[24,32] dot(%lhs, %rhs),
lhs_contracting_dims={0}, rhs_contracting_dims={0},
sharding={devices=[2,2]1,0,3,2}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[12,24]"), op::Parameter(0));
auto masked_lhs = op::Select(_, lhs, op::Broadcast(op::Constant()));
auto rhs = AllOf(op::Shape("f32[12,16]"), op::Parameter(1));
auto masked_rhs = op::Select(_, rhs, op::Broadcast(op::Constant()));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(
root,
AllOf(op::Shape("f32[12,16]"),
op::DynamicSlice(
AllOf(op::Shape("f32[24,16]"),
op::AllReduce(op::Dot(
masked_lhs, op::CollectivePermute(masked_rhs)))),
_, _)));
}
TEST_F(SpmdPartitioningTest, Dot2DPartitionedBatchAndNonContracting) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[4,24,100] parameter(0), sharding={devices=[2,2,1]0,1,2,3}
%rhs = f32[4,32,100] parameter(1), sharding={devices=[2,2,1]0,1,2,3}
ROOT %dot = f32[4,24,32] dot(%lhs, %rhs),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2}, rhs_contracting_dims={2},
sharding={devices=[2,2,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[2,12,100]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[2,16,100]"), op::Parameter(1));
auto partial_replicated_rhs =
AllOf(op::Shape("f32[2,32,100]"),
op::AllReduce(op::DynamicUpdateSlice(_, rhs, _, _, _)));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[2,12,32]"),
op::Dot(lhs, partial_replicated_rhs)));
}
TEST_F(SpmdPartitioningTest, Dot2DPartitionedBatchAndContracting) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[4,24,100] parameter(0), sharding={devices=[2,1,2]0,1,2,3}
%rhs = f32[4,32,100] parameter(1), sharding={devices=[1,2,2]0,1,2,3}
ROOT %dot = f32[4,24,32] dot(%lhs, %rhs),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2}, rhs_contracting_dims={2},
sharding={devices=[2,2,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[2,24,50]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[4,16,50]"), op::Parameter(1));
auto resharded_rhs =
AllOf(op::Shape("f32[2,32,50]"),
op::Reshape(op::Transpose(op::AllToAll(op::Reshape(rhs)))));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[2,12,32]"),
op::DynamicSlice(
AllOf(op::Shape("f32[2,24,32]"),
op::AllReduce(op::Dot(lhs, resharded_rhs))),
_, _, _)));
}
TEST_F(SpmdPartitioningTest, Dot2DPartitionedBatchAndContracting2) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[4,24,100] parameter(0), sharding={devices=[2,1,2]0,1,2,3}
%rhs = f32[4,32,100] parameter(1), sharding={replicated}
ROOT %dot = f32[4,24,32] dot(%lhs, %rhs),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2}, rhs_contracting_dims={2},
sharding={devices=[2,2,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[2,24,50]"), op::Parameter(0));
auto resharded_lhs =
AllOf(op::Shape("f32[2,12,100]"),
op::Reshape(op::Transpose(op::AllToAll(op::Reshape(lhs)))));
auto rhs = AllOf(op::Shape("f32[4,32,100]"), op::Parameter(1));
auto rhs_slice =
AllOf(op::Shape("f32[2,32,100]"), op::DynamicSlice(rhs, _, _, _));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[2,12,32]"),
op::Dot(resharded_lhs, rhs_slice)));
}
TEST_F(SpmdPartitioningTest,
Dot2DPartitionedBatchNonContractingAndContracting) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[4,24,100] parameter(0), sharding={devices=[2,1,2]0,1,2,3}
%rhs = f32[4,32,100] parameter(1), sharding={devices=[2,2,1]0,1,2,3}
ROOT %dot = f32[4,24,32] dot(%lhs, %rhs),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2}, rhs_contracting_dims={2},
sharding={devices=[2,1,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[2,24,50]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[2,16,100]"), op::Parameter(1));
auto partial_replicated_lhs =
AllOf(op::Shape("f32[2,24,100]"),
op::AllReduce(op::DynamicUpdateSlice(_, lhs, _, _, _)));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[2,24,16]"),
op::Dot(partial_replicated_lhs, rhs)));
}
TEST_F(SpmdPartitioningTest, Dot2DPartitionedBatchAndReshard) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[4,8,24,100] parameter(0), sharding={devices=[2,1,2,1]0,1,2,3}
%rhs = f32[4,8,32,100] parameter(1), sharding={devices=[2,1,2,1]0,1,2,3}
ROOT %dot = f32[4,8,24,32] dot(%lhs, %rhs),
lhs_batch_dims={0,1}, rhs_batch_dims={0,1},
lhs_contracting_dims={3}, rhs_contracting_dims={3},
sharding={devices=[1,2,2,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[2,8,12,100]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[2,8,16,100]"), op::Parameter(1));
auto partial_replicated_rhs =
AllOf(op::Shape("f32[2,8,32,100]"),
op::AllReduce(op::DynamicUpdateSlice(_, rhs, _, _, _, _)));
auto dot =
AllOf(op::Shape("f32[2,8,12,32]"), op::Dot(lhs, partial_replicated_rhs));
auto reshape = AllOf(op::Shape("f32[2,2,4,12,32]"), op::Reshape(dot));
auto all_to_all = AllOf(op::Shape("f32[2,2,4,12,32]"), op::AllToAll(reshape));
auto xpose = AllOf(op::Shape("f32[2,2,4,12,32]"), op::Transpose(all_to_all));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[4,4,12,32]"), op::Reshape(xpose)));
}
TEST_F(SpmdPartitioningTest, SimpleDotPartial) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[2,24,100] parameter(0),
sharding={devices=[2,1,1,2]0,1,2,3 last_tile_dim_replicate}
%rhs = f32[2,32,100] parameter(1),
sharding={devices=[2,1,1,2]0,1,2,3 last_tile_dim_replicate}
ROOT %dot = f32[2,24,32] dot(%lhs, %rhs),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2}, rhs_contracting_dims={2},
sharding={devices=[2,1,1,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[1,24,100]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[1,32,100]"), op::Parameter(1));
auto dot = AllOf(op::Shape("f32[1,24,32]"), op::Dot(lhs, rhs));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, dot);
}
TEST_F(SpmdPartitioningTest, DotPartialContracting) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[24,100] parameter(0),
sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
%rhs = f32[32,100] parameter(1),
sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
ROOT %dot = f32[24,32] dot(%lhs, %rhs),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={1}, rhs_contracting_dims={1},
sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[24,50]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[32,50]"), op::Parameter(1));
auto dot = AllOf(op::Shape("f32[24,32]"), op::Dot(lhs, rhs));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, op::AllReduce(dot));
}
TEST_F(SpmdPartitioningTest, DotPartialContracting2) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[24,100] parameter(0),
sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
%rhs = f32[32,100] parameter(1),
sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
ROOT %dot = f32[24,32] dot(%lhs, %rhs),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={1}, rhs_contracting_dims={1},
sharding={devices=[2,1,2]0,2,1,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[24,50]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[32,50]"), op::Parameter(1));
auto dot =
AllOf(op::Shape("f32[12,32]"),
op::Dot(AllOf(op::Shape("f32[12,50]"), op::DynamicSlice(lhs, _, _)),
rhs));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, op::AllReduce(dot));
}
TEST_F(SpmdPartitioningTest, DotPartialContracting3) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[24,100] parameter(0),
sharding={devices=[1,2,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
%rhs = f32[32,100] parameter(1),
sharding={devices=[1,2,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %dot = f32[24,32] dot(%lhs, %rhs),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={1}, rhs_contracting_dims={1},
sharding={devices=[1,2,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[24,50]"), op::Parameter(0));
auto rhs =
AllOf(op::Shape("f32[16,50]"), op::DynamicSlice(op::Parameter(1), _, _));
auto dot = AllOf(op::Shape("f32[24,16]"), op::Dot(lhs, rhs));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, op::CollectivePermute(op::AllReduce(dot)));
}
TEST_F(SpmdPartitioningTest, DotBatchAndPartialContracting) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[4,24,100] parameter(0),
sharding={devices=[2,2,2]0,1,2,3,4,5,6,7}
%rhs = f32[4,32,100] parameter(1),
sharding={devices=[2,1,2,2]0,2,1,3,4,6,5,7 last_tile_dim_replicate}
ROOT %dot = f32[4,24,32] dot(%lhs, %rhs),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={2}, rhs_contracting_dims={2},
sharding={devices=[2,2,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[2,12,50]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[2,32,50]"), op::Parameter(1));
auto dot = AllOf(op::Shape("f32[2,12,32]"), op::Dot(lhs, rhs));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, op::AllReduce(dot));
}
TEST_F(SpmdPartitioningTest, DotPartialNonContracting) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[24,8,100] parameter(0),
sharding={devices=[2,1,1,2]0,1,2,3 last_tile_dim_replicate}
%rhs = f32[32,100] parameter(1), sharding={devices=[2,2]0,2,1,3}
ROOT %dot = f32[24,8,32] dot(%lhs, %rhs),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={2}, rhs_contracting_dims={1},
sharding={devices=[2,1,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[12,8,100]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[16,50]"), op::Parameter(1));
auto partially_replicated_rhs =
AllOf(op::Shape("f32[16,100]"),
op::AllReduce(op::DynamicUpdateSlice(op::Broadcast(_), rhs, _, _)));
auto dot =
AllOf(op::Shape("f32[12,8,16]"), op::Dot(lhs, partially_replicated_rhs));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, dot);
}
TEST_F(SpmdPartitioningTest, DotPartialNonContractingPartialMatch) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[24,8,100] parameter(0), sharding={devices=[2,2,1]0,1,2,3}
%rhs = f32[32,100] parameter(1),
sharding={devices=[2,1,2]0,2,1,3 last_tile_dim_replicate}
ROOT %dot = f32[24,8,32] dot(%lhs, %rhs),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={2}, rhs_contracting_dims={1},
sharding={devices=[2,1,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[12,4,100]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[16,100]"), op::Parameter(1));
auto partially_replicated_lhs = AllOf(
op::Shape("f32[12,8,100]"),
op::AllReduce(op::DynamicUpdateSlice(op::Broadcast(_), lhs, _, _, _)));
auto dot =
AllOf(op::Shape("f32[12,8,16]"), op::Dot(partially_replicated_lhs, rhs));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, dot);
}
TEST_F(SpmdPartitioningTest, DotPartialContractingPartialMatch) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[24,8,100] parameter(0), sharding={devices=[1,2,2]0,1,2,3}
%rhs = f32[32,8,100] parameter(1),
sharding={devices=[1,1,2,2]0,2,1,3 last_tile_dim_replicate}
ROOT %dot = f32[24,32] dot(%lhs, %rhs),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={1,2}, rhs_contracting_dims={1,2},
sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[24,4,50]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[32,8,50]"), op::Parameter(1));
auto dot = AllOf(op::Shape("f32[24,32]"),
op::Dot(lhs, AllOf(op::Shape("f32[32,4,50]"),
op::DynamicSlice(rhs, _, _, _))));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, op::AllReduce(op::AllReduce(dot)));
}
TEST_F(SpmdPartitioningTest, DotNonContractingPartialMatchContractingMatch) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[24,8,100] parameter(0), sharding={devices=[2,1,2]0,1,2,3}
%rhs = f32[100,50] parameter(1), sharding={devices=[2,2]0,2,1,3}
ROOT %dot = f32[24,8,50] dot(%lhs, %rhs),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={2}, rhs_contracting_dims={0},
sharding={devices=[2,2,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[12,8,50]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[50,25]"), op::Parameter(1));
auto dot = AllOf(
op::Shape("f32[12,8,50]"),
op::Dot(lhs, AllOf(op::Shape("f32[50,50]"),
op::AllReduce(op::DynamicUpdateSlice(_, rhs, _, _)))));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[12,4,50]"),
op::DynamicSlice(op::AllReduce(dot), _, _, _)))
<< module->ToString();
}
TEST_F(SpmdPartitioningTest, DotLHSMutiNonContractingRHSNotMatch) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[24,8,10] parameter(0), sharding={devices=[2,2,1]0,1,2,3}
%rhs = f32[10,50] parameter(1),
sharding={devices=[2,1,2]0,2,1,3 last_tile_dim_replicate}
ROOT %dot = f32[24,8,50] dot(%lhs, %rhs),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={2}, rhs_contracting_dims={0},
sharding={devices=[2,2,1]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto lhs = AllOf(op::Shape("f32[12,4,10]"), op::Parameter(0));
auto rhs = AllOf(op::Shape("f32[5,50]"), op::Parameter(1));
auto dot = AllOf(
op::Shape("f32[12,4,50]"),
op::Dot(lhs, AllOf(op::Shape("f32[10,50]"),
op::AllReduce(op::DynamicUpdateSlice(_, rhs, _, _)))));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, dot) << module->ToString();
}
TEST_F(SpmdPartitioningTest,
ElementwiseTest_PartialReplicateToTiledHaloExchange) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
constant = f32[6,3]{1,0}
constant({{1,3,7},{5,1,4},{1,2,8},{2,3,7},{5,2,4},{2,2,8}}),
sharding={replicated}
constant.1 = f32[6,3]{1,0}
constant({{2,7,2},{2,9,2},{2,6,2},{3,7,2},{2,9,3},{2,3,2}}),
sharding={replicated}
multiply = f32[6,3]{1,0} multiply(constant, constant.1),
sharding={devices=[2,1,2]0,1,2,3 last_tile_dim_replicate}
ROOT add = f32[6,3]{1,0} add(multiply, constant.1),
sharding={devices=[4,1]0,1,2,3}
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto partial_replicate_lhs =
AllOf(op::Shape("f32[3,3]"),
op::DynamicSlice(op::Constant(), op::Reshape(), op::Constant()));
auto partial_replicate_rhs =
AllOf(op::Shape("f32[3,3]"),
op::DynamicSlice(op::Constant(), op::Reshape(), op::Constant()));
auto multiply =
AllOf(op::Shape("f32[3,3]"),
op::Multiply(partial_replicate_lhs, partial_replicate_rhs));
auto right_halo =
AllOf(op::Shape("f32[1,3]"), op::CollectivePermute(op::Slice(multiply)));
auto add_lhs = AllOf(
op::Shape("f32[2,3]"),
op::DynamicSlice(
op::DynamicSlice(
op::Pad(op::Concatenate(multiply, right_halo), op::Constant()),
op::Reshape(), op::Constant()),
op::Subtract(), op::Subtract()));
auto add_rhs = AllOf(op::Shape("f32[2,3]"),
op::DynamicSlice(op::Pad(op::Constant(), op::Constant()),
op::Reshape(), op::Constant()));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, AllOf(op::Shape("f32[2,3]"), op::Add(add_lhs, add_rhs)));
}
TEST_F(SpmdPartitioningTest, TileToPartialReplicateReshard) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[8,8] parameter(0)
%copy = f32[8,8] copy(%param0),
sharding={devices=[2,2]0,1,2,3}
ROOT %copy0 = f32[8,8] copy(%copy),
sharding={devices=[2,1,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto tiled = AllOf(op::Shape("f32[4,4]"),
op::Copy(op::DynamicSlice(op::Parameter(0), op::Reshape(),
op::Reshape())));
auto partially_replicated = AllOf(
op::Shape("f32[4,8]"), op::Copy(op::AllReduce(op::DynamicUpdateSlice(
op::Broadcast(_), tiled, _, _))));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, partially_replicated);
}
TEST_F(SpmdPartitioningTest, TileToPartialReplicateReshardUnevenPartition) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[8,8] parameter(0),
sharding={devices=[2,3]0,1,2,3,4,5}
ROOT %copy0 = f32[8,8] copy(%param0),
sharding={devices=[1,2,3]0,1,2,3,4,5 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/6));
VLOG(1) << module->ToString();
auto tiled = AllOf(op::Shape("f32[4,3]"), op::Parameter(0));
auto partially_replicated = AllOf(
op::Shape("f32[8,4]"),
op::Copy(op::Reshape(
op::Transpose(op::AllToAll(op::Reshape(op::Slice(op::AllReduce(
op::DynamicUpdateSlice(op::Broadcast(), tiled, _, _)))))))));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, partially_replicated);
}
TEST_F(SpmdPartitioningTest, PartialReplicateToTileReshardUnevenPartition) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[8,8] parameter(0),
sharding={devices=[1,2,3]0,1,2,3,4,5 last_tile_dim_replicate}
ROOT %copy0 = f32[8,8] copy(%param0),
sharding={devices=[2,3]0,1,2,3,4,5}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/6));
VLOG(1) << module->ToString();
auto partial_replicated = AllOf(op::Shape("f32[8,4]"), op::Parameter(0));
auto tiled = AllOf(
op::Shape("f32[4,3]"),
op::Copy(op::DynamicSlice(op::Pad(op::Reshape(op::Transpose(op::AllToAll(
op::Reshape(partial_replicated)))),
_),
_, _)));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, tiled);
}
TEST_F(SpmdPartitioningTest, PartialReplicateToTileReshard) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[8,8] parameter(0)
%copy = f32[8,8] copy(%param0),
sharding={devices=[2,1,2]0,1,2,3 last_tile_dim_replicate}
ROOT %copy0 = f32[8,8] copy(%copy),
sharding={devices=[2,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto partially_replicated =
AllOf(op::Shape("f32[4,8]"),
op::Copy(op::DynamicSlice(op::Parameter(0), op::Reshape(),
op::Constant())));
auto tiled =
AllOf(op::Shape("f32[4,4]"),
op::Copy(op::DynamicSlice(partially_replicated, op::Subtract(),
op::Subtract())));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, tiled);
}
TEST_F(SpmdPartitioningTest,
PartialReplicateToPartialReplicateReshard_AllReduce) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[8,8] parameter(0)
%copy = f32[8,8] copy(param0),
sharding={devices=[2,2,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %copy0 = f32[8,8] copy(%copy),
sharding={devices=[2,1,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto partially_replicated_init =
AllOf(op::Shape("f32[4,4]"),
op::Copy(op::DynamicSlice(op::Parameter(0), op::Reshape(),
op::Reshape())));
auto partially_replicated =
AllOf(op::Shape("f32[4,8]"),
op::Copy(op::AllReduce(op::DynamicUpdateSlice(
op::Broadcast(_), partially_replicated_init, _, _))));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, partially_replicated);
}
TEST_F(SpmdPartitioningTest,
PartialReplicateToPartialReplicateReshard_DynamicSlice) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[8,8] parameter(0)
%copy = f32[8,8] copy(%param0),
sharding={devices=[2,1,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %copy0 = f32[8,8] copy(%copy),
sharding={devices=[2,2,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto partially_replicated =
AllOf(op::Shape("f32[4,8]"),
op::Copy(op::DynamicSlice(op::Parameter(0), op::Reshape(),
op::Constant())));
auto tiled =
AllOf(op::Shape("f32[4,4]"),
op::Copy(op::DynamicSlice(partially_replicated, op::Subtract(),
op::Subtract())));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, tiled);
}
TEST_F(SpmdPartitioningTest,
PartialReplicateToPartialReplicateReshardWithCollectivePermute) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[8,8] parameter(0)
%copy = f32[8,8] copy(param0),
sharding={devices=[2,2,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %copy0 = f32[8,8] copy(%copy),
sharding={devices=[1,2,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto partially_replicated_init =
AllOf(op::Shape("f32[4,4]"),
op::CollectivePermute(op::Copy(op::DynamicSlice(
op::Parameter(0), op::Reshape(), op::Reshape()))));
auto partially_replicated =
AllOf(op::Shape("f32[8,4]"),
op::Copy(op::AllReduce(op::DynamicUpdateSlice(
op::Broadcast(_), partially_replicated_init, _, _))));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, partially_replicated);
}
TEST_F(SpmdPartitioningTest,
PartialReplicateToPartialReplicateReshardCollectivePermute1) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[8,8] parameter(0)
%copy = f32[8,8] copy(%param0),
sharding={devices=[1,2,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %copy0 = f32[8,8] copy(%copy),
sharding={devices=[2,2,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto partially_replicated =
AllOf(op::Shape("f32[8,4]"),
op::Copy(op::DynamicSlice(op::Parameter(0), op::Constant(),
op::Reshape())));
auto tiled =
AllOf(op::Shape("f32[4,4]"),
op::Copy(op::CollectivePermute(op::DynamicSlice(
partially_replicated, op::Subtract(), op::Subtract()))));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, tiled);
}
TEST_F(SpmdPartitioningTest,
PartialReplicateToPartialReplicateReshardHaloExchange) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[6,3] parameter(0)
%copy = f32[6,3] copy(param0),
sharding={devices=[4,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %copy0 = f32[6,3] copy(%copy),
sharding={devices=[2,1,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto partially_replicated_init =
AllOf(op::Shape("f32[2,3]"),
op::Copy(op::DynamicSlice(op::Pad(op::Parameter(0), op::Constant()),
op::Reshape(), op::Constant())));
auto slice =
AllOf(op::Shape("f32[2,3]"),
op::DynamicSlice(op::Concatenate(op::CollectivePermute(op::Slice(
partially_replicated_init)),
partially_replicated_init),
_, _));
auto partially_replicated =
AllOf(op::Shape("f32[3,3]"),
op::Copy(op::Slice(op::AllReduce(
op::DynamicUpdateSlice(op::Broadcast(_), slice, _, _)))));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, partially_replicated);
}
TEST_F(SpmdPartitioningTest,
PartialReplicateToPartialReplicateReshardHaloExchange1) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[6,3] parameter(0)
%copy = f32[6,3] copy(param0),
sharding={devices=[2,1,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %copy0 = f32[6,3] copy(%copy),
sharding={devices=[4,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto partially_replicated_init =
AllOf(op::Shape("f32[3,3]"),
op::Copy(op::DynamicSlice(op::Parameter(0), op::Reshape(),
op::Constant())));
auto slice = AllOf(
op::Shape("f32[4,3]"),
op::DynamicSlice(op::Pad(op::Concatenate(partially_replicated_init,
op::CollectivePermute(op::Slice(
partially_replicated_init))),
op::Constant()),
_, _));
auto partially_replicated =
AllOf(op::Shape("f32[2,3]"), op::Copy(op::DynamicSlice(slice, _, _)));
auto root = module->entry_computation()->root_instruction();
EXPECT_THAT(root, partially_replicated);
}
TEST_F(SpmdPartitioningTest, PartitionConvWithBathGroupCount) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,1,1,2]0,1}
%rhs = f32[16,801,1,1024] parameter(1)
%rhs.copy = f32[16,801,1,1024] copy(%rhs),
sharding={devices=[1,1,1,2]0,1}
ROOT %conv = f32[5,1,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=f01b_i01o->01bf,batch_group_count=1024,
window={size=801x1 pad=2_2x0_0},
sharding={devices=[1,1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[16,801,1,512]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[16,801,1,512]"));
EXPECT_THAT(root,
AllOf(op::Convolution(lhs, rhs), op::Shape("f32[5,1,1,512]")));
}
TEST_F(SpmdPartitioningTest, PartitionConvWithBathGroupCountRHSAlignWithLHS) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,1,1,2]0,1}
%rhs = f32[16,801,1,1024] parameter(1)
%rhs.copy = f32[16,801,1,1024] copy(%rhs),
sharding={devices=[1,2,1,1]0,1}
ROOT %conv = f32[5,1,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=f01b_i01o->01bf,batch_group_count=1024,
window={size=801x1 pad=2_2x0_0},
sharding={devices=[1,1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[16,801,1,512]"));
auto rhs = AllOf(op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Constant())),
op::Shape("f32[16,401,1,1024]"));
auto resharded_rhs = AllOf(
op::Slice(op::Reshape(op::Transpose(op::AllToAll(op::Reshape(rhs))))),
op::Shape("f32[16,801,1,512]"));
EXPECT_THAT(root, AllOf(op::Convolution(lhs, resharded_rhs),
op::Shape("f32[5,1,1,512]")));
}
TEST_F(SpmdPartitioningTest, PartitionConvWithBathGroupCountLHSAlignWithRHS) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,2,1,1]0,1}
%rhs = f32[16,801,1,1024] parameter(1)
%rhs.copy = f32[16,801,1,1024] copy(%rhs),
sharding={devices=[1,1,1,2]0,1}
ROOT %conv = f32[5,1,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=f01b_i01o->01bf,batch_group_count=1024,
window={size=801x1 pad=2_2x0_0},
sharding={devices=[1,1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[16,801,1,512]"));
auto lhs = AllOf(op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Constant())),
op::Shape("f32[16,401,1,1024]"));
auto resharded_lhs = AllOf(
op::Slice(op::Reshape(op::Transpose(op::AllToAll(op::Reshape(lhs))))),
op::Shape("f32[16,801,1,512]"));
EXPECT_THAT(root, AllOf(op::Convolution(resharded_lhs, rhs),
op::Shape("f32[5,1,1,512]")));
}
TEST_F(SpmdPartitioningTest,
PartitionConvWithBathGroupCountOutputAlignWithLHS) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,1,1,2]0,1}
%rhs = f32[16,801,1,1024] parameter(1)
%rhs.copy = f32[16,801,1,1024] copy(%rhs),
sharding={devices=[1,1,1,2]0,1}
ROOT %conv = f32[5,1,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=f01b_i01o->01bf,batch_group_count=1024,
window={size=801x1 pad=2_2x0_0},
sharding={devices=[2,1,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[16,801,1,512]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[16,801,1,512]"));
auto conv = AllOf(op::Convolution(lhs, rhs), op::Shape("f32[5,1,1,512]"));
EXPECT_THAT(root, AllOf(op::Reshape(op::Transpose(op::AllToAll(
op::Reshape(op::Pad(conv, op::Constant()))))),
op::Shape("f32[3,1,1,1024]")));
}
TEST_F(SpmdPartitioningTest,
PartitionConvWithBathGroupCountOutputAlignWithRHS) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,2,1,1]0,1}
%rhs = f32[16,801,1,1024] parameter(1)
%rhs.copy = f32[16,801,1,1024] copy(%rhs),
sharding={devices=[1,1,1,2]0,1}
ROOT %conv = f32[5,1,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=f01b_i01o->01bf,batch_group_count=1024,
window={size=801x1 pad=2_2x0_0},
sharding={devices=[2,1,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[16,801,1,512]"));
auto lhs = AllOf(op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Constant())),
op::Shape("f32[16,401,1,1024]"));
auto resharded_lhs = AllOf(
op::Slice(op::Reshape(op::Transpose(op::AllToAll(op::Reshape(lhs))))),
op::Shape("f32[16,801,1,512]"));
auto conv =
AllOf(op::Convolution(resharded_lhs, rhs), op::Shape("f32[5,1,1,512]"));
EXPECT_THAT(root, AllOf(op::Reshape(op::Transpose(op::AllToAll(
op::Reshape(op::Pad(conv, op::Constant()))))),
op::Shape("f32[3,1,1,1024]")));
}
TEST_F(SpmdPartitioningTest, PartitionConvWithFeatureGroupCount) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,1,1,2]0,1}
%rhs = f32[5,1,1,1024] parameter(1)
%rhs.copy = f32[5,1,1,1024] copy(%rhs),
sharding={devices=[1,1,1,2]0,1}
ROOT %conv = f32[16,801,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=b01f_01io->b01f,feature_group_count=1024,
window={size=5x1 pad=2_2x0_0},
sharding={devices=[1,1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[16,801,1,512]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[5,1,1,512]"));
EXPECT_THAT(root,
AllOf(op::Convolution(lhs, rhs), op::Shape("f32[16,801,1,512]")));
}
TEST_F(SpmdPartitioningTest,
PartitionConvWithFeatureGroupCountRHSAlignWithLHS) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,1,1,2]0,1}
%rhs = f32[5,1,1,1024] parameter(1)
%rhs.copy = f32[5,1,1,1024] copy(%rhs),
sharding={devices=[2,1,1,1]0,1}
ROOT %conv = f32[16,801,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=b01f_01io->b01f,feature_group_count=1024,
window={size=5x1 pad=2_2x0_0},
sharding={devices=[1,1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[16,801,1,512]"));
auto rhs = AllOf(op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Reshape(),
op::Constant(), op::Constant(), op::Constant())),
op::Shape("f32[3,1,1,1024]"));
auto resharded_rhs = AllOf(
op::Slice(op::Reshape(op::Transpose(op::AllToAll(op::Reshape(rhs))))),
op::Shape("f32[5,1,1,512]"));
EXPECT_THAT(root, AllOf(op::Convolution(lhs, resharded_rhs),
op::Shape("f32[16,801,1,512]")));
}
TEST_F(SpmdPartitioningTest,
PartitionConvWithFeatureGroupCountLHSAlignWithRHS) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,2,1,1]0,1}
%rhs = f32[5,1,1,1024] parameter(1)
%rhs.copy = f32[5,1,1,1024] copy(%rhs),
sharding={devices=[1,1,1,2]0,1}
ROOT %conv = f32[16,801,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=b01f_01io->b01f,feature_group_count=1024,
window={size=5x1 pad=2_2x0_0},
sharding={devices=[1,1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Constant())),
op::Shape("f32[16,401,1,1024]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[5,1,1,512]"));
auto resharded_lhs = AllOf(
op::Slice(op::Reshape(op::Transpose(op::AllToAll(op::Reshape(lhs))))),
op::Shape("f32[16,801,1,512]"));
EXPECT_THAT(root, AllOf(op::Convolution(resharded_lhs, rhs),
op::Shape("f32[16,801,1,512]")));
}
TEST_F(SpmdPartitioningTest,
PartitionConvWithFeatureGroupCountAlignOuputWithLHS) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,1,1,2]0,1}
%rhs = f32[5,1,1,1024] parameter(1)
%rhs.copy = f32[5,1,1,1024] copy(%rhs),
sharding={devices=[1,1,1,2]0,1}
ROOT %conv = f32[16,801,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=b01f_01io->b01f,feature_group_count=1024,
window={size=5x1 pad=2_2x0_0},
sharding={devices=[2,1,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[16,801,1,512]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[5,1,1,512]"));
auto conv = AllOf(op::Convolution(lhs, rhs), op::Shape("f32[16,801,1,512]"));
EXPECT_THAT(root,
AllOf(op::Reshape(op::Transpose(op::AllToAll(op::Reshape(conv)))),
op::Shape("f32[8,801,1,1024]")));
}
TEST_F(SpmdPartitioningTest,
PartitionConvGroupOnFeatureGroupCount_RHSPartialReplicate) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,2,1,2]0,1,2,3}
%rhs = f32[5,1,1,1024] parameter(1)
%rhs.copy = f32[5,1,1,1024] copy(%rhs),
sharding={devices=[1,1,1,2,2]0,2,1,3 last_tile_dim_replicate}
ROOT %conv = f32[16,801,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=b01f_01io->b01f,feature_group_count=1024,
window={size=5x1 pad=2_2x0_0},
sharding={devices=[1,2,1,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Reshape())),
op::Shape("f32[16,401,1,512]"));
auto left_halo = AllOf(op::Shape("f32[16,2, 1, 512]"),
op::CollectivePermute(op::Slice(lhs)));
auto right_halo = AllOf(op::Shape("f32[16,2, 1, 512]"),
op::CollectivePermute(op::Slice(lhs)));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[5,1,1,512]"));
EXPECT_THAT(
root,
AllOf(op::Convolution(
op::Select(_, op::Concatenate(left_halo, lhs, right_halo), _),
rhs),
op::Shape("f32[16, 401, 1, 512]")));
}
TEST_F(SpmdPartitioningTest,
PartitionConvGroupOnFeatureGroupCount_RHSAlignWithOutput) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,2,1,2]0,1,2,3}
%rhs = f32[5,1,1,1024] parameter(1), sharding={replicated}
ROOT %conv = f32[16,801,1,1024] convolution(%lhs.copy, %rhs),
dim_labels=b01f_01io->b01f,feature_group_count=1024,
window={size=5x1 pad=2_2x0_0},
sharding={devices=[1,2,1,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Reshape())),
op::Shape("f32[16,401,1,512]"));
auto left_halo = AllOf(op::Shape("f32[16,2, 1, 512]"),
op::CollectivePermute(op::Slice(lhs)));
auto right_halo = AllOf(op::Shape("f32[16,2, 1, 512]"),
op::CollectivePermute(op::Slice(lhs)));
auto rhs =
AllOf(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape()),
op::Shape("f32[5,1,1,512]"));
EXPECT_THAT(
root,
AllOf(op::Convolution(
op::Select(_, op::Concatenate(left_halo, lhs, right_halo), _),
rhs),
op::Shape("f32[16, 401, 1, 512]")));
}
TEST_F(SpmdPartitioningTest,
PartitionConvGroupOnFeatureGroupCount_LHSAlignWithOutput) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[2,1,1,1,2]0,1,2,3 last_tile_dim_replicate}
%rhs = f32[5,1,1,1024] parameter(1)
%rhs.copy = f32[5,1,1,1024] copy(%rhs),
sharding={devices=[1,1,1,2,2]0,2,1,3 last_tile_dim_replicate}
ROOT %conv = f32[16,801,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=b01f_01io->b01f,feature_group_count=1024,
window={size=5x1 pad=2_2x0_0},
sharding={devices=[1,2,1,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Reshape(), op::Constant(),
op::Constant(), op::Constant())),
op::Shape("f32[8,801,1,1024]"));
auto resharded_lhs =
AllOf(op::Reshape(op::Transpose(op::AllToAll(op::Reshape(
op::Pad(op::DynamicSlice(lhs, op::Subtract(), op::Subtract(),
op::Subtract(), op::Subtract()),
op::Constant()))))),
op::Shape("f32[16,401,1,512]"));
auto left_halo = AllOf(op::Shape("f32[16,2, 1, 512]"),
op::CollectivePermute(op::Slice(resharded_lhs)));
auto right_halo = AllOf(op::Shape("f32[16,2, 1, 512]"),
op::CollectivePermute(op::Slice(resharded_lhs)));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[5,1,1,512]"));
EXPECT_THAT(
root,
AllOf(
op::Convolution(
op::Select(
_, op::Concatenate(left_halo, resharded_lhs, right_halo), _),
rhs),
op::Shape("f32[16, 401, 1, 512]")));
}
TEST_F(SpmdPartitioningTest, PartitionConvGroupOnBatchGroupCount) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,2,1,2]0,1,2,3}
%rhs = f32[16,801,1,1024] parameter(1)
%rhs.copy = f32[16,801,1,1024] copy(%rhs),
sharding={devices=[1,2,1,2]0,1,2,3}
ROOT %conv = f32[5,1,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=f01b_i01o->01bf,batch_group_count=1024,
window={size=801x1 pad=2_2x0_0},
sharding={devices=[1,1,1,2,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Select(_,
op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Reshape())),
_),
op::Shape("f32[16,401,1,512]"));
auto left_halo = AllOf(op::Shape("f32[16,2, 1, 512]"),
op::CollectivePermute(op::Slice(lhs)));
auto right_halo = AllOf(op::Shape("f32[16,2, 1, 512]"),
op::CollectivePermute(op::Slice(lhs)));
auto rhs = AllOf(op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Reshape())),
op::Shape("f32[16,401,1,512]"));
auto conv = AllOf(op::Convolution(op::Concatenate(left_halo, lhs, right_halo),
op::Select(_, rhs, _)),
op::Shape("f32[5,1,1,512]"));
EXPECT_THAT(root, AllOf(op::CollectivePermute(op::AllReduce(conv)),
op::Shape("f32[5,1,1,512]")));
}
TEST_F(SpmdPartitioningTest,
PartitionConvWithFeatureGroupCountAlignOuputWithRHS) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,2,1,1]0,1}
%rhs = f32[5,1,1,1024] parameter(1)
%rhs.copy = f32[5,1,1,1024] copy(%rhs),
sharding={devices=[1,1,1,2]0,1}
ROOT %conv = f32[16,801,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=b01f_01io->b01f,feature_group_count=1024,
window={size=5x1 pad=2_2x0_0},
sharding={devices=[2,1,1,1]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(op::Copy(op::DynamicSlice(
op::Pad(op::Parameter(), op::Constant()), op::Constant(),
op::Reshape(), op::Constant(), op::Constant())),
op::Shape("f32[16,401,1,1024]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[5,1,1,512]"));
auto resharded_lhs = AllOf(
op::Slice(op::Reshape(op::Transpose(op::AllToAll(op::Reshape(lhs))))),
op::Shape("f32[16,801,1,512]"));
auto conv = AllOf(op::Convolution(resharded_lhs, rhs),
op::Shape("f32[16,801,1,512]"));
EXPECT_THAT(root,
AllOf(op::Reshape(op::Transpose(op::AllToAll(op::Reshape(conv)))),
op::Shape("f32[8,801,1,1024]")));
}
TEST_F(SpmdPartitioningTest, PartitionConvWithFeatureGroupCountBackProp) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[16,801,1,1024] parameter(0)
%lhs.copy = f32[16,801,1,1024] copy(%lhs),
sharding={devices=[1,1,1,2]0,1}
%rhs = f32[5,1,1024,1] parameter(1)
%rhs.copy = f32[5,1,1024,1] copy(%rhs),
sharding={devices=[1,1,2,1]0,1}
ROOT %conv = f32[16,801,1,1024] convolution(%lhs.copy, %rhs.copy),
dim_labels=b01f_01oi->b01f,feature_group_count=1024,
window={size=5x1 pad=2_2x0_0 rhs_reversal=1x1},
sharding={devices=[1,1,1,2]0,1}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[16,801,1,512]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Reshape(), op::Constant())),
op::Shape("f32[5,1,512,1]"));
EXPECT_THAT(root,
AllOf(op::Convolution(lhs, rhs), op::Shape("f32[16,801,1,512]")));
}
TEST_F(SpmdPartitioningTest, NoReshardOnBroadcastDims) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%param0 = f32[2,3] parameter(0)
%param1 = f32[2,3,20] parameter(1)
%br0 = f32[20,2,20,3,20] broadcast(%param0), dimensions={1,3}, sharding={devices=[2,1,2,1,2]0,1,2,3,4,5,6,7}
%br1 = f32[20,2,20,3,20] broadcast(%param1), dimensions={1,3,4}, sharding={devices=[2,1,2,1,2]0,1,2,3,4,5,6,7}
%add = f32[20,2,20,3,20] add(%br0, %br1), sharding={devices=[2,1,2,1,2]0,1,2,3,4,5,6,7}
%reshape = f32[10,4,10,6,20] reshape(%br0), sharding={devices=[2,1,2,1,2]0,1,2,3,4,5,6,7}
%transpose = f32[2,3,20,20,20] transpose(%br0), dimensions={1,3,0,2,4}, sharding={devices=[1,1,2,2,2]0,1,2,3,4,5,6,7}
%copy_add0 = f32[20,2,20,3,20] copy(%add), sharding={devices=[2,1,2,1,2]6,7,2,3,4,5,0,1}
%copy_add1 = f32[20,2,20,3,20] copy(%add), sharding={devices=[2,1,2,1,2]7,6,3,2,5,4,0,1}
%copy_reshape = f32[10,4,10,6,20] copy(%reshape), sharding={devices=[2,1,2,1,2]7,6,3,2,5,4,0,1}
%copy_transpose = f32[2,3,20,20,20] copy(%transpose), sharding={devices=[1,1,2,2,2]7,6,3,2,5,4,0,1}
ROOT %tuple = (f32[20,2,20,3,20], f32[20,2,20,3,20], f32[10,4,10,6,20], f32[2,3,20,20,20])
tuple(%copy_add0, %copy_add1, %copy_reshape, %copy_transpose),
sharding={{devices=[2,1,2,1,2]6,7,2,3,4,5,0,1},{devices=[2,1,2,1,2]7,6,3,2,5,4,0,1},{devices=[2,1,2,1,2]7,6,3,2,5,4,0,1},{devices=[1,1,2,2,2]7,6,3,2,5,4,0,1}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
// Reshard on copy_add0 only happens on broadcast dims, can be skipped.
auto copy_add0 =
op::Copy(op::Copy(op::Add(op::Broadcast(_), op::Broadcast(_))));
// Reshard on copy_add1 also happens on non-broadcast dims.
auto copy_add1 = op::Copy(
op::CollectivePermute(op::Add(op::Broadcast(_), op::Broadcast(_))));
// Reshard on copy_reshape only happens on broadcast dims, can be skipped.
auto copy_reshape = op::Copy(op::Copy(op::Reshape(op::Broadcast(_))));
// Reshard on copy_transpose only happens on broadcast dims, can be skipped.
auto copy_transpose = op::Copy(op::Copy(op::Transpose(op::Broadcast(_))));
EXPECT_THAT(root,
op::Tuple(copy_add0, copy_add1, copy_reshape, copy_transpose));
}
TEST_F(SpmdPartitioningTest,
ConvolutionFilterIFOFPartitionedInputPartialReplicate) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,112,112,12] parameter(0)
%lhs.copy = f32[128,112,112,12] copy(f32[128,112,112,12] %lhs),
sharding={devices=[1,1,1,2,2]0,1,2,3 last_tile_dim_replicate}
%rhs = f32[7,7,12,64] parameter(1)
%rhs.copy = f32[7,7,12,64] copy(f32[7,7,12,64] %rhs),
sharding={devices=[1,1,2,2]0,1,2,3}
ROOT %conv = f32[128,56,56,64] convolution(
f32[128,112,112,12] %lhs.copy,
f32[7,7,12,64] %rhs.copy),
window={size=7x7 stride=2x2 pad=3_3x3_3},
dim_labels=b01f_01io->b01f,
sharding={devices=[1,1,1,2,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[128,112,112,6]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Reshape(), op::Reshape())),
op::Shape("f32[7,7,6,32]"));
EXPECT_THAT(
root,
AllOf(op::CollectivePermute(op::AllReduce(op::Convolution(lhs, rhs))),
op::Shape("f32[128,56,56,32]")));
}
TEST_F(SpmdPartitioningTest,
ConvolutionInputKernelNonContractingDimPartialReplicate) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[128,56,56,256] parameter(0)
%lhs.copy = f32[128,56,56,256] copy(%lhs),
sharding={devices=[1,1,1,2,2]0,1,2,3 last_tile_dim_replicate}
%rhs = f32[128,28,28,512] parameter(1)
%rhs.copy = f32[128,28,28,512] copy(%rhs),
sharding={devices=[1,1,1,2,2]0,1,2,3 last_tile_dim_replicate}
ROOT %conv = f32[1,1,256,512] convolution(%lhs.copy, %rhs.copy),
window={size=28x28 pad=0_-1x0_-1 rhs_dilate=2x2}, dim_labels=f01b_i01o->01bf,
sharding={devices=[1,1,2,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[128,56,56,128]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Constant(), op::Reshape())),
op::Shape("f32[128,28,28,256]"));
EXPECT_THAT(root, AllOf(op::Convolution(lhs, op::CollectivePermute(rhs)),
op::Shape("f32[1,1,128,256]")));
}
TEST_F(SpmdPartitioningTest,
ConvolutionInputSpatialDimAndFeatureDimParttiioned) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[8,210,210,12] parameter(0)
%lhs.copy = f32[8,210,210,12] copy(f32[8,210,210,12] %lhs),
sharding={devices=[1,2,1,2]0,1,2,3}
%rhs = f32[3,3,12,32] parameter(1)
%rhs.copy = f32[3,3,12,32] copy(f32[3,3,12,32] %rhs),
sharding={devices=[1,1,2,1,2]0,1,2,3 last_tile_dim_replicate}
ROOT %conv = f32[8,210,210,32] convolution(
f32[8,210,210,12] %lhs.copy,
f32[3,3,12,32] %rhs.copy),
window={size=3x3 pad=1_1x1_1},
dim_labels=b01f_01io->b01f,
sharding={devices=[1,2,1,1,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto lhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Reshape(),
op::Constant(), op::Reshape())),
op::Shape("f32[8,105,210,6]"));
auto left_halo =
AllOf(op::CollectivePermute(op::Slice(lhs)), op::Shape("f32[8,1,210,6]"));
auto right_halo =
AllOf(op::CollectivePermute(op::Slice(lhs)), op::Shape("f32[8,1,210,6]"));
auto exchanged_lhs = AllOf(
op::Select(op::And(_, _), op::Concatenate(left_halo, lhs, right_halo),
op::Broadcast(_)),
op::Shape("f32[8,107,210,6]"));
auto rhs = AllOf(
op::Copy(op::DynamicSlice(op::Parameter(), op::Constant(), op::Constant(),
op::Reshape(), op::Constant())),
op::Shape("f32[3,3,6,32]"));
EXPECT_THAT(root, AllOf(op::AllReduce(op::Convolution(
exchanged_lhs, op::CollectivePermute(rhs))),
op::Shape("f32[8,105,210,32]")));
}
TEST_F(SpmdPartitioningTest, Fft3D) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
constant = c64[1,1,6]
constant({{{(0,0),(1,1),(2,2),(3,3),(4,4),(5,5)}}}),
sharding={devices=[1,1,2]0,1}
ROOT fft = c64[1,1,6] fft(c64[1,1,6] constant), fft_type=FFT, fft_length={6},
sharding={devices=[1,1,2]0,1}
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/2));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto input = AllOf(op::DynamicSlice(op::Constant(), op::Constant(),
op::Constant(), op::Reshape()),
op::Shape("c64[1,1,3]"));
auto padded_input =
AllOf(op::DynamicSlice(
op::Concatenate(input, op::CollectivePermute(op::Slice())),
op::Constant(), op::Constant(), op::Reshape()),
op::Shape("c64[1,1,4]"));
auto shuffled_input =
AllOf(op::Slice(op::AllToAll(op::Dot(padded_input, op::Convert()))),
op::Shape("c64[1,1,3]"));
auto local_fft = AllOf(op::Fft(shuffled_input), op::Shape("c64[1,1,3]"));
EXPECT_THAT(root, AllOf(op::GetTupleElement(op::While(op::Tuple(
_, op::Multiply(local_fft, op::Exp()), _, _, _))),
op::Shape("c64[1,1,3]")));
}
TEST_F(SpmdPartitioningTest, DotInputsAreIdentical) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%parameter.1 = f32[4000,4000]{1,0} parameter(0),
sharding={devices=[2,4]0,1,2,3,4,5,6,7}
ROOT %convolution = f32[4000,4000]{1,0} convolution(
f32[4000,4000]{1,0} %parameter.1, f32[4000,4000]{1,0} %parameter.1),
dim_labels=bf_io->bf, sharding={devices=[2,4]0,1,2,3,4,5,6,7}
}
)";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto param = AllOf(op::Parameter(), op::Shape("f32[2000, 1000]"));
auto resharded_lhs =
AllOf(op::AllReduce(op::DynamicUpdateSlice(_, param, _, _)),
op::Shape("f32[2000, 4000]"));
auto resharded_rhs =
AllOf(op::AllReduce(op::DynamicUpdateSlice(_, op::Copy(param), _, _)),
op::Shape("f32[4000, 1000]"));
EXPECT_THAT(root, AllOf(op::Convolution(resharded_lhs, resharded_rhs),
op::Shape("f32[2000, 1000]")));
}
TEST_F(SpmdPartitioningTest, ConstantSliceReshard) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%constant.785 = f32[1,8] constant({{0,1,2,3,4,5,6,7}}),
sharding={devices=[1,8]0,1,2,3,4,5,6,7}
%slice.62 = f32[1,1] slice(%constant.785), slice={[0:1], [0:1]},
sharding={devices=[1,8]0,1,2,3,4,5,6,7}
ROOT %reshape.779 = f32[] reshape(%slice.62), sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
auto root = module->entry_computation()->root_instruction();
VLOG(1) << module->ToString();
auto slice = AllOf(op::Shape("f32[1,1]"),
op::Copy(op::DynamicSlice(op::Constant(), _, _)));
EXPECT_THAT(root, op::Reshape(op::Slice(op::AllReduce(op::DynamicUpdateSlice(
op::Broadcast(), slice, _, _)))));
}
TEST_F(SpmdPartitioningTest, GatherParallelDimRedistributionOperand) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY %module {
%parameter.0 = s32[8,4,2,2]{3,2,1,0} parameter(0),
sharding={devices=[4,2,1,1]0,1,2,3,4,5,6,7}
%iota = s32[1,8,4]{2,1,0} iota(), iota_dimension=2,
sharding={devices=[1,8,1]0,1,2,3,4,5,6,7}
%iota2 = s32[1,8,4]{2,1,0} iota(), iota_dimension=1,
sharding={devices=[1,8,1]0,1,2,3,4,5,6,7}
%concatenate.19 = s32[2,8,4]{2,1,0} concatenate(s32[1,8,4]{2,1,0} %iota,
s32[1,8,4]{2,1,0} %iota2), dimensions={0},
sharding={devices=[1,8,1]0,1,2,3,4,5,6,7}
ROOT %gather.20 = s32[8,4,2,2]{3,2,1,0} gather(
s32[8,4,2,2]{3,2,1,0} %parameter.0,
s32[2,8,4]{2,1,0} %concatenate.19), offset_dims={2,3},
collapsed_slice_dims={0,1}, start_index_map={1,0}, index_vector_dim=0,
slice_sizes={1,1,2,2}, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
auto root = module->entry_computation()->root_instruction();
VLOG(1) << module->ToString();
auto operand = AllOf(op::Shape("s32[1,4,2,2]"), op::DynamicSlice());
auto indices = AllOf(op::Shape("s32[2,1,4]"), op::Subtract());
auto gather = AllOf(op::Shape("s32[1,4,2,2]"), op::Gather(operand, indices));
EXPECT_THAT(root,
op::AllReduce(op::DynamicUpdateSlice(_, gather, _, _, _, _)));
}
TEST_F(SpmdPartitioningTest, GatherParallelDimRedistributionIndices) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY %module {
%parameter.0 = s32[8,4,2,2]{3,2,1,0} parameter(0),
sharding={devices=[8,1,1,1]0,1,2,3,4,5,6,7}
%iota = s32[1,8,4]{2,1,0} iota(), iota_dimension=1,
sharding={devices=[1,4,2]0,1,2,3,4,5,6,7}
%iota2 = s32[1,8,4]{2,1,0} iota(), iota_dimension=2,
sharding={devices=[1,4,2]0,1,2,3,4,5,6,7}
%concatenate.19 = s32[2,8,4]{2,1,0} concatenate(s32[1,8,4]{2,1,0} %iota,
s32[1,8,4]{2,1,0} %iota2), dimensions={0},
sharding={devices=[1,4,2]0,1,2,3,4,5,6,7}
ROOT %gather.20 = s32[8,4,2,2]{3,2,1,0} gather(s32[8,4,2,2]{3,2,1,0} %parameter.0,
s32[2,8,4]{2,1,0} %concatenate.19), offset_dims={2,3},
collapsed_slice_dims={0,1}, start_index_map={0,1}, index_vector_dim=0,
slice_sizes={1,1,2,2}, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
auto root = module->entry_computation()->root_instruction();
VLOG(1) << module->ToString();
auto operand = AllOf(op::Shape("s32[2,2,2,2]"), op::DynamicSlice());
auto indices = AllOf(op::Shape("s32[2,2,2]"), op::Subtract());
auto gather = AllOf(op::Shape("s32[2,2,2,2]"), op::Gather(operand, indices));
EXPECT_THAT(root, op::AllReduce(op::AllReduce(
op::DynamicUpdateSlice(_, gather, _, _, _, _))));
}
TEST_F(SpmdPartitioningTest, GatherParallelDimReplicatedIndices) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY %module {
%parameter.0 = s32[8,4,2,2]{3,2,1,0} parameter(0),
sharding={devices=[8,1,1,1]0,1,2,3,4,5,6,7}
%iota = s32[1,8,4]{2,1,0} iota(), iota_dimension=1,
sharding={replicated}
%iota2 = s32[1,8,4]{2,1,0} iota(), iota_dimension=2,
sharding={replicated}
%concatenate.19 = s32[2,8,4]{2,1,0} concatenate(s32[1,8,4]{2,1,0} %iota,
s32[1,8,4]{2,1,0} %iota2), dimensions={0},
sharding={replicated}
ROOT %gather.20 = s32[8,4,2,2]{3,2,1,0} gather(
s32[8,4,2,2]{3,2,1,0} %parameter.0,
s32[2,8,4]{2,1,0} %concatenate.19), offset_dims={2,3},
collapsed_slice_dims={0,1}, start_index_map={0,1}, index_vector_dim=0,
slice_sizes={1,1,2,2}, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
auto root = module->entry_computation()->root_instruction();
VLOG(1) << module->ToString();
auto operand = AllOf(op::Shape("s32[1,4,2,2]"), op::Parameter());
auto indices = AllOf(op::Shape("s32[2,1,4]"), op::Subtract());
auto gather = AllOf(op::Shape("s32[1,4,2,2]"), op::Gather(operand, indices));
EXPECT_THAT(root,
op::AllReduce(op::DynamicUpdateSlice(_, gather, _, _, _, _)));
}
TEST_F(SpmdPartitioningTest, GatherParallelDimReplicatedOperand) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY %module {
%parameter.0 = s32[8,4,2,2]{3,2,1,0} parameter(0), sharding={replicated}
%iota = s32[1,8,4]{2,1,0} iota(), iota_dimension=1,
sharding={devices=[1,8,1]0,1,2,3,4,5,6,7}
%iota2 = s32[1,8,4]{2,1,0} iota(), iota_dimension=2,
sharding={devices=[1,8,1]0,1,2,3,4,5,6,7}
%concatenate.19 = s32[2,8,4]{2,1,0} concatenate(s32[1,8,4]{2,1,0} %iota,
s32[1,8,4]{2,1,0} %iota2), dimensions={0},
sharding={devices=[1,8,1]0,1,2,3,4,5,6,7}
ROOT %gather.20 = s32[8,4,2,2]{3,2,1,0} gather(
s32[8,4,2,2]{3,2,1,0} %parameter.0,
s32[2,8,4]{2,1,0} %concatenate.19), offset_dims={2,3},
collapsed_slice_dims={0,1}, start_index_map={0,1}, index_vector_dim=0,
slice_sizes={1,1,2,2}, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
auto root = module->entry_computation()->root_instruction();
VLOG(1) << module->ToString();
auto operand = AllOf(op::Shape("s32[1,4,2,2]"), op::DynamicSlice());
auto indices = AllOf(op::Shape("s32[2,1,4]"), op::Subtract());
auto gather = AllOf(op::Shape("s32[1,4,2,2]"), op::Gather(operand, indices));
EXPECT_THAT(root,
op::AllReduce(op::DynamicUpdateSlice(_, gather, _, _, _, _)));
}
TEST_F(SpmdPartitioningTest, GatherParallelDimPartialReplicatedIndices) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY %module {
%parameter.0 = s32[8,4,2,2]{3,2,1,0} parameter(0),
sharding={devices=[8,1,1,1]0,1,2,3,4,5,6,7}
%iota = s32[1,8,4]{2,1,0} iota(), iota_dimension=1,
sharding={devices=[1,2,1,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
%iota2 = s32[1,8,4]{2,1,0} iota(), iota_dimension=2,
sharding={devices=[1,2,1,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
%concatenate.19 = s32[2,8,4]{2,1,0} concatenate(s32[1,8,4]{2,1,0} %iota,
s32[1,8,4]{2,1,0} %iota2), dimensions={0},
sharding={devices=[1,2,1,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %gather.20 = s32[8,4,2,2]{3,2,1,0} gather(
s32[8,4,2,2]{3,2,1,0} %parameter.0,
s32[2,8,4]{2,1,0} %concatenate.19), offset_dims={2,3},
collapsed_slice_dims={0,1}, start_index_map={0,1}, index_vector_dim=0,
slice_sizes={1,1,2,2}, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
auto root = module->entry_computation()->root_instruction();
VLOG(1) << module->ToString();
auto operand = AllOf(op::Shape("s32[1,4,2,2]"), op::Parameter());
auto indices = AllOf(op::Shape("s32[2,1,4]"), op::Subtract());
auto gather = AllOf(op::Shape("s32[1,4,2,2]"), op::Gather(operand, indices));
EXPECT_THAT(root,
op::AllReduce(op::DynamicUpdateSlice(_, gather, _, _, _, _)));
}
TEST_F(SpmdPartitioningTest, GatherParallelDimPartialReplicatedOperand) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY %module {
%parameter.0 = s32[8,4,2,2]{3,2,1,0} parameter(0), sharding={
devices=[2,1,1,1,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
%iota = s32[1,8,4]{2,1,0} iota(), iota_dimension=1,
sharding={devices=[1,8,1]0,1,2,3,4,5,6,7}
%iota2 = s32[1,8,4]{2,1,0} iota(), iota_dimension=2,
sharding={devices=[1,8,1]0,1,2,3,4,5,6,7}
%concatenate.19 = s32[2,8,4]{2,1,0} concatenate(s32[1,8,4]{2,1,0} %iota,
s32[1,8,4]{2,1,0} %iota2), dimensions={0},
sharding={devices=[1,8,1]0,1,2,3,4,5,6,7}
ROOT %gather.20 = s32[8,4,2,2]{3,2,1,0} gather(
s32[8,4,2,2]{3,2,1,0} %parameter.0,
s32[2,8,4]{2,1,0} %concatenate.19), offset_dims={2,3},
collapsed_slice_dims={0,1}, start_index_map={0,1}, index_vector_dim=0,
slice_sizes={1,1,2,2}, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
auto root = module->entry_computation()->root_instruction();
VLOG(1) << module->ToString();
auto operand = AllOf(op::Shape("s32[1,4,2,2]"), op::DynamicSlice());
auto indices = AllOf(op::Shape("s32[2,1,4]"), op::Subtract());
auto gather = AllOf(op::Shape("s32[1,4,2,2]"), op::Gather(operand, indices));
EXPECT_THAT(root,
op::AllReduce(op::DynamicUpdateSlice(_, gather, _, _, _, _)));
}
TEST_F(SpmdPartitioningTest, GatherParallelDimSwappedDimensions) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY %module {
%parameter.0 = s32[8,4,2,2]{3,2,1,0} parameter(0), sharding={
devices=[4,2,1,1]0,1,2,3,4,5,6,7}
%iota = s32[1,8,4]{2,1,0} iota(), iota_dimension=1,
sharding={devices=[1,2,4]0,1,2,3,4,5,6,7}
%iota2 = s32[1,8,4]{2,1,0} iota(), iota_dimension=2,
sharding={devices=[1,2,4]0,1,2,3,4,5,6,7}
%concatenate.19 = s32[2,8,4]{2,1,0} concatenate(s32[1,8,4]{2,1,0} %iota,
s32[1,8,4]{2,1,0} %iota2), dimensions={0},
sharding={devices=[1,2,4]0,1,2,3,4,5,6,7}
ROOT %gather.20 = s32[8,4,2,2]{3,2,1,0} gather(
s32[8,4,2,2]{3,2,1,0} %parameter.0,
s32[2,8,4]{2,1,0} %concatenate.19), offset_dims={2,3},
collapsed_slice_dims={0,1}, start_index_map={0,1}, index_vector_dim=0,
slice_sizes={1,1,2,2}, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
auto root = module->entry_computation()->root_instruction();
VLOG(1) << module->ToString();
auto operand = AllOf(op::Shape("s32[4,1,2,2]"), op::CollectivePermute());
auto indices = AllOf(op::Shape("s32[2,4,1]"), op::Subtract());
auto gather = AllOf(op::Shape("s32[4,1,2,2]"), op::Gather(operand, indices));
EXPECT_THAT(root, op::AllReduce(op::AllReduce(
op::DynamicUpdateSlice(_, gather, _, _, _, _))));
}
TEST_F(SpmdPartitioningTest, GatherMergedParalleIndexPassthrough) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY %module {
%parameter.0 = s32[8,4,2,2]{3,2,1,0} parameter(0),
sharding={devices=[2,2,2,1]0,1,2,3,4,5,6,7}
%iota = s32[1,8,4]{2,1,0} iota(), iota_dimension=2,
sharding={devices=[1,4,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
%iota2 = s32[1,8,4]{2,1,0} iota(), iota_dimension=1,
sharding={devices=[1,4,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
%concatenate.19 = s32[2,8,4]{2,1,0} concatenate(s32[1,8,4]{2,1,0} %iota,
s32[1,8,4]{2,1,0} %iota2), dimensions={0},
sharding={devices=[1,4,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %gather.20 = s32[8,4,2,2]{3,2,1,0} gather(
s32[8,4,2,2]{3,2,1,0} %parameter.0,
s32[2,8,4]{2,1,0} %concatenate.19), offset_dims={2,3},
collapsed_slice_dims={0,1}, start_index_map={1,0}, index_vector_dim=0,
slice_sizes={1,1,2,2}, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
auto root = module->entry_computation()->root_instruction();
auto operand = AllOf(op::Shape("s32[2,4,1,2]"), op::DynamicSlice());
auto indices = AllOf(op::Shape("s32[2,2,4]"), op::Subtract());
auto gather = AllOf(op::Shape("s32[2,4,1,2]"), op::Gather(operand, indices));
EXPECT_THAT(
root, op::AllReduce(op::DynamicUpdateSlice(
_, op::AllReduce(op::DynamicUpdateSlice(_, gather, _, _, _, _)),
_, _, _, _)));
}
TEST_F(SpmdPartitioningTest, GatherMergedParallelIndexTrivialSlice) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY %module {
%parameter.0 = s32[8,4,2,2]{3,2,1,0} parameter(0),
sharding={devices=[4,2,1,1]0,1,2,3,4,5,6,7}
%parameter.1 = s32[1,8,1]{2,1,0} parameter(1),
sharding={devices=[1,4,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
%iota = s32[1,8,1]{2,1,0} iota(), iota_dimension=1,
sharding={devices=[1,4,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
%concatenate.19 = s32[2,8,1]{2,1,0} concatenate(
s32[1,8,1]{2,1,0} %parameter.1, s32[1,8,1]{2,1,0} %iota), dimensions={0},
sharding={devices=[1,4,1,2]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %gather.20 = s32[8,1,2,2]{3,2,1,0} gather(
s32[8,4,2,2]{3,2,1,0} %parameter.0,
s32[2,8,1]{2,1,0} %concatenate.19), offset_dims={2,3},
collapsed_slice_dims={0,1}, start_index_map={1,0}, index_vector_dim=0,
slice_sizes={1,1,2,2}, sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
auto root = module->entry_computation()->root_instruction();
auto operand = AllOf(op::Shape("s32[2,2,2,2]"), op::Parameter());
auto indices = AllOf(op::Shape("s32[2,2,1]"), op::Subtract());
auto gather = AllOf(op::Shape("s32[2,1,2,2]"), op::Gather(operand, indices));
EXPECT_THAT(root,
op::AllReduce(op::DynamicUpdateSlice(
_, op::AllReduce(op::Select(_, _, gather)), _, _, _, _)));
}
TEST_F(SpmdPartitioningTest, SortTopKNonSortDimension) {
absl::string_view hlo_string = R"(
HloModule module
%compare-greater-than.42077 (p.0.lhs.42078: f32[],
p.0.rhs.42079: f32[], p.1.lhs.42080: s32[], p.1.rhs.42081: s32[]) -> pred[] {
%p.0.lhs.42078 = f32[] parameter(0)
%bitcast-convert.135 = s32[] bitcast-convert(f32[] %p.0.lhs.42078)
%constant.45054 = s32[] constant(0)
%compare.133 = pred[] compare(s32[] %bitcast-convert.135,
s32[] %constant.45054), direction=LT
%constant.45278 = u32[] constant(2147483647)
%bitcast-convert.136 = u32[] bitcast-convert(f32[] %p.0.lhs.42078)
%subtract.337 = u32[] subtract(u32[] %constant.45278,
u32[] %bitcast-convert.136)
%bitcast-convert.137 = s32[] bitcast-convert(u32[] %subtract.337)
%select.282 = s32[] select(pred[] %compare.133, s32[] %bitcast-convert.137,
s32[] %bitcast-convert.135)
%p.0.rhs.42079 = f32[] parameter(1)
%bitcast-convert.138 = s32[] bitcast-convert(f32[] %p.0.rhs.42079)
%compare.134 = pred[] compare(s32[] %bitcast-convert.138,
s32[] %constant.45054), direction=LT
%bitcast-convert.139 = u32[] bitcast-convert(f32[] %p.0.rhs.42079)
%subtract.338 = u32[] subtract(u32[] %constant.45278,
u32[] %bitcast-convert.139)
%bitcast-convert.140 = s32[] bitcast-convert(u32[] %subtract.338)
%select.283 = s32[] select(pred[] %compare.134, s32[] %bitcast-convert.140,
s32[] %bitcast-convert.138)
%compare.135 = pred[] compare(s32[] %select.282,
s32[] %select.283), direction=GT
%compare.428 = pred[] compare(s32[] %select.283,
s32[] %select.282), direction=GT
%compare.429 = pred[] compare(pred[] %compare.135,
pred[] %compare.428), direction=EQ
%p.1.lhs.42080 = s32[] parameter(2)
%p.1.rhs.42081 = s32[] parameter(3)
%compare.430 = pred[] compare(s32[] %p.1.lhs.42080,
s32[] %p.1.rhs.42081), direction=LT
ROOT %select.579 = pred[] select(pred[] %compare.429,
pred[] %compare.430, pred[] %compare.135)
}
ENTRY %module {
%parameter.0 = f32[2,64,32128]{2,1,0} parameter(0),
sharding={devices=[2,1,4]0,1,2,3,4,5,6,7}
%iota = s32[2,64,32128]{2,1,0} iota(), iota_dimension=2,
sharding={devices=[2,1,4]0,1,2,3,4,5,6,7}
%sort.18 = (f32[2,64,32128]{2,1,0}, s32[2,64,32128]{2,1,0}) sort(
f32[2,64,32128]{2,1,0} %parameter.0, s32[2,64,32128]{2,1,0} %iota),
dimensions={2}, is_stable=true, to_apply=%compare-greater-than.42077,
sharding={{devices=[2,1,4]0,1,2,3,4,5,6,7},
{devices=[2,1,4]0,1,2,3,4,5,6,7}}
output = f32[2,64,32128]{2,1,0} get-tuple-element(%sort.18), index=0,
sharding={devices=[2,1,4]0,1,2,3,4,5,6,7}
%slice.0 = f32[2,64,2]{2,1,0} slice(f32[2,64,32128]{2,1,0} output),
slice={[0:2], [0:64], [0:2]},
sharding={devices=[2,1,4]0,1,2,3,4,5,6,7}
output2 = s32[2,64,32128]{2,1,0} get-tuple-element(%sort.18), index=1,
sharding={replicated}
%slice.1 = s32[2,64,2]{2,1,0} slice(s32[2,64,32128]{2,1,0} output2),
slice={[0:2], [0:64], [0:2]},
sharding={devices=[2,1,4]0,1,2,3,4,5,6,7}
ROOT output.t = (f32[2,64,2]{2,1,0},
s32[2,64,2]{2,1,0}) tuple(slice.0, slice.1),
sharding={{replicated}, {replicated}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
const HloInstruction* sort = FindInstruction(module.get(), "sort");
EXPECT_NE(sort, nullptr);
auto sort_match =
AllOf(op::Shape("(f32[2,64,32128], s32[2,64,32128])"), op::Sort(_, _));
EXPECT_THAT(sort, sort_match);
}
TEST_F(SpmdPartitioningTest, SortTopKPropagateBaseShape) {
absl::string_view hlo_string = R"(
HloModule module
%compare-greater-than.42077 (p.0.lhs.42078: f32[],
p.0.rhs.42079: f32[], p.1.lhs.42080: s32[], p.1.rhs.42081: s32[]) -> pred[] {
%p.0.lhs.42078 = f32[] parameter(0)
%bitcast-convert.135 = s32[] bitcast-convert(f32[] %p.0.lhs.42078)
%constant.45054 = s32[] constant(0)
%compare.133 = pred[] compare(s32[] %bitcast-convert.135,
s32[] %constant.45054), direction=LT
%constant.45278 = u32[] constant(2147483647)
%bitcast-convert.136 = u32[] bitcast-convert(f32[] %p.0.lhs.42078)
%subtract.337 = u32[] subtract(u32[] %constant.45278,
u32[] %bitcast-convert.136)
%bitcast-convert.137 = s32[] bitcast-convert(u32[] %subtract.337)
%select.282 = s32[] select(pred[] %compare.133, s32[] %bitcast-convert.137,
s32[] %bitcast-convert.135)
%p.0.rhs.42079 = f32[] parameter(1)
%bitcast-convert.138 = s32[] bitcast-convert(f32[] %p.0.rhs.42079)
%compare.134 = pred[] compare(s32[] %bitcast-convert.138,
s32[] %constant.45054), direction=LT
%bitcast-convert.139 = u32[] bitcast-convert(f32[] %p.0.rhs.42079)
%subtract.338 = u32[] subtract(u32[] %constant.45278,
u32[] %bitcast-convert.139)
%bitcast-convert.140 = s32[] bitcast-convert(u32[] %subtract.338)
%select.283 = s32[] select(pred[] %compare.134, s32[] %bitcast-convert.140,
s32[] %bitcast-convert.138)
%compare.135 = pred[] compare(s32[] %select.282,
s32[] %select.283), direction=GT
%compare.428 = pred[] compare(s32[] %select.283,
s32[] %select.282), direction=GT
%compare.429 = pred[] compare(pred[] %compare.135,
pred[] %compare.428), direction=EQ
%p.1.lhs.42080 = s32[] parameter(2)
%p.1.rhs.42081 = s32[] parameter(3)
%compare.430 = pred[] compare(s32[] %p.1.lhs.42080,
s32[] %p.1.rhs.42081), direction=LT
ROOT %select.579 = pred[] select(pred[] %compare.429,
pred[] %compare.430, pred[] %compare.135)
}
ENTRY %module {
%parameter.0 = f32[2,64,32128]{2,1,0} parameter(0),
sharding={devices=[1,1,8]0,1,2,3,4,5,6,7}
%iota = s32[2,64,32128]{2,1,0} iota(), iota_dimension=2,
sharding={devices=[1,1,8]0,1,2,3,4,5,6,7}
%sort.18 = (f32[2,64,32128]{2,1,0}, s32[2,64,32128]{2,1,0}) sort(
f32[2,64,32128]{2,1,0} %parameter.0, s32[2,64,32128]{2,1,0} %iota),
dimensions={2}, is_stable=true, to_apply=%compare-greater-than.42077,
sharding={{devices=[1,1,8]0,1,2,3,4,5,6,7},
{devices=[1,1,8]0,1,2,3,4,5,6,7}}
output = f32[2,64,32128]{2,1,0} get-tuple-element(%sort.18), index=0,
sharding={devices=[1,1,8]0,1,2,3,4,5,6,7}
%slice.0 = f32[2,64,2]{2,1,0} slice(f32[2,64,32128]{2,1,0} output),
slice={[0:2], [0:64], [0:2]},
sharding={devices=[1,1,8]0,1,2,3,4,5,6,7}
output2 = s32[2,64,32128]{2,1,0} get-tuple-element(%sort.18), index=1,
sharding={replicated}
%slice.1 = s32[2,64,2]{2,1,0} slice(s32[2,64,32128]{2,1,0} output2),
slice={[0:2], [0:64], [0:2]},
sharding={devices=[1,1,8]0,1,2,3,4,5,6,7}
ROOT output.t = (f32[2,64,2]{2,1,0},
s32[2,64,2]{2,1,0}) tuple(slice.0, slice.1),
sharding={{replicated}, {replicated}}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
const HloInstruction* root = module->entry_computation()->root_instruction();
auto all_reduce_val =
AllOf(op::Shape("f32[2,64,2]"),
op::Slice(op::AllReduce(op::DynamicUpdateSlice(_, _, _, _, _))));
auto all_reduce_idx =
AllOf(op::Shape("s32[2,64,2]"),
op::Slice(op::AllReduce(op::DynamicUpdateSlice(_, _, _, _, _))));
auto tuple = AllOf(op::Shape("(f32[2,64,2], s32[2,64,2])"),
op::Tuple(all_reduce_val, all_reduce_idx));
EXPECT_THAT(root, tuple);
}
TEST_F(SpmdPartitioningTest, GatherIndexOnlyCorrectReplacement) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY %module {
%parameter.0 = bf16[1,8,6,6]{3,2,1,0} parameter(0),
sharding={replicated}
%parameter.1 = s32[2,4]{1,0} parameter(1),
sharding={devices=[2,1,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
%gather.100 = bf16[2,1,8,1,6]{4,3,2,1,0} gather(
bf16[1,8,6,6]{3,2,1,0} %parameter.0, s32[2,4]{1,0} %parameter.1),
offset_dims={1,2,3,4}, collapsed_slice_dims={}, start_index_map={0,1,2,3},
index_vector_dim=1, slice_sizes={1,8,1,6},
sharding={devices=[2,1,4,1,1]0,1,2,3,4,5,6,7}
%constant.45590 = s32[] constant(0), sharding={replicated}
%broadcast.54515 = s32[2,64,1,1]{3,2,1,0} broadcast(s32[] %constant.45590),
dimensions={},
sharding={devices=[2,1,1,1,4]0,1,2,3,4,5,6,7 last_tile_dim_replicate}
ROOT %reshape.4243 = bf16[2,8,6]{2,1,0} reshape(
bf16[2,1,8,1,6]{4,3,2,1,0} %gather.100),
sharding={devices=[2,4,1]0,1,2,3,4,5,6,7}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/8));
const HloInstruction* root = module->entry_computation()->root_instruction();
auto param0 = AllOf(op::Shape("bf16[1,8,6,6]"), op::Parameter());
auto param1 = AllOf(op::Shape("s32[1,4]"), op::Parameter());
auto reshape = AllOf(
op::Shape("bf16[1,2,6]"),
op::Reshape(op::DynamicSlice(op::Gather(param0, param1), _, _, _, _, _)));
EXPECT_THAT(root, reshape);
}
TEST_F(SpmdPartitioningTest, WindowedEinsumPreferMemoryFootprint) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY %module {
%parameter.0 = bf16[128,1024,4,4,1152,1,1]{6,5,4,3,2,1,0} parameter(0),
sharding={devices=[4,1,2,1,1,1,1]0,1,2,3,4,5,6,7}
%parameter.1 = bf16[4,4,1152,4,176,256,1]{6,5,4,3,2,1,0} parameter(1),
sharding={devices=[2,2,1,2,1,1,1]0,1,2,3,4,5,6,7}
%convolution.3 = bf16[128,1024,4,176,256,1,1]{6,5,4,3,2,1,0}
convolution(bf16[128,1024,4,4,1152,1,1]{6,5,4,3,2,1,0} %parameter.0,
bf16[4,4,1152,4,176,256,1]{6,5,4,3,2,1,0} %parameter.1),
window={size=1x4x176x4x4 pad=0_0x3_3x175_175x0_0x0_0
rhs_reversal=0x1x1x0x0}, dim_labels=0b34f12_34i12o0->0b12f34,
sharding={devices=[4,1,2,1,1,1,1]0,1,2,3,4,5,6,7}
ROOT %reshape.3973 = bf16[128,1024,4,176,256]{4,3,2,1,0}
reshape(bf16[128,1024,4,176,256,1,1]{6,5,4,3,2,1,0} %convolution.3),
sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(
auto module,
PartitionComputation(hlo_string, /*num_devices=*/8,
/*conv_halo_exchange_always_on_lhs =*/true,
/*choose_faster_windowed_einsum =*/false));
const HloInstruction* while_inst = FindInstruction(module.get(), "while");
EXPECT_NE(while_inst, nullptr);
const HloComputation* cond_comp = while_inst->while_condition();
const HloInstruction* root = cond_comp->root_instruction();
EXPECT_THAT(root, op::Compare(_, op::Constant()));
const HloConstantInstruction* iterations =
Cast<HloConstantInstruction>(root->operand(1));
EXPECT_TRUE(iterations->literal().GetFirstInteger());
EXPECT_EQ(*iterations->literal().GetFirstInteger(), 4);
}
TEST_F(SpmdPartitioningTest, WindowedEinsumPreferNumberIterations) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY %module {
%parameter.0 = bf16[128,1024,4,4,1152,1,1]{6,5,4,3,2,1,0} parameter(0),
sharding={devices=[4,1,2,1,1,1,1]0,1,2,3,4,5,6,7}
%parameter.1 = bf16[4,4,1152,4,176,256,1]{6,5,4,3,2,1,0} parameter(1),
sharding={devices=[2,2,1,2,1,1,1]0,1,2,3,4,5,6,7}
%convolution.3 = bf16[128,1024,4,176,256,1,1]{6,5,4,3,2,1,0}
convolution(bf16[128,1024,4,4,1152,1,1]{6,5,4,3,2,1,0} %parameter.0,
bf16[4,4,1152,4,176,256,1]{6,5,4,3,2,1,0} %parameter.1),
window={size=1x4x176x4x4 pad=0_0x3_3x175_175x0_0x0_0
rhs_reversal=0x1x1x0x0}, dim_labels=0b34f12_34i12o0->0b12f34,
sharding={devices=[4,1,2,1,1,1,1]0,1,2,3,4,5,6,7}
ROOT %reshape.3973 = bf16[128,1024,4,176,256]{4,3,2,1,0}
reshape(bf16[128,1024,4,176,256,1,1]{6,5,4,3,2,1,0} %convolution.3),
sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(
auto module,
PartitionComputation(hlo_string, /*num_devices=*/8,
/*conv_halo_exchange_always_on_lhs =*/true,
/*choose_faster_windowed_einsum =*/true));
const HloInstruction* while_inst = FindInstruction(module.get(), "while");
EXPECT_NE(while_inst, nullptr);
const HloComputation* cond_comp = while_inst->while_condition();
const HloInstruction* root = cond_comp->root_instruction();
EXPECT_THAT(root, op::Compare(_, op::Constant()));
const HloConstantInstruction* iterations =
Cast<HloConstantInstruction>(root->operand(1));
EXPECT_TRUE(iterations->literal().GetFirstInteger());
EXPECT_EQ(*iterations->literal().GetFirstInteger(), 2);
}
TEST_F(SpmdPartitioningTest, WindowedEinsumPreferNumberIterations2) {
const char* const hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = bf16[512,1024,16,36,256]{4,3,2,1,0} parameter(0)
%lhs.copy = bf16[512,1024,16,36,256]{4,3,2,1,0} copy(%lhs),
sharding={devices=[8,1,4,1,1,1,1]0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
18,19,20,21,22,23,24,25,26,27,28,29,30,31}
%rhs = bf16[512,1024,16,4,288]{4,3,2,1,0} parameter(1)
%rhs.copy = bf16[512,1024,16,4,288]{4,3,2,1,0} copy(%rhs),
sharding={devices=[8,1,4,1,1,1,1]0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}
%reshape.2556 = bf16[512,1024,16,4,288,1,1]{6,5,4,3,2,1,0} reshape(
bf16[512,1024,16,4,288]{4,3,2,1,0} %rhs.copy), sharding={
devices=[8,1,4,1,1,1,1]0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
20,21,22,23,24,25,26,27,28,29,30,31}
%reshape.2570 = bf16[512,1024,16,36,256,1,1]{6,5,4,3,2,1,0}
reshape(bf16[512,1024,16,36,256]{4,3,2,1,0} %lhs.copy), sharding={
devices=[8,1,4,1,1,1,1]0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
20,21,22,23,24,25,26,27,28,29,30,31}
%convolution.10 = bf16[16,36,256,16,4,288,1]{6,5,4,3,2,1,0}
convolution(bf16[512,1024,16,36,256,1,1]{6,5,4,3,2,1,0} %reshape.2570,
bf16[512,1024,16,4,288,1,1]{6,5,4,3,2,1,0} %reshape.2556),
window={size=1x1x16x4x512 pad=0_0x0_0x15_15x3_3x0_0 rhs_reversal=0x0x1x1x0},
dim_labels=4f01b23_4i23o01->01b23f4, sharding={devices=[4,1,1,4,2,1,1]0,4,8,
12,16,20,24,28,1,5,9,13,17,21,25,29,2,6,10,14,18,22,26,30,3,7,11,15,19,23,
27,31}
ROOT %output = bf16[16,36,256,16,4,288,1]{6,5,4,3,2,1,0}
copy(%convolution.10), sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(
auto module,
PartitionComputation(hlo_string, /*num_devices=*/32,
/*conv_halo_exchange_always_on_lhs =*/true,
/*choose_faster_windowed_einsum =*/true));
const HloInstruction* while_inst = FindInstruction(module.get(), "while");
EXPECT_NE(while_inst, nullptr);
const HloComputation* cond_comp = while_inst->while_condition();
const HloInstruction* root = cond_comp->root_instruction();
EXPECT_THAT(root, op::Compare(_, op::Constant()));
const HloConstantInstruction* iterations =
Cast<HloConstantInstruction>(root->operand(1));
EXPECT_TRUE(iterations->literal().GetFirstInteger());
EXPECT_EQ(*iterations->literal().GetFirstInteger(), 4);
}
TEST_F(SpmdPartitioningTest, WindowedEinsumPreferMemoryFootprint2) {
const char* const hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = bf16[512,1024,16,36,256]{4,3,2,1,0} parameter(0)
%lhs.copy = bf16[512,1024,16,36,256]{4,3,2,1,0} copy(%lhs),
sharding={devices=[8,1,4,1,1,1,1]0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
18,19,20,21,22,23,24,25,26,27,28,29,30,31}
%rhs = bf16[512,1024,16,4,288]{4,3,2,1,0} parameter(1)
%rhs.copy = bf16[512,1024,16,4,288]{4,3,2,1,0} copy(%rhs),
sharding={devices=[8,1,4,1,1,1,1]0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}
%reshape.2556 = bf16[512,1024,16,4,288,1,1]{6,5,4,3,2,1,0} reshape(
bf16[512,1024,16,4,288]{4,3,2,1,0} %rhs.copy), sharding={
devices=[8,1,4,1,1,1,1]0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
20,21,22,23,24,25,26,27,28,29,30,31}
%reshape.2570 = bf16[512,1024,16,36,256,1,1]{6,5,4,3,2,1,0}
reshape(bf16[512,1024,16,36,256]{4,3,2,1,0} %lhs.copy), sharding={
devices=[8,1,4,1,1,1,1]0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
20,21,22,23,24,25,26,27,28,29,30,31}
%convolution.10 = bf16[16,36,256,16,4,288,1]{6,5,4,3,2,1,0}
convolution(bf16[512,1024,16,36,256,1,1]{6,5,4,3,2,1,0} %reshape.2570,
bf16[512,1024,16,4,288,1,1]{6,5,4,3,2,1,0} %reshape.2556),
window={size=1x1x16x4x512 pad=0_0x0_0x15_15x3_3x0_0 rhs_reversal=0x0x1x1x0},
dim_labels=4f01b23_4i23o01->01b23f4, sharding={devices=[4,1,1,4,2,1,1]0,4,8,
12,16,20,24,28,1,5,9,13,17,21,25,29,2,6,10,14,18,22,26,30,3,7,11,15,19,23,
27,31}
ROOT %output = bf16[16,36,256,16,4,288,1]{6,5,4,3,2,1,0}
copy(%convolution.10), sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(
auto module,
PartitionComputation(hlo_string, /*num_devices=*/32,
/*conv_halo_exchange_always_on_lhs =*/true,
/*choose_faster_windowed_einsum =*/false));
const HloInstruction* while_inst = FindInstruction(module.get(), "while");
EXPECT_NE(while_inst, nullptr);
const HloComputation* cond_comp = while_inst->while_condition();
const HloInstruction* root = cond_comp->root_instruction();
EXPECT_THAT(root, op::Compare(_, op::Constant()));
const HloConstantInstruction* iterations =
Cast<HloConstantInstruction>(root->operand(1));
EXPECT_TRUE(iterations->literal().GetFirstInteger());
EXPECT_EQ(*iterations->literal().GetFirstInteger(), 8);
}
TEST_F(SpmdPartitioningTest, ContractingPartitionDotOperandsSlicedWrong) {
const char* const hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[8,2,15,4] parameter(0)
%lhs.copy = f32[8,2,15,4] copy(%lhs),
sharding={devices=[1,2,4,1]0,1,2,3,4,5,6,7}
%rhs = f32[2,15,4] parameter(1)
%rhs.copy = f32[2,15,4] copy(%rhs),
sharding={devices=[2,4,1]0,1,2,3,4,5,6,7}
%dot = f32[8,2,2] dot(%lhs.copy, %rhs.copy),
lhs_batch_dims={}, rhs_batch_dims={},
lhs_contracting_dims={2,3}, rhs_contracting_dims={1,2},
operand_precision={HIGH,HIGH},
sharding={devices=[2,2,2]0,1,2,3,4,5,6,7}
ROOT %output = f32[8,2,2] copy(%dot), sharding={replicated}
})";
TF_ASSERT_OK_AND_ASSIGN(
auto module,
PartitionComputation(hlo_string, /*num_devices=*/8,
/*conv_halo_exchange_always_on_lhs =*/true,
/*choose_faster_windowed_einsum =*/true));
const HloInstruction* dot_op = FindInstruction(module.get(), "dot.1");
auto op1 = op::Shape("f32[4,2,4,4]");
auto op2 = op::Shape("f32[2,4,4]");
EXPECT_THAT(dot_op, op::Dot(op1, op2));
}
TEST_F(SpmdPartitioningTest, PartitionDotGroupOnBatchContractingReshard) {
absl::string_view hlo_string = R"(
HloModule module
ENTRY entry {
%lhs = f32[32,32,24,4096] parameter(0),
sharding={devices=[2,1,1,2]0,1,2,3}
%rhs = f32[32,4096,1024] parameter(1),
sharding={devices=[2,2,1]0,1,2,3}
ROOT %dot = f32[32,32,24,1024] dot(%lhs, %rhs),
lhs_batch_dims={0}, rhs_batch_dims={0},
lhs_contracting_dims={3}, rhs_contracting_dims={1},
sharding={devices=[1,2,1,2]0,1,2,3}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto dot = AllOf(op::Shape("f32[16,32,24,1024]"),
op::Dot(op::Parameter(0), op::Parameter(1)));
auto reduce_scatter = AllOf(op::Shape("f32[16,32,24,512]"),
op::DynamicSlice(op::AllReduce(dot), _, _, _, _));
EXPECT_THAT(root, AllOf(op::Reshape(op::Transpose(
op::AllToAll(op::Reshape(reduce_scatter)))),
op::Shape("f32[32,16,24,512]")));
}
TEST_F(SpmdPartitioningTest, PartitionPassthroughScatterCorrectOutputSharding) {
absl::string_view hlo_string = R"(
HloModule module
%scatter_add (parameter.0: bf16[], parameter.1: bf16[]) -> bf16[] {
%parameter.0 = bf16[] parameter(0)
%parameter.1 = bf16[] parameter(1)
ROOT %add = bf16[] add(bf16[] %parameter.0, bf16[] %parameter.1)
}
ENTRY entry {
%operand = bf16[2,1024]{1,0} parameter(0),
sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
%indices = s32[8,512,1]{2,1,0} parameter(1),
sharding={devices=[2,1,1,2]0,2,1,3 last_tile_dim_replicate}
%updates = bf16[8,512,1024]{2,1,0} parameter(2),
sharding={devices=[2,1,2]0,2,1,3}
ROOT %scatter = bf16[2,1024]{1,0} scatter(bf16[2,1024]{1,0} %operand,
s32[8,512,1]{2,1,0} %indices,
bf16[8,512,1024]{2,1,0} %updates), update_window_dims={2},
inserted_window_dims={0}, scatter_dims_to_operand_dims={0},
index_vector_dim=2, to_apply=%scatter_add,
sharding={devices=[1,2,2]0,1,2,3 last_tile_dim_replicate}
})";
TF_ASSERT_OK_AND_ASSIGN(auto module,
PartitionComputation(hlo_string, /*num_devices=*/4));
VLOG(1) << module->ToString();
auto root = module->entry_computation()->root_instruction();
auto scatter = AllOf(op::Shape("bf16[2,512]"), op::Scatter(_, _, _));
EXPECT_THAT(root, scatter);
}
} // namespace
} // namespace spmd
} // namespace xla
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
98a28ea2b951c0886a3e52dedf8f2c79d7ba3469 | 62b021aec0aa47bb7566aa8517d4d7d1878001df | /include/rtti/metanamespace.h | a8de4e1e475704504bf6d3e8e1537505e64aea56 | [
"MIT"
] | permissive | elohim-meth/rtti | 7939c4acb9cf6a8a1d0b50e779c99c0614effa37 | c208d5b69d5d6bffb658a3b4bbdbc10d6224fed2 | refs/heads/master | 2021-06-18T06:23:24.063751 | 2021-03-10T10:02:16 | 2021-03-10T10:02:16 | 39,070,468 | 13 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 834 | h | #ifndef METANAMESPACE_H
#define METANAMESPACE_H
#include <rtti/metacontainer.h>
namespace rtti {
class MetaNamespacePrivate;
class RTTI_API MetaNamespace final: public MetaContainer
{
DECLARE_PRIVATE(MetaNamespace)
public:
static MetaNamespace const* global();
bool isGlobal() const;
MetaCategory category() const override;
protected:
using MetaContainer::MetaContainer;
static MetaNamespace* create(std::string_view name, MetaContainer &owner);
private:
MetaNamespace(); //global namespace
DECLARE_ACCESS_KEY(CreateAccessKey)
template<typename, typename> friend class rtti::meta_define;
};
public:
static MetaNamespace* create(std::string_view name, MetaContainer &owner, CreateAccessKey)
{ return create(name, owner); }
};
} // namespace rtti
#endif // METANAMESPACE_H
| [
"elohim-meth@yandex.ru"
] | elohim-meth@yandex.ru |
c67b9dd291dd1d1f44c263f767029c88cdde335a | c477e9f106f52369901ba3946f30f5af6df4b930 | /src/Fish.h | a2bb98a823cd63016482f122218345a8fe60cfc6 | [] | no_license | richelbilderbeek/GenomeAdmixR | 84ce904c8a87939bf9bb7684c117a06b05820637 | 8f7b0e4ebd4b5d484635cd25ceb5b481e343e95a | refs/heads/master | 2022-12-06T21:46:19.003792 | 2020-08-20T13:11:20 | 2020-08-20T13:11:20 | 289,009,428 | 0 | 0 | null | 2020-08-20T13:11:21 | 2020-08-20T13:09:37 | null | UTF-8 | C++ | false | false | 677 | h | //
// Fish.hpp
//
//
// Created by Thijs Janzen on 02/11/2017.
//
//
#ifndef Fish_hpp
#define Fish_hpp
#include <stdio.h>
#include <vector>
struct junction {
long double pos;
int right;
junction();
junction(long double loc, int B) ;
junction(const junction& other);
bool operator ==(const junction& other) const;
bool operator <(const junction& other) const;
bool operator !=(const junction& other) const;
};
struct Fish {
std::vector< junction > chromosome1;
std::vector< junction > chromosome2;
Fish();
Fish(int initLoc);
};
Fish mate(const Fish& A, const Fish& B, double numRecombinations);
#endif /* Fish_hpp */
| [
"thijsjanzen@gmail.com"
] | thijsjanzen@gmail.com |
e93c00f9dabd02bc9b5783dfee72763b8a11aaec | 733f41021ad37851a02b1ddcff1c455c9d9409a8 | /src/render_pipeline/enn_shadow_pre_pass.cpp | d896738e28d770db07692234de99c8ab9fc0cff6 | [] | no_license | zengqh/glRenderEngine | e8470abbd9e0e4093ca1065634d0845ff12b2ba6 | 7ae1033271857e4e19e53b034a348a9534106969 | refs/heads/master | 2020-04-02T10:43:45.241443 | 2018-10-23T15:32:11 | 2018-10-23T15:32:11 | 154,352,063 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,436 | cpp | //
// Copyright (c) 2013-2014 the enn project.
//
// 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.
//
// Time: 2013/08/21
// File: enn_shadow_pre_pass.cpp
//
#include "enn_shadow_pre_pass.h"
#include "enn_gl_rtt_pool.h"
#include "enn_root.h"
#include "enn_gl_render_target.h"
#include "enn_render_pipe.h"
namespace enn
{
ShadowPrePass::ShadowPrePass(RenderPipe* render_pipe)
: RenderPassBase(render_pipe)
, curr_cull_cam_(0)
, forward_general_render_(0)
, main_dir_lit_(0)
, shadow_rtt_(0)
{
}
ShadowPrePass::~ShadowPrePass()
{
}
void ShadowPrePass::render(Camera* cam)
{
if (!main_dir_lit_)
{
return;
}
renderShadowMap(cam, main_dir_lit_);
}
void ShadowPrePass::setMainDirLit(Light* light)
{
main_dir_lit_ = light;
}
void ShadowPrePass::setGeneralRender(GeneralRenderPass* general_render)
{
forward_general_render_ = general_render;
}
void ShadowPrePass::renderShadowMap(Camera* cam, Light* lit)
{
lit->updateShadowInfo(cam);
if (!lit->isShadowCurrActive())
{
return;
}
RenderSystem* rs = Root::getSingletonPtr()->get_render_system();
ShadowInfo* si = lit->getShadowInfo();
int rtt_size = si->need_rtt_size_;
if (!shadow_rtt_)
{
shadow_rtt_ = rs->getRttPool()->getRTTBuffer(F32_1, rtt_size, rtt_size);
RttPool::ItemTemp depth_temp = rs->getRttPool()->getDepthBufferTemp(D24, rtt_size, rtt_size);
si->link_rtt(shadow_rtt_, depth_temp);
}
/** render each split */
RenderTarget* render_target = si->render_target_;
RenderTarget::Iterator itvp = render_target->getViewports();
/** bind rtt */
render_target->begin_render();
rs->enableBlend(false);
SceneManager* sm = Root::getSingletonPtr()->getSceneManager();
bool is_first = true;
while (itvp.hasNext())
{
Viewport* vp = itvp.get().second;
curr_cull_cam_ = si->getCullCaster() + vp->getZOrder();
SceneFindShadowCasterByCamera finder;
finder.find(sm, curr_cull_cam_, &shadow_split_render_results_);
forward_general_render_->begin_insert_obj(GeneralRenderPass::GR_SHADOW);
ENN_FOR_EACH(RenderableNodeList, shadow_split_render_results_, it)
{
RenderableNode* rn = *it;
forward_general_render_->insert_obj(rn);
}
forward_general_render_->end_insert_obj();
if (is_first)
{
vp->apply();
is_first = false;
}
else
{
vp->applyOnlyVP();
}
forward_general_render_->render(vp->getCamera());
}
render_target->end_render();
rs->restoreMainViewport();
}
} | [
"zengqh.mansion@gmail.com"
] | zengqh.mansion@gmail.com |
c2fcb550cc91667ca968f15eebf1b243405b7667 | 05f66db47fdb07e6001f5c1356ada68244c5a1d8 | /Estructura de Datos/Apuntes/punteros/strings.cpp | 49990c1ebf08519a6ffad2de4d03c79efa3e5b7d | [] | no_license | Portilloglez95/Lenguaje-c | 197011f0daa89622893de70b3a904801c495d9fb | 0c363b8962dfde684e955c98eb492d1d2da203d8 | refs/heads/master | 2020-04-08T04:00:59.314927 | 2017-11-15T13:20:08 | 2017-11-15T13:20:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | cpp | /*
Fecha: 14/02/2017
Nota: Para declara una cadena por medio de punteros lo indicamos al
momento de declararla (char *identificador = "contenido";)
*identificador (accede al dato almacenado)
identificador (accede a la direccion de memoria)
*/
#include <cstdio>
int main()
{
// Declaramos una cadena
char *cadena = "Hola mundo";
// Mostramos la cadena por medio de un ciclo for
for(char *i = cadena; *i != '\0'; i++){
printf("%c", *i);
}
printf("\n\n");
// Imprimimos solo el primer caracter de la cadena
putchar(*cadena);
printf("\n\n");
printf("%c", *cadena);
return 0;
}
| [
"source.compu@gmail.com"
] | source.compu@gmail.com |
0b63bd58c9dfad9a85091af49cd346fb417d3ed7 | 826d8ce73bc03a8de50232663dc3806f60d85bd3 | /Usuario_arreglos/include/Estadistica.h | 595af719b66951c947a012f7b7e9b4ad93d2f48e | [] | no_license | LaTrifuerza/Proyectazo | 20d7443e20173919b53464eb1810078ddd4aeed4 | 656cc0f6ef9df51d9cf07bcfe345a891a5b23fcd | refs/heads/master | 2020-09-09T16:14:47.106129 | 2019-11-29T12:25:59 | 2019-11-29T12:25:59 | 221,493,683 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 536 | h | #ifndef ESTADISTICA_H
#define ESTADISTICA_H
#include "Usuario.h"
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Estadistica:public Usuario
{
private:
float IMC;
float auxPeso;
float auxAltura;
public:
Estadistica();
virtual ~Estadistica();
void opciones();
void Modificar();
float calcularIMC();
};
#endif // ESTADISTICA_H
| [
"noreply@github.com"
] | noreply@github.com |
a5b6d21b8c15233b67d944c5543a881281813f63 | 02099155d15b3d65330abc7276b13c8deff68e94 | /A/A. Letter/main.cpp | 0aedae1ff2d100d2324f2977862bdd357544a65f | [] | no_license | xUser5000/competitive-programming | d7c760fa6db58956e472dd80e24def0358bbb5a8 | 90337c982dd3663a69f2d19021e692f1edb1b3a5 | refs/heads/master | 2023-06-26T21:56:02.452867 | 2021-07-23T22:39:49 | 2021-07-23T22:39:49 | 288,557,139 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
map<char,int> mp;
string a, b;
getline(cin, a);
getline(cin, b);
for (char ch: a) {
if (ch == ' ') continue;
mp[ch]++;
}
for (char ch: b) {
if (ch == ' ') continue;
if (mp.find(ch) == mp.end() || mp[ch] == 0) {
cout << "NO";
return 0;
} else mp[ch]--;
}
cout << "YES";
return 0;
}
| [
"abdallah.11306@stemmenof.moe.edu.eg"
] | abdallah.11306@stemmenof.moe.edu.eg |
04c841a316d25b08c3fe79890653216a6ff54a8d | 0f2a1fa07030c8043db3dd4dc3ae5857c3070dcf | /D6-codes/strategy/LCGenerator.cpp | 8139a31b4e39eb119f1620d448c98fa5acb119ae | [] | no_license | pdicerbo/P1.5 | 0e271e458a1672bfd5273b63cf406264154e5dc1 | 400c31bc869efe0c40fefeabf8864fd546be3658 | refs/heads/master | 2021-01-19T03:47:55.305010 | 2015-11-17T12:22:31 | 2015-11-17T12:22:31 | 69,650,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | cpp | /* Created by G.P. Brandino for the Course P1.5 - Object Oriented Programming @ MHPC
* Last Revision: November 2015
*/
#include "LCGenerator.h"
LCGenerator::LCGenerator()
:
_seed( 0 ), _a( 1103515245 ), _c( 12345 ), _m( 1<<31 )
{
}
void LCGenerator::seed(unsigned int s )
{
_seed=s;
}
float LCGenerator::rnd()
{
_seed = ( _a * _seed + _c ) % _m ;
return ((float) _seed)/_m;
}
| [
"brandino@sissa.it"
] | brandino@sissa.it |
336f3735cec000f41ad228dd3d9bebaf0cb01e93 | 959bad0c9b9a198f2865c412ffa2122496433eb9 | /problemset/atcoderDP/g.cpp | b7b0d6de7efdb8885879958b168cebc748b512d5 | [] | no_license | leviwc/CompetitiveProgramming | 599d072dc8ecb6f53fe5db57ca11c517d74dce1b | 0a839b0800cb825e19dcf85cfdc726e9cb213086 | refs/heads/main | 2023-06-19T01:24:44.915108 | 2021-07-19T20:09:02 | 2021-07-19T20:09:02 | 386,133,800 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,790 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll INF = 2e18;
#define int long long
#define pb push_back
#define mp make_pair
#define pii pair<int, int>
#define vi vector<int>
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size();
#define endl "\n"
#define fastio \
cin.tie(NULL); \
cout.tie(NULL); \
ios_base::sync_with_stdio(false)
#define double long double
#define rep(i, x, n) for (int i = x; i < (n); i++)
#define td(i) i.begin(), i.end()
#define rtd(i) i.rbegin(), i.rend()
const double e = exp(1);
const double pi = acos(-1.0);
int gcd(int a, int b) {
while (b) {
a %= b;
swap(a, b);
}
return a;
}
int lcm(int a, int b) { return a / gcd(a, b) * b; }
long long binpows(long long a, long long b) {
long long res = 1;
while (b > 0) {
if (b & 1) // impar
res = res * a;
a = a * a;
b >>= 1; // /2
}
return res;
}
ll binpow(ll a, ll b, ll m) {
a %= m;
long long res = 1;
while (b > 0) {
if (b & 1) res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
void solve() {
int n, m;
cin >> n >> m;
vector<vector<int> > adj(n + 1);
vector<int> dp(n + 1);
for (int i = 0; i < n; i++) {
int a, b;
cin >> a >> b;
adj[b].pb(a);
}
int mai = 0;
for (int i = 1; i <= n; i++) {
for (int x : adj[i]) {
dp[i] = max(dp[i], dp[x] + 1);
}
mai = max(mai, dp[i]);
}
cout << mai << endl;
}
// revise as variaveis e a ordem nas funções
signed main() {
// freopen("zeros.in", "r", stdin);
// freopen("hidden.out", "w", stdout);
fastio;
int t = 1;
// cin >> t;
while (t--) {
solve();
}
}
| [
"leviwc3@hotmail.com"
] | leviwc3@hotmail.com |
2ea437cb1fa8c1b47f5785b32afab3f58e846146 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_new_hunk_671.cpp | 87b056e4a560a37aac528de29e16981bb7364da3 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,985 | cpp | /* Copyright 1999-2005 The Apache Software Foundation or its licensors, as
* applicable.
*
* 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.
*/
/*
* Info Module. Display configuration information for the server and
* all included modules.
*
* <Location /server-info>
* SetHandler server-info
* </Location>
*
* GET /server-info - Returns full configuration page for server and all modules
* GET /server-info?server - Returns server configuration only
* GET /server-info?module_name - Returns configuration for a single module
* GET /server-info?list - Returns quick list of included modules
* GET /server-info?config - Returns full configuration
* GET /server-info?hooks - Returns a listing of the modules active for each hook
*
* Original Author:
* Rasmus Lerdorf <rasmus vex.net>, May 1996
*
* Modified By:
* Lou Langholtz <ldl usi.utah.edu>, July 1997
*
* Apache 2.0 Port:
* Ryan Morgan <rmorgan covalent.net>, August 2000
*
*/
#include "apr.h"
#include "apr_strings.h"
#include "apr_lib.h"
#define APR_WANT_STRFUNC
#include "apr_want.h"
#define CORE_PRIVATE
#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_main.h"
#include "http_protocol.h"
#include "http_connection.h"
#include "http_request.h"
#include "util_script.h"
#include "ap_mpm.h"
typedef struct
{
const char *name; /* matching module name */
const char *info; /* additional info */
} info_entry;
typedef struct
{
apr_array_header_t *more_info;
} info_svr_conf;
module AP_MODULE_DECLARE_DATA info_module;
static void *create_info_config(apr_pool_t * p, server_rec * s)
{
info_svr_conf *conf =
(info_svr_conf *) apr_pcalloc(p, sizeof(info_svr_conf));
conf->more_info = apr_array_make(p, 20, sizeof(info_entry));
return conf;
}
static void *merge_info_config(apr_pool_t * p, void *basev, void *overridesv)
{
info_svr_conf *new =
(info_svr_conf *) apr_pcalloc(p, sizeof(info_svr_conf));
info_svr_conf *base = (info_svr_conf *) basev;
info_svr_conf *overrides = (info_svr_conf *) overridesv;
new->more_info =
apr_array_append(p, overrides->more_info, base->more_info);
return new;
}
static void put_int_flush_right(request_rec * r, int i, int field)
{
if (field > 1 || i > 9)
put_int_flush_right(r, i / 10, field - 1);
if (i)
ap_rputc('0' + i % 10, r);
else
ap_rputs(" ", r);
}
static void mod_info_indent(request_rec * r, int nest,
const char *thisfn, int linenum)
{
int i;
const char *prevfn =
ap_get_module_config(r->request_config, &info_module);
if (thisfn == NULL)
thisfn = "*UNKNOWN*";
if (prevfn == NULL || 0 != strcmp(prevfn, thisfn)) {
thisfn = ap_escape_html(r->pool, thisfn);
ap_rprintf(r, "<dd><tt><strong>In file: %s</strong></tt></dd>\n",
thisfn);
ap_set_module_config(r->request_config, &info_module,
(void *) thisfn);
}
ap_rputs("<dd><tt>", r);
put_int_flush_right(r, linenum > 0 ? linenum : 0, 4);
ap_rputs(": ", r);
for (i = 1; i <= nest; ++i) {
ap_rputs(" ", r);
}
}
static void mod_info_show_cmd(request_rec * r, const ap_directive_t * dir,
int nest)
{
mod_info_indent(r, nest, dir->filename, dir->line_num);
ap_rprintf(r, "%s <i>%s</i></tt></dd>\n",
ap_escape_html(r->pool, dir->directive),
ap_escape_html(r->pool, dir->args));
}
static void mod_info_show_open(request_rec * r, const ap_directive_t * dir,
int nest)
{
mod_info_indent(r, nest, dir->filename, dir->line_num);
ap_rprintf(r, "%s %s</tt></dd>\n",
ap_escape_html(r->pool, dir->directive),
ap_escape_html(r->pool, dir->args));
}
static void mod_info_show_close(request_rec * r, const ap_directive_t * dir,
int nest)
{
const char *dirname = dir->directive;
mod_info_indent(r, nest, dir->filename, 0);
if (*dirname == '<') {
ap_rprintf(r, "</%s></tt></dd>",
ap_escape_html(r->pool, dirname + 1));
}
else {
ap_rprintf(r, "/%s</tt></dd>", ap_escape_html(r->pool, dirname));
}
}
static int mod_info_has_cmd(const command_rec * cmds, ap_directive_t * dir)
{
const command_rec *cmd;
if (cmds == NULL)
return 1;
for (cmd = cmds; cmd->name; ++cmd) {
if (strcasecmp(cmd->name, dir->directive) == 0)
return 1;
}
return 0;
}
static void mod_info_show_parents(request_rec * r, ap_directive_t * node,
int from, int to)
{
if (from < to)
mod_info_show_parents(r, node->parent, from, to - 1);
mod_info_show_open(r, node, to);
}
static int mod_info_module_cmds(request_rec * r, const command_rec * cmds,
ap_directive_t * node, int from, int level)
{
int shown = from;
ap_directive_t *dir;
if (level == 0)
ap_set_module_config(r->request_config, &info_module, NULL);
for (dir = node; dir; dir = dir->next) {
if (dir->first_child != NULL) {
if (level < mod_info_module_cmds(r, cmds, dir->first_child,
shown, level + 1)) {
shown = level;
mod_info_show_close(r, dir, level);
}
}
else if (mod_info_has_cmd(cmds, dir)) {
if (shown < level) {
mod_info_show_parents(r, dir->parent, shown, level - 1);
shown = level;
}
mod_info_show_cmd(r, dir, level);
}
}
return shown;
}
typedef struct
{ /*XXX: should get something from apr_hooks.h instead */
void (*pFunc) (void); /* just to get the right size */
const char *szName;
const char *const *aszPredecessors;
const char *const *aszSuccessors;
int nOrder;
} hook_struct_t;
/*
* hook_get_t is a pointer to a function that takes void as an argument and
* returns a pointer to an apr_array_header_t. The nasty WIN32 ifdef
* is required to account for the fact that the ap_hook* calls all use
* STDCALL calling convention.
*/
typedef apr_array_header_t *(
#ifdef WIN32
__stdcall
#endif
* hook_get_t) (void);
typedef struct
{
const char *name;
hook_get_t get;
} hook_lookup_t;
static hook_lookup_t startup_hooks[] = {
{"Pre-Config", ap_hook_get_pre_config},
{"Test Configuration", ap_hook_get_test_config},
{"Post Configuration", ap_hook_get_post_config},
{"Open Logs", ap_hook_get_open_logs},
{"Child Init", ap_hook_get_child_init},
{NULL},
};
static hook_lookup_t request_hooks[] = {
{"Pre-Connection", ap_hook_get_pre_connection},
{"Create Connection", ap_hook_get_create_connection},
{"Process Connection", ap_hook_get_process_connection},
{"Create Request", ap_hook_get_create_request},
{"Post-Read Request", ap_hook_get_post_read_request},
{"Header Parse", ap_hook_get_header_parser},
{"HTTP Scheme", ap_hook_get_http_scheme},
{"Default Port", ap_hook_get_default_port},
{"Quick Handler", ap_hook_get_quick_handler},
{"Translate Name", ap_hook_get_translate_name},
{"Map to Storage", ap_hook_get_map_to_storage},
{"Check Access", ap_hook_get_access_checker},
{"Verify User ID", ap_hook_get_check_user_id},
{"Verify User Access", ap_hook_get_auth_checker},
{"Check Type", ap_hook_get_type_checker},
{"Fixups", ap_hook_get_fixups},
{"Insert Filters", ap_hook_get_insert_filter},
{"Content Handlers", ap_hook_get_handler},
{"Logging", ap_hook_get_log_transaction},
{"Insert Errors", ap_hook_get_insert_error_filter},
{NULL},
};
static int module_find_hook(module * modp, hook_get_t hook_get)
{
int i;
apr_array_header_t *hooks = hook_get();
hook_struct_t *elts;
if (!hooks) {
return 0;
}
elts = (hook_struct_t *) hooks->elts;
for (i = 0; i < hooks->nelts; i++) {
if (strcmp(elts[i].szName, modp->name) == 0) {
return 1;
}
}
return 0;
}
static void module_participate(request_rec * r,
module * modp,
hook_lookup_t * lookup, int *comma)
{
if (module_find_hook(modp, lookup->get)) {
if (*comma) {
ap_rputs(", ", r);
}
ap_rvputs(r, "<tt>", lookup->name, "</tt>", NULL);
*comma = 1;
}
}
static void module_request_hook_participate(request_rec * r, module * modp)
{
int i, comma = 0;
ap_rputs("<dt><strong>Request Phase Participation:</strong>\n", r);
for (i = 0; request_hooks[i].name; i++) {
module_participate(r, modp, &request_hooks[i], &comma);
}
if (!comma) {
ap_rputs("<tt> <em>none</em></tt>", r);
}
ap_rputs("</dt>\n", r);
}
static const char *find_more_info(server_rec * s, const char *module_name)
{
int i;
info_svr_conf *conf =
(info_svr_conf *) ap_get_module_config(s->module_config,
&info_module);
info_entry *entry = (info_entry *) conf->more_info->elts;
if (!module_name) {
return 0;
}
for (i = 0; i < conf->more_info->nelts; i++) {
| [
"993273596@qq.com"
] | 993273596@qq.com |
154de783d57cf7a42ea1ddbc86362e20ffaeae99 | cf7ae4ac2644daa52e0f7c5ae30c72b66d15fc7f | /LegendDataEditor/LegendDataEditor/Sqlite/Data/TDBuff.h | 462b287fad196b42a12cceb0c5625ad7480626b1 | [] | no_license | ZHOURUIH/GameEditor | 13cebb5037a46d1c414c944b4f0229b26d859fb5 | eb391bd8c2bec8976c29047183722f90d75af361 | refs/heads/master | 2023-08-21T10:56:59.318660 | 2023-08-10T16:33:40 | 2023-08-10T16:33:40 | 133,002,663 | 18 | 21 | null | null | null | null | UTF-8 | C++ | false | false | 581 | h | #ifndef _TD_BUFF_H_
#define _TD_BUFF_H_
#include "SQLiteData.h"
class TDBuff : public SQLiteData
{
public:
static const char* ID;
static const char* Name;
static const char* Description;
static const char* NotifyPlayer;
static const char* NotifyOthers;
public:
int mID;
string mName;
string mDescription;
bool mNotifyPlayer;
bool mNotifyOthers;
public:
TDBuff()
{
registeParam(mID, ID);
registeParam(mName, Name);
registeParam(mDescription, Description);
registeParam(mNotifyPlayer, NotifyPlayer);
registeParam(mNotifyOthers, NotifyOthers);
}
};
#endif | [
"785130190@qq.com"
] | 785130190@qq.com |
6c6a49f6ce51b2923048525fd9f24b1ecb8a2bb2 | d0700ba442a0239abce547cda15e3a70537a29fe | /copy.cpp | 8bd714ba8b2aee3e1c493246df1cdfc25d519a5a | [] | no_license | ClausKlein/samples | 9fd369f1f40b3d44c3b26a4d159f89c7ab77c42a | 07563fb9f90df1459df61e4f15d3c68a00edb29a | refs/heads/develop | 2021-07-05T08:57:01.365290 | 2020-11-12T09:00:02 | 2020-11-12T09:00:02 | 200,117,955 | 1 | 0 | null | 2020-10-30T22:40:20 | 2019-08-01T20:54:34 | C++ | UTF-8 | C++ | false | false | 1,161 | cpp | /* copy.cpp
Copy the file named argv[1] to a new file named in argv[2].
*/
#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, char *argv[])
{
if (strcmp(argv[1], "--help") == 0) {
cerr << argv[0] << " [old-file [new-file]]" << endl;
exit(EXIT_FAILURE);
}
const istream &in(cin);
ostream &out(cout);
// Open input and output files
if (argc > 1) {
cerr << argv[1] << endl;
ifstream _in(argv[1], ios::in | ios::binary);
// FIXME const in = _in;
if (argc > 2) {
cerr << argv[2] << endl;
ofstream _out(argv[2], ios::out | ios::binary | ios::trunc);
_out << _in.rdbuf(); // or: in >> out.rdbuf();
// FIXME private operator= out=_out;
} else {
cout << _in.rdbuf();
}
} else {
// FIXME Bus error cout << cin.rdbuf(); // or: cin >> cout.rdbuf();
}
// copy contents
// XXX out << in.rdbuf(); // or: in >> out.rdbuf();
if (out && in) {
exit(EXIT_SUCCESS);
} else {
exit(EXIT_FAILURE);
}
}
| [
"claus.klein@arcormail.de"
] | claus.klein@arcormail.de |
dee8131bfbddf057e8ebe7d4747f4a14e4e01edb | 78da2c3fc16fb25587576c406b101a7e07e35c6a | /src/run_upload_task.hh | 22ef6465ae02d9b419006728acde1baca97fe75e | [
"Apache-2.0",
"CC-BY-4.0"
] | permissive | amoe/figshare-uploader | a0ff57710a2c4fce9efa46705b7aed01781e2118 | 6a2c32c8521891e7f5e37670e7adb37dafbda3da | refs/heads/master | 2023-06-23T02:32:02.736670 | 2023-06-13T07:04:08 | 2023-06-13T07:04:08 | 113,032,906 | 7 | 1 | Apache-2.0 | 2022-09-23T16:24:49 | 2017-12-04T11:13:08 | C++ | UTF-8 | C++ | false | false | 609 | hh | #include <QObject>
#include <QThread>
#include <QString>
#include "slot_adapter.hh"
#include "driver_thread.hh"
#include "mapping_types.hh"
class RunUploadTask : public QObject {
public:
RunUploadTask(
Driver* driver, StringAdapter adapter, StringAdapter errorAdapter,
string inputPath, const MappingScheme& fieldMappings
);
~RunUploadTask();
void run();
public slots:
void onPartiallyDone(QString qValue);
void onFatalError(QString qValue);
void onFullyDone();
private:
StringAdapter adapter;
StringAdapter errorAdapter;
DriverThread* theTask;
};
| [
"amoebae@gmail.com"
] | amoebae@gmail.com |
811c9776497bf0a5cc68a49b67036e7a63b78e7a | 744bdc8b6929eb67069b3332b9eb0ac1386a96a7 | /misc/UndoStack.cpp | e7f6749e97a5768f44164ff0e6e786aa321c2b79 | [] | no_license | adam-davis/CS-Capstone | dc426d91e99df639462212c4548f96f68f98ea0d | 955dfc5614fe73356aa9016ccac388e380a938c9 | refs/heads/master | 2016-09-06T01:59:44.600307 | 2012-08-05T00:22:49 | 2012-08-05T00:22:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 695 | cpp | #include "UndoStack.h"
void UndoStack::saveUndoState(QImage& theImage)
{
undoVector.push_back(new QImage(theImage));
undoPointer++;
}
UndoStack::~UndoStack()
{
for(int i = 0; i < undoVector.size();i++)
delete undoVector[i];
}
void UndoStack::undo(QImage& theImage)
{
if(undoPointer >= 0)
{
if(undoPointer > 0)
undoPointer--;
theImage = *undoVector[undoPointer];
}
}
void UndoStack::redo(QImage& theImage)
{
int i = undoVector.size()-1;
if(undoPointer < i)
{
++undoPointer;
theImage = *undoVector[undoPointer];
}
}
void UndoStack::cleanUndoStack()
{
for(int i = undoVector.size()-1;i > undoPointer;--i)
{
delete undoVector[i];
undoVector.pop_back();
}
} | [
"adavis71@kent.edu"
] | adavis71@kent.edu |
14a4613b5e20e396aaaa58fd1ef68812fe55416f | 08ae5bb64b354f65f5bcd938771a67e848b76868 | /Week_04/153_findMin.cpp | 0e61a3a8ba15e5da3c2ba0cbbb18bc33257d6f54 | [] | no_license | larry07/algorithm014-algorithm014 | b6be762a64ab37af11ce246cd93698f009f5e5bf | 63ccaac82cdebbbb2443f58ca723e06d491c2330 | refs/heads/master | 2023-01-06T14:04:06.523964 | 2020-10-31T15:51:52 | 2020-10-31T15:51:52 | 286,749,464 | 0 | 0 | null | 2020-08-11T13:17:41 | 2020-08-11T13:17:40 | null | UTF-8 | C++ | false | false | 983 | cpp | class Solution {
public:
int findMin(vector<int>& nums) {
if(nums.empty())return -1;
int n = nums.size();
if(n==1||nums[0]<nums[n-1])return nums[0];//不保证一定拆为2个升序 {1,2}
int left = 0;
int right = nums.size() - 1;
while (left < right)
{
int mid = left + ((right - left) >> 1);
if (nums[mid] > nums[right]) //mid左 right右
left = mid + 1;
else
right = mid; //right拉近到更左的右区
}
return nums[left];
}
};
int l=0,r=n-1,mid;
while(l<=r){
mid = (l+r)/2;
int m=nums[mid];
if(mid>0 && nums[mid-1]>m)return m;
if(mid+1<n && m>nums[mid+1])return nums[mid+1]; //自己的繁琐了 只想到了边界条件
if(nums[0]<m){//左半区
l = mid+1;
}else{
r = mid-1;
}
} | [
"wangyulongx@163.com"
] | wangyulongx@163.com |
5cc29b5a66f0e0b3eb40585f5a5ef5f8aeb45e2c | 163162f1834a18d529991fd2f3d2a3a18b7fd4e1 | /code2.cpp | b1768e38384f1dbe1d936eecd98fdabbfea14910 | [] | no_license | windersegura/proyectoalgritmos | 89b0e5235ee3ade2c2d2941b6de0e464b6a45eaf | d810833a741be98b1d0ac604f2e6bb2cd9ddaae2 | refs/heads/master | 2021-05-02T13:44:28.809552 | 2017-03-08T08:51:00 | 2017-03-08T08:51:00 | 72,668,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 947 | cpp | #include <iostream>
#include <fstream>
#include <conio.h>
#include <string>
#include <cstdlib>
#include <ctype.h>
using namespace std;
void pausa ();
void pausa (){
cout<<"Desea volver al menu 's' / 'n' "<<endl;
getwchar();
//getwchar();
}
/*void funcion_venta(){
int cantidad=0;
char dec;
}
*/
int main (){
//proceso del menu
char tecla;
do{
cout<<" Menu de opciones"<<endl;
cout<<"A) Registrar Ventas"<<endl;
cout<<"B) Consultar Catalogo "<<endl;
cout<<"C) salir."<<endl;
do{
do{
tecla=toupper(getch());
}while(!isalpha(tecla));
}while((tecla < 'A') || (tecla > 'C'));
switch(tecla){
case 'A' :
system("cls");
cout<<"venta";
pausa();
break;
case 'B' :
system("cls");
cout<<"catalogo";
pausa();
break;
}
system("cls");
}while(tecla!='C');
//fin del menu
getch();
}
| [
"noreply@github.com"
] | noreply@github.com |
8102e35ef8832e74f7a4c650d55c3eacfa8dcea9 | b08698f3a84923b9308aad61eb4d71aa808ba06f | /src/testApp.h | d938903c3b03c9bc9923c4ce5da1884cfa30b8ce | [] | no_license | tomschofield/triggerShiftKinectToOsc | bc767f5346b983c029dc353807ab61a72092e6b0 | ea4ffa181fbc3b9e576b77e87c55a411c740fe51 | refs/heads/master | 2021-01-23T13:29:17.760480 | 2012-04-24T16:12:54 | 2012-04-24T16:12:54 | null | 0 | 0 | null | null | null | null | MacCentralEurope | C++ | false | false | 3,488 | h | /*
cc tom schofield 2012
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
I acknowledge the following code libraries
oxOpenNI,
Copyright 2011 (c) Matthew Gingold http://gingold.com.au
* Originally forked from a project by roxlu http://www.roxlu.com/
ofxOsc,
Copyright (c) 2007-2009, Damian Stewart
All rights reserved
and osc message format to fit
osceleton https://github.com/Sensebloom/OSCeleton
The above copyleft 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 COPYLEFT 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.
*/
#ifndef _TEST_APP
#define _TEST_APP
//#define USE_IR // Uncomment this to use infra red instead of RGB cam...
#include "ofxOpenNI.h"
#include "ofMain.h"
#include "ofxOsc.h"
#include "KinectGesture.h"
#include "User.h"
#define HOST "localhost"
#define PORT 7110
class testApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed (int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void jointOSCMessage(ofxLimb * jointName, string jointString, int nUserNum);
void userJointOSCMessage(ofPoint jointName, string jointString, int nUserNum);
void handOSCMessage(ofxTrackedHand * aHand, string handString, int nHandNum);
void gestureOSCmessage(string gestureName, bool gestureIsOn, int nUserNum);
void sendUserInfo(ofxTrackedUser * aUser, int nUserNum);
void sendHandInfo(ofxTrackedHand * aHand, int nUserNum);
void sendNewUserInfo(int nUserNum);
void setupOpenNI();
void setupPlayback(string _filename);
string generateFileName();
//returns vector of joint points and has a pointer to given vector of strings TODO - fix this ridiculous pointer approach
vector<ofPoint> passJointInfo(ofxTrackedUser * aUser, vector<string> & jointNames, int nUserNum);
vector<ofPoint> user1Joints;
vector<string> user1JointNames;
ofxOscSender sender;
bool isTracking;
float tilt;
ofxOpenNIContext context;
ofxDepthGenerator depth;
ofTrueTypeFont font;
vector<User> users;
#ifdef USE_IR
ofxIRGenerator image;
#else
ofxImageGenerator image;
#endif
//not currently used
ofxHandGenerator handTracker;
ofxUserGenerator user;
#if defined (TARGET_OSX) //|| defined(TARGET_LINUX) // only working on Mac/Linux at the moment (but on Linux you need to run as sudo...)
ofxHardwareDriver hardware;
#endif
void drawMasks();
void drawPointCloud(ofxUserGenerator * user_generator, int userID);
int nearThreshold, farThreshold;
int pointCloudRotationY;
ofImage allUserMasks, user1Mask, user2Mask, depthRangeMask;
float filterFactor;
//actually position rather than gesture
KinectGesture kGesture;
};
#endif
| [
"tomschofieldart@gmail.com"
] | tomschofieldart@gmail.com |
1ee9646334a4c082987ee242e610002a60c378ae | 0edbcda83b7a9542f15f706573a8e21da51f6020 | /private/shell/cplwiz/access/pgwizopt.cpp | 732fcddc7be3be233d088d9c74a4053c6f3297c8 | [] | no_license | yair-k/Win2000SRC | fe9f6f62e60e9bece135af15359bb80d3b65dc6a | fd809a81098565b33f52d0f65925159de8f4c337 | refs/heads/main | 2023-04-12T08:28:31.485426 | 2021-05-08T22:47:00 | 2021-05-08T22:47:00 | 365,623,923 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,057 | cpp | #include "pch.hxx" // pch
#pragma hdrstop
#include "resource.h"
#include "pgWizOpt.h"
CWizardOptionsPg::CWizardOptionsPg(
LPPROPSHEETPAGE ppsp
) : WizardPage(ppsp, 0, 0)
{
m_dwPageId = IDD_WIZOPTIONS;
ppsp->pszTemplate = MAKEINTRESOURCE(m_dwPageId);
}
CWizardOptionsPg::~CWizardOptionsPg(
VOID
)
{
}
DWORD g_rgdwWizNoOptionsSelected[] = {IDD_WIZNOOPTIONSSELECTED};
DWORD g_rgdwWizDoFonts[] = {
0, // min text size
/* IDD_PREV_MINTEXT1,
IDD_PREV_MINTEXT2,
IDD_PREV_MINTEXT3,
IDD_FNTWIZMINTEXT,
*/
IDD_FNTWIZMINTEXT2,
0, // scroll bar
/*
IDD_PREV_SCROLL1,
IDD_PREV_SCROLL2,
IDD_FNTWIZSCROLLBAR,
*/
0, // border
/*
IDD_PREV_BORDER1,
IDD_PREV_BORDER2,
*/
IDD_PREV_ICON1
};
DWORD g_rgdwWizDoColors[] = {
IDD_PREV_COLOR,
// IDD_CLRWIZHIGHCONTRAST
};
DWORD g_rgdwWizDoSounds[] = {
IDD_SNDWIZSENTRYSHOWSOUNDS,
};
DWORD g_rgdwWizDoKeyboard[] = {
IDD_KBDWIZSTICKYKEYS,
IDD_KBDWIZFILTERKEYS,
IDD_KBDWIZTOGGLEKEYS,
IDD_KBDWIZSHOWEXTRAKEYBOARDHELP,
// IDD_KBDWIZSERIALKEYS
};
DWORD g_rgdwWizDoMouse[] = {
IDD_MSEWIZMOUSEKEYS,
IDD_MSEWIZMOUSECURSOR,
IDD_MSEWIZBUTTONCONFIG
};
DWORD g_rgdwWizFinalPages[] = {
IDD_WIZHOTKEYANDNOTIFICATION,
0,
/* // For usability tests
IDD_WIZACCESSTIMEOUT1,
IDD_WIZACCESSTIMEOUT2,
*/
IDD_WIZWORKSTATIONDEFAULT,
IDD_WIZSAVETOFILE,
IDD_WIZFINISH
};
BOOL CWizardOptionsPg::AdjustWizPageOrder()
{
// HACK TO DYNAMICALLY CHANGE WHICH PAGES ARE USED BY THE WIZARD
switch(g_Options.m_nTypeMinText)
{
case 0: g_rgdwWizDoFonts[0] = IDD_PREV_MINTEXT1;break;
case 1: g_rgdwWizDoFonts[0] = IDD_PREV_MINTEXT2;break;
case 2: g_rgdwWizDoFonts[0] = IDD_PREV_MINTEXT3;break;
case 3: g_rgdwWizDoFonts[0] = IDD_FNTWIZMINTEXT;break;
}
switch(g_Options.m_nTypeScrollBar)
{
case 0: g_rgdwWizDoFonts[2] = IDD_PREV_SCROLL1;break;
case 1: g_rgdwWizDoFonts[2] = IDD_PREV_SCROLL2;break;
case 2: g_rgdwWizDoFonts[2] = IDD_FNTWIZSCROLLBAR;break;
}
switch(g_Options.m_nTypeBorder)
{
case 0: g_rgdwWizDoFonts[3] = IDD_PREV_BORDER1;break;
case 1: g_rgdwWizDoFonts[3] = IDD_PREV_BORDER2;break;
}
switch(g_Options.m_nTypeAccTimeOut)
{
case 0: g_rgdwWizFinalPages[1] = IDD_WIZACCESSTIMEOUT1;break;
case 1: g_rgdwWizFinalPages[1] = IDD_WIZACCESSTIMEOUT2;break;
}
BOOL bDoFonts = Button_GetCheck(GetDlgItem(m_hwnd, IDC_DOFONTS));
BOOL bDoColors = Button_GetCheck(GetDlgItem(m_hwnd, IDC_DOCOLORS));
BOOL bDoSounds = Button_GetCheck(GetDlgItem(m_hwnd, IDC_DOSOUND));
BOOL bDoKeyboard = Button_GetCheck(GetDlgItem(m_hwnd, IDC_DOKEYBOARD));
BOOL bDoMouse = Button_GetCheck(GetDlgItem(m_hwnd, IDC_DOMOUSE));
BOOL bDoNoOptions = (!bDoColors && !bDoFonts && !bDoSounds && !bDoKeyboard && !bDoMouse);
// First remove all possible pages since we want to insert them in the correct order
// Return value does not matter since the pages may not be in the array
sm_WizPageOrder.RemovePages(g_rgdwWizNoOptionsSelected, ARRAYSIZE(g_rgdwWizNoOptionsSelected));
sm_WizPageOrder.RemovePages(g_rgdwWizDoFonts, ARRAYSIZE(g_rgdwWizDoFonts));
sm_WizPageOrder.RemovePages(g_rgdwWizDoColors, ARRAYSIZE(g_rgdwWizDoColors));
sm_WizPageOrder.RemovePages(g_rgdwWizDoSounds, ARRAYSIZE(g_rgdwWizDoSounds));
sm_WizPageOrder.RemovePages(g_rgdwWizDoKeyboard, ARRAYSIZE(g_rgdwWizDoKeyboard));
sm_WizPageOrder.RemovePages(g_rgdwWizDoMouse, ARRAYSIZE(g_rgdwWizDoMouse));
sm_WizPageOrder.RemovePages(g_rgdwWizFinalPages, ARRAYSIZE(g_rgdwWizFinalPages));
// Then Add in pages in groups in the reverse order that we want them to appear.
// We do them this way since they are inserted after this page, so the first group inserted
// will be the last group at the end of this.
// NOTE: We do not care about the return value from AddPages() in the sense
// that we they do not allocate or free memory so it does not hurt to keep calling them. We
// Will propogate a return value of FALSE if any of them fail.
BOOL bSuccess = TRUE;
// Add Final Pages
bSuccess = bSuccess && sm_WizPageOrder.AddPages(m_dwPageId, g_rgdwWizFinalPages, ARRAYSIZE(g_rgdwWizFinalPages));
if(bDoNoOptions)
bSuccess = bSuccess && sm_WizPageOrder.AddPages(m_dwPageId, g_rgdwWizNoOptionsSelected, ARRAYSIZE(g_rgdwWizNoOptionsSelected));
if(bDoMouse)
bSuccess = bSuccess && sm_WizPageOrder.AddPages(m_dwPageId, g_rgdwWizDoMouse, ARRAYSIZE(g_rgdwWizDoMouse));
if(bDoKeyboard)
bSuccess = bSuccess && sm_WizPageOrder.AddPages(m_dwPageId, g_rgdwWizDoKeyboard, ARRAYSIZE(g_rgdwWizDoKeyboard));
// If keyboard was selected, but mouse was not selected, add the mousekeys page at the end of the keyboard page
if(bDoKeyboard && !bDoMouse)
{
DWORD dw = IDD_MSEWIZMOUSEKEYS;
bSuccess = bSuccess && sm_WizPageOrder.AddPages(g_rgdwWizDoKeyboard[ARRAYSIZE(g_rgdwWizDoKeyboard) - 1], &dw, 1);
}
if(bDoSounds)
bSuccess = bSuccess && sm_WizPageOrder.AddPages(m_dwPageId, g_rgdwWizDoSounds, ARRAYSIZE(g_rgdwWizDoSounds));
if(bDoColors & !bDoFonts) // Don't add colors here if we have fonts to add
bSuccess = bSuccess && sm_WizPageOrder.AddPages(m_dwPageId, g_rgdwWizDoColors, ARRAYSIZE(g_rgdwWizDoColors));
if(bDoFonts)
bSuccess = bSuccess && sm_WizPageOrder.AddPages(m_dwPageId, g_rgdwWizDoFonts, ARRAYSIZE(g_rgdwWizDoFonts));
if(bDoFonts && bDoColors) // Add the colors here if we also have fonts
bSuccess = bSuccess && sm_WizPageOrder.AddPages(IDD_FNTWIZMINTEXT2, g_rgdwWizDoColors, ARRAYSIZE(g_rgdwWizDoColors));
return bSuccess;
}
LRESULT
CWizardOptionsPg::OnCommand(
HWND hwnd,
WPARAM wParam,
LPARAM lParam
)
{
LRESULT lResult = 1;
WORD wNotifyCode = HIWORD(wParam);
WORD wCtlID = LOWORD(wParam);
HWND hwndCtl = (HWND)lParam;
switch(wCtlID)
{
case IDC_BTNRESTORETODEFAULT:
MessageBox(m_hwnd, __TEXT("Not Yet Implemented"), __TEXT("Error"), MB_OK);
// g_Options.ApplyWindowsDefault();
break;
default:
break;
}
return lResult;
}
| [
"ykorokhov@pace.ca"
] | ykorokhov@pace.ca |
8e3b51f67467e3c8c6563b72b181160ed68abc96 | f7630e0933c2cf480f869e361680a269f1ac50aa | /sololearn/IsogramDetector/IsogramDetector.cpp | 9b11c45f9776b12764635a11f77ab0a48453cd86 | [] | no_license | chankruze/challenges | 9a4ef0065e92d404676333c99b02bd22c6b52922 | daf494e7775bb0de5afcfdcfd45aa73e6a950e0e | refs/heads/master | 2022-02-17T06:20:22.946043 | 2021-02-03T11:46:44 | 2021-02-03T11:46:44 | 202,938,560 | 5 | 5 | null | 2022-02-07T17:52:27 | 2019-08-17T22:59:13 | C++ | UTF-8 | C++ | false | false | 536 | cpp | /*
Author: chankruze (chankruze@geekofia.in)
Created: Tue Aug 25 2020 21:24:53 GMT+0530 (India Standard Time)
Copyright (c) Geekofia 2020 and beyond
*/
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
bool isIsogram(string word) {
unordered_set<char> set;
for (char c : word) {
set.insert(c);
}
return (word.length() == set.size());
}
int main(int argc, char const *argv[]) {
string word;
cin >> word;
cout << (isIsogram(word) ? "true" : "false") << endl;
}
| [
"chankruze@gmail.com"
] | chankruze@gmail.com |
a3f3074db6c94f44a02b7a08271c98629a23ef8c | 77b91ed9e8f72ee913af0a39c64ebcc7aaf3388a | /xcbb/xcbb/xutils.h | ba378409c7455cb0c32b749786b3e604f86050b1 | [] | no_license | eaglenature/XCBB | 70a821004f85eca9f972453b50fcebfc7bcebece | 234184f3811202e1f47095c29cd7dee0cc613c61 | refs/heads/master | 2016-08-02T22:16:05.709441 | 2013-05-03T16:38:32 | 2013-05-03T16:38:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,190 | h | /*
* <xcbb/xutils.h>
*
* Created on: Apr 1, 2013
* Author: eaglenature@gmail.com
*/
#ifndef XUTILS_H_
#define XUTILS_H_
#define WARP_SIZE 32
struct NoValue {};
template <typename T>
struct IsKeyOnly
{ static const bool value = false; };
template <>
struct IsKeyOnly<NoValue>
{ static const bool value = true; };
template <int n> struct VectorTypeTraits;
template <> struct VectorTypeTraits<1> { typedef uint type; };
template <> struct VectorTypeTraits<2> { typedef uint2 type; };
template <> struct VectorTypeTraits<4> { typedef uint4 type; };
template <typename T, int NumElements>
struct Vectorized;
template <typename T>
struct Vectorized<T, 1> { T x; };
template <typename T>
struct Vectorized<T, 2> { T x, y; };
template <typename T>
struct Vectorized<T, 3> { T x, y, z; };
template <typename T>
struct Vectorized<T, 4> { T x, y, z, w; };
template <typename T>
__device__ __forceinline__
T Default() { return T(); }
template <>
__device__ __forceinline__
uint Default<uint>() { return (uint)-1u; }
__device__ __forceinline__
uint2 operator+(const uint2& a, const uint2& b)
{
return make_uint2(a.x + b.x, a.y + b.y);
}
__device__ __forceinline__
uint4 operator+(const uint4& a, const uint4& b)
{
return make_uint4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
__device__ __forceinline__
uint2 operator+(const uint2& a, uint alpha)
{
return make_uint2(a.x + alpha, a.y + alpha);
}
__device__ __forceinline__
uint4 operator+(const uint4& a, uint alpha)
{
return make_uint4(a.x + alpha, a.y + alpha, a.z + alpha, a.w + alpha);
}
template <int NUM_ELEMENTS_PER_THREAD>
__device__ __forceinline__
int GetWarpDataOffset(int warp)
{
return warp * WARP_SIZE * NUM_ELEMENTS_PER_THREAD;
}
template <int NUM_ELEMENTS_PER_THREAD>
__device__ __forceinline__
int GetBlockDataOffset(int block, int tilesPerBlock)
{
return block * tilesPerBlock * blockDim.x * NUM_ELEMENTS_PER_THREAD;
}
template <int NUM_ELEMENTS_PER_THREAD>
__device__ __forceinline__
int GetBlockDataOffset(int precedingTiles)
{
return precedingTiles * blockDim.x * NUM_ELEMENTS_PER_THREAD;
}
template <int NUM_ELEMENTS_PER_THREAD>
__device__ __forceinline__
int GetTileDataOffset(int tile)
{
return tile * blockDim.x * NUM_ELEMENTS_PER_THREAD;
}
template <int NUM_WARPS, int WARP_STORAGE_SIZE>
__device__ __forceinline__
void LoadReduceAndStore(
uint shared_storage[NUM_WARPS][WARP_STORAGE_SIZE],
uint2* global_storage,
int warp,
int lane)
{
uint2 word = global_storage[lane];
shared_storage[warp][lane] = word.x + word.y;
}
template <int NUM_WARPS, int WARP_STORAGE_SIZE>
__device__ __forceinline__
void LoadReduceAndStore(
uint shared_storage[NUM_WARPS][WARP_STORAGE_SIZE],
uint4* global_storage,
int warp,
int lane)
{
uint4 word = global_storage[lane];
shared_storage[warp][lane] = word.x + word.y + word.z + word.w;
}
__device__ __forceinline__
uint LoadReduce(
uint* global_storage,
int lane)
{
uint word = global_storage[lane];
return word;
}
__device__ __forceinline__
uint LoadReduce(
uint2* global_storage,
int lane)
{
uint2 word = global_storage[lane];
return word.x + word.y;
}
__device__ __forceinline__
uint LoadReduce(
uint4* global_storage,
int lane)
{
uint4 word = global_storage[lane];
return word.x + word.y + word.z + word.w;
}
/*
* Reduce word
*/
__device__ __forceinline__
uint ReduceWord(const uint& word)
{
return word;
}
__device__ __forceinline__
uint ReduceWord(const uint2& word)
{
return word.x + word.y;
}
__device__ __forceinline__
uint ReduceWord(const uint4& word)
{
return word.x + word.y + word.z + word.w;
}
/*
* Scan word
*/
__device__ __host__ __forceinline__
void ScanWord(uint& word)
{
word = 0;
}
__device__ __host__ __forceinline__
void ScanWord(uint2& word)
{
word.y = word.x;
word.x = 0;
}
__device__ __host__ __forceinline__
void ScanWord(uint4& word)
{
uint sum, x;
sum = 0;
x = word.x; word.x = sum; sum += x;
x = word.y; word.y = sum; sum += x;
x = word.z; word.z = sum; sum += x;
x = word.w; word.w = sum;
}
__device__ __host__ __forceinline__
void ScanWord(uint& word, int seed)
{
word = seed;
}
__device__ __host__ __forceinline__
void ScanWord(uint2& word, int seed)
{
word.y = word.x + seed;
word.x = seed;
}
__device__ __host__ __forceinline__
void ScanWord(uint4& word, int seed)
{
uint sum, x;
sum = 0;
x = word.x; word.x = sum + seed; sum += x;
x = word.y; word.y = sum + seed; sum += x;
x = word.z; word.z = sum + seed; sum += x;
x = word.w; word.w = sum + seed;
}
/*
* Scan segment
*/
template <int NUM_ELEMENTS>
__device__ __host__ __forceinline__
void ScanSegment(uint segment[])
{
uint sum, x;
sum = 0;
#pragma unroll
for (int i = 0; i < NUM_ELEMENTS; ++i)
{
x = segment[i];
segment[i] = sum;
sum += x;
}
}
template <int NUM_ELEMENTS>
__device__ __host__ __forceinline__
void ScanSegment(uint segment[], int seed)
{
uint sum, x;
sum = 0;
#pragma unroll
for (int i = 0; i < NUM_ELEMENTS; ++i)
{
x = segment[i];
segment[i] = sum + seed;
sum += x;
}
}
__device__ __host__ __forceinline__
void ScanSegment(uint* segment, int num_elements)
{
uint sum, x;
sum = 0;
for (int i = 0; i < num_elements; ++i)
{
x = segment[i];
segment[i] = sum;
sum += x;
}
}
__device__ __host__ __forceinline__
void ScanSegment(uint* segment, int num_elements, int seed)
{
uint sum, x;
sum = 0;
for (int i = 0; i < num_elements; ++i)
{
x = segment[i];
segment[i] = sum + seed;
sum += x;
}
}
template <int NUM_ELEMENTS>
__device__ __host__ __forceinline__
void ScanSegment(int segment[], int seed)
{
int sum, x;
sum = 0;
#pragma unroll
for (int i = 0; i < NUM_ELEMENTS; ++i)
{
x = segment[i];
segment[i] = sum + seed;
sum += x;
}
}
__device__ __host__ __forceinline__
void ScanSegment(int* segment, int num_elements)
{
int sum, x;
sum = 0;
for (int i = 0; i < num_elements; ++i)
{
x = segment[i];
segment[i] = sum;
sum += x;
}
}
__device__ __host__ __forceinline__
void ScanSegment(int* segment, int num_elements, int seed)
{
int sum, x;
sum = 0;
for (int i = 0; i < num_elements; ++i)
{
x = segment[i];
segment[i] = sum + seed;
sum += x;
}
}
template <int NUM_WARPS, int WARP_STORAGE_SIZE>
__device__ __forceinline__
uint* GetWarpStorage(
uint shared_storage[NUM_WARPS][WARP_STORAGE_SIZE],
int warp)
{
return &shared_storage[warp][0];
}
/*
* TODO implement version with no conditionals that reqire WARP_SIZE + WARP_SIZE/2 shared memory
*/
__device__ __forceinline__
void KoggeStoneWarpExclusiveScan(volatile uint* shared_storage, int tid)
{
uint x = shared_storage[tid];
int sum = x;
if (tid >= 1) sum += shared_storage[tid - 1];
shared_storage[tid] = sum;
if (tid >= 2) sum += shared_storage[tid - 2];
shared_storage[tid] = sum;
if (tid >= 4) sum += shared_storage[tid - 4];
shared_storage[tid] = sum;
if (tid >= 8) sum += shared_storage[tid - 8];
shared_storage[tid] = sum;
if (tid >= 16) sum += shared_storage[tid - 16];
shared_storage[tid] = sum;
shared_storage[tid] = sum - x;
}
/*
* TODO implement version with no conditionals that reqire WARP_SIZE + WARP_SIZE/2 shared memory
*/
__device__ __forceinline__
void KoggeStoneWarpExclusiveScan(volatile uint* shared_storage, int tid, int seed)
{
uint x = shared_storage[tid];
int sum = x;
if (tid >= 1) sum += shared_storage[tid - 1];
shared_storage[tid] = sum;
if (tid >= 2) sum += shared_storage[tid - 2];
shared_storage[tid] = sum;
if (tid >= 4) sum += shared_storage[tid - 4];
shared_storage[tid] = sum;
if (tid >= 8) sum += shared_storage[tid - 8];
shared_storage[tid] = sum;
if (tid >= 16) sum += shared_storage[tid - 16];
shared_storage[tid] = sum;
shared_storage[tid] = sum - x + seed;
}
/*
* TODO implement version with no conditionals that reqire WARP_SIZE + WARP_SIZE/2 shared memory
*/
__device__ __forceinline__
void KoggeStoneWarpInclusiveScan(volatile uint* shared_storage, int tid)
{
int sum = shared_storage[tid];
if (tid >= 1) sum += shared_storage[tid - 1];
shared_storage[tid] = sum;
if (tid >= 2) sum += shared_storage[tid - 2];
shared_storage[tid] = sum;
if (tid >= 4) sum += shared_storage[tid - 4];
shared_storage[tid] = sum;
if (tid >= 8) sum += shared_storage[tid - 8];
shared_storage[tid] = sum;
if (tid >= 16) sum += shared_storage[tid - 16];
shared_storage[tid] = sum;
}
/*
* TODO implement version with no conditionals that reqire WARP_SIZE + WARP_SIZE/2 shared memory
*/
__device__ __forceinline__
void KoggeStoneWarpInclusiveScan(volatile uint* shared_storage, int tid, int seed)
{
int sum = shared_storage[tid];
if (tid >= 1) sum += shared_storage[tid - 1];
shared_storage[tid] = sum;
if (tid >= 2) sum += shared_storage[tid - 2];
shared_storage[tid] = sum;
if (tid >= 4) sum += shared_storage[tid - 4];
shared_storage[tid] = sum;
if (tid >= 8) sum += shared_storage[tid - 8];
shared_storage[tid] = sum;
if (tid >= 16) sum += shared_storage[tid - 16];
shared_storage[tid] = sum + seed;
}
/*
* TODO implement version with no conditionals that reqire WARP_SIZE + WARP_SIZE/2 shared memory
*/
__device__ __forceinline__
void KoggeStoneWarpReduceTODO(volatile uint* shared_storage, int tid)
{
//uint x = shared_storage[tid];
int sum = shared_storage[tid];
sum += shared_storage[tid + 1];
shared_storage[tid] = sum;
sum += shared_storage[tid + 2];
shared_storage[tid] = sum;
sum += shared_storage[tid + 4];
shared_storage[tid] = sum;
sum += shared_storage[tid + 8];
shared_storage[tid] = sum;
sum += shared_storage[tid + 16];
shared_storage[tid] = sum;
}
__device__ __forceinline__
void KoggeStoneWarpReduce(volatile uint* shared_storage, int tid)
{
//uint x = shared_storage[tid];
int sum = shared_storage[tid];
if (tid < WARP_SIZE - 1) sum += shared_storage[tid + 1];
shared_storage[tid] = sum;
if (tid < WARP_SIZE - 2) sum += shared_storage[tid + 2];
shared_storage[tid] = sum;
if (tid < WARP_SIZE - 4) sum += shared_storage[tid + 4];
shared_storage[tid] = sum;
if (tid < WARP_SIZE - 8) sum += shared_storage[tid + 8];
shared_storage[tid] = sum;
if (tid < WARP_SIZE - 16) sum += shared_storage[tid + 16];
shared_storage[tid] = sum;
}
/*
* NUM_ELEMENTS = 64 => Active Threads = 32
* NUM_ELEMENTS = 32 => Active Threads = 16
* NUM_ELEMENTS = 16 => Active Threads = 8
* NUM_ELEMENTS = 8 => Active Threads = 4
* NUM_ELEMENTS = 4 => Active Threads = 2
* NUM_ELEMENTS = 2 => Active Threads = 1
*/
template <int NUM_ELEMENTS>
__device__ __forceinline__
void WarpReduce(volatile uint* shared_storage, int tid)
{
if (tid < (NUM_ELEMENTS >> 1))
{
if (NUM_ELEMENTS > 32) shared_storage[tid] += shared_storage[tid + 32];
if (NUM_ELEMENTS > 16) shared_storage[tid] += shared_storage[tid + 16];
if (NUM_ELEMENTS > 8) shared_storage[tid] += shared_storage[tid + 8];
if (NUM_ELEMENTS > 4) shared_storage[tid] += shared_storage[tid + 4];
if (NUM_ELEMENTS > 2) shared_storage[tid] += shared_storage[tid + 2];
if (NUM_ELEMENTS > 1) shared_storage[tid] += shared_storage[tid + 1];
}
}
template <int NUM_ELEMENTS>
__device__ __forceinline__
int SerialReduce(uint* segment)
{
uint reduce = 0;
#pragma unroll
for (int i = 0; i < NUM_ELEMENTS; ++i)
{
reduce += segment[i];
}
return reduce;
}
__device__ __forceinline__
int SerialReduce(uint* segment, int num_elements)
{
uint reduce = 0;
for (int i = 0; i < num_elements; ++i)
{
reduce += segment[i];
}
return reduce;
}
template <int NUM_ELEMENTS>
__device__ __forceinline__ int SerialReduce(int* segment)
{
int reduce = 0;
#pragma unroll
for (int i = 0; i < NUM_ELEMENTS; ++i)
{
reduce += segment[i];
}
return reduce;
}
__device__ __forceinline__
int SerialReduce(int* segment, int num_elements)
{
int reduce = 0;
for (int i = 0; i < num_elements; ++i)
{
reduce += segment[i];
}
return reduce;
}
// TODO do it more generic for raking segment other than 4
__device__ __forceinline__
uint* GetRakingThreadDataSegment(
uint shared_storage[][WARP_SIZE + 1],
int lane)
{
/*
* Get offset of lane in [4][33] input array, used only by single warp
* row = lane/8, col = (lane%8)*4,
*/
return &shared_storage[lane >> 3][(lane & 7) << 2];
}
__device__ __forceinline__
void WarpRakingReduce(
uint* shared_totals,
uint shared_storage[][WARP_SIZE + 1],
int lane)
{
/*
* Single warp perform serial reduction in shared memory
*/
shared_totals[lane] = SerialReduce<4>(GetRakingThreadDataSegment(shared_storage, lane));
/*
* Warp synchronous reduction Kogge-Stone
*/
KoggeStoneWarpReduce(shared_totals, lane);
}
__device__ __forceinline__
uint WarpRakingScan(
uint* shared_totals,
uint shared_storage[][WARP_SIZE + 1],
int lane)
{
/*
* Single warp perform serial reduction in shared memory
*/
uint x = shared_totals[lane] = SerialReduce<4>(GetRakingThreadDataSegment(shared_storage, lane));
/*
* Warp synchronous scan Kogge-Stone
*/
KoggeStoneWarpExclusiveScan(shared_totals, lane);
x += shared_totals[lane];
/*
* Single warp perform serial scan and seed in shared memory
*/
ScanSegment<4>(GetRakingThreadDataSegment(shared_storage, lane), shared_totals[lane]);
/*
* last lane returns total of current tile
*/
return x;
}
#endif /* XUTILS_H_ */
| [
"eaglenature@gmail.com"
] | eaglenature@gmail.com |
708e1fbc371eb3e7f6d27cfdb2cba7d6631c25c9 | 612325535126eaddebc230d8c27af095c8e5cc2f | /src/net/http/http_network_transaction_ssl_unittest.cc | 890d7ed4a0e0e47790ae2fe478912dc5ae105447 | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/proto-quic_1V94 | 1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673 | feee14d96ee95313f236e0f0e3ff7719246c84f7 | refs/heads/master | 2023-04-01T14:36:53.888576 | 2019-10-17T02:23:04 | 2019-10-17T02:23:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,880 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <string>
#include <vector>
#include "base/deferred_sequenced_task_runner.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/threading/thread.h"
#include "net/base/request_priority.h"
#include "net/cert/ct_policy_enforcer.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/cert/multi_log_ct_verifier.h"
#include "net/dns/mock_host_resolver.h"
#include "net/http/http_auth_handler_mock.h"
#include "net/http/http_network_session.h"
#include "net/http/http_network_transaction.h"
#include "net/http/http_request_info.h"
#include "net/http/http_server_properties_impl.h"
#include "net/http/transport_security_state.h"
#include "net/log/net_log_with_source.h"
#include "net/proxy/proxy_service.h"
#include "net/socket/socket_test_util.h"
#include "net/ssl/default_channel_id_store.h"
#include "net/test/gtest_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using net::test::IsError;
using net::test::IsOk;
namespace net {
namespace {
class TokenBindingSSLConfigService : public SSLConfigService {
public:
TokenBindingSSLConfigService() {
ssl_config_.token_binding_params.push_back(TB_PARAM_ECDSAP256);
}
void GetSSLConfig(SSLConfig* config) override { *config = ssl_config_; }
private:
~TokenBindingSSLConfigService() override {}
SSLConfig ssl_config_;
};
} // namespace
class HttpNetworkTransactionSSLTest : public testing::Test {
protected:
HttpNetworkTransactionSSLTest() = default;
void SetUp() override {
ssl_config_service_ = new TokenBindingSSLConfigService;
session_params_.ssl_config_service = ssl_config_service_.get();
auth_handler_factory_.reset(new HttpAuthHandlerMock::Factory());
session_params_.http_auth_handler_factory = auth_handler_factory_.get();
proxy_service_ = ProxyService::CreateDirect();
session_params_.proxy_service = proxy_service_.get();
session_params_.client_socket_factory = &mock_socket_factory_;
session_params_.host_resolver = &mock_resolver_;
session_params_.http_server_properties = &http_server_properties_;
session_params_.cert_verifier = &cert_verifier_;
session_params_.transport_security_state = &transport_security_state_;
session_params_.cert_transparency_verifier = &ct_verifier_;
session_params_.ct_policy_enforcer = &ct_policy_enforcer_;
}
HttpRequestInfo* GetRequestInfo(const std::string& url) {
HttpRequestInfo* request_info = new HttpRequestInfo;
request_info->url = GURL(url);
request_info->method = "GET";
request_info_vector_.push_back(base::WrapUnique(request_info));
return request_info;
}
scoped_refptr<SSLConfigService> ssl_config_service_;
std::unique_ptr<HttpAuthHandlerMock::Factory> auth_handler_factory_;
std::unique_ptr<ProxyService> proxy_service_;
MockClientSocketFactory mock_socket_factory_;
MockHostResolver mock_resolver_;
HttpServerPropertiesImpl http_server_properties_;
MockCertVerifier cert_verifier_;
TransportSecurityState transport_security_state_;
MultiLogCTVerifier ct_verifier_;
CTPolicyEnforcer ct_policy_enforcer_;
HttpNetworkSession::Params session_params_;
std::vector<std::unique_ptr<HttpRequestInfo>> request_info_vector_;
};
#if !defined(OS_IOS)
TEST_F(HttpNetworkTransactionSSLTest, TokenBinding) {
ChannelIDService channel_id_service(new DefaultChannelIDStore(NULL));
session_params_.channel_id_service = &channel_id_service;
SSLSocketDataProvider ssl_data(ASYNC, OK);
ssl_data.token_binding_negotiated = true;
ssl_data.token_binding_key_param = TB_PARAM_ECDSAP256;
mock_socket_factory_.AddSSLSocketDataProvider(&ssl_data);
MockRead mock_reads[] = {MockRead("HTTP/1.1 200 OK\r\n\r\n"),
MockRead(SYNCHRONOUS, OK)};
StaticSocketDataProvider data(mock_reads, arraysize(mock_reads), NULL, 0);
mock_socket_factory_.AddSocketDataProvider(&data);
HttpNetworkSession session(session_params_);
HttpNetworkTransaction trans1(DEFAULT_PRIORITY, &session);
TestCompletionCallback callback;
int rv = callback.GetResult(
trans1.Start(GetRequestInfo("https://www.example.com/"),
callback.callback(), NetLogWithSource()));
EXPECT_THAT(rv, IsOk());
HttpRequestHeaders headers1;
ASSERT_TRUE(trans1.GetFullRequestHeaders(&headers1));
std::string token_binding_header1;
EXPECT_TRUE(headers1.GetHeader(HttpRequestHeaders::kTokenBinding,
&token_binding_header1));
// Send a second request and verify that the token binding header is the same
// as in the first request.
mock_socket_factory_.AddSSLSocketDataProvider(&ssl_data);
StaticSocketDataProvider data2(mock_reads, arraysize(mock_reads), NULL, 0);
mock_socket_factory_.AddSocketDataProvider(&data2);
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, &session);
rv = callback.GetResult(
trans2.Start(GetRequestInfo("https://www.example.com/"),
callback.callback(), NetLogWithSource()));
EXPECT_THAT(rv, IsOk());
HttpRequestHeaders headers2;
ASSERT_TRUE(trans2.GetFullRequestHeaders(&headers2));
std::string token_binding_header2;
EXPECT_TRUE(headers2.GetHeader(HttpRequestHeaders::kTokenBinding,
&token_binding_header2));
EXPECT_EQ(token_binding_header1, token_binding_header2);
}
TEST_F(HttpNetworkTransactionSSLTest, NoTokenBindingOverHttp) {
ChannelIDService channel_id_service(new DefaultChannelIDStore(NULL));
session_params_.channel_id_service = &channel_id_service;
SSLSocketDataProvider ssl_data(ASYNC, OK);
ssl_data.token_binding_negotiated = true;
ssl_data.token_binding_key_param = TB_PARAM_ECDSAP256;
mock_socket_factory_.AddSSLSocketDataProvider(&ssl_data);
MockRead mock_reads[] = {MockRead("HTTP/1.1 200 OK\r\n\r\n"),
MockRead(SYNCHRONOUS, OK)};
StaticSocketDataProvider data(mock_reads, arraysize(mock_reads), NULL, 0);
mock_socket_factory_.AddSocketDataProvider(&data);
HttpNetworkSession session(session_params_);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, &session);
TestCompletionCallback callback;
int rv =
callback.GetResult(trans.Start(GetRequestInfo("http://www.example.com/"),
callback.callback(), NetLogWithSource()));
EXPECT_THAT(rv, IsOk());
HttpRequestHeaders headers;
ASSERT_TRUE(trans.GetFullRequestHeaders(&headers));
std::string token_binding_header;
EXPECT_FALSE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
&token_binding_header));
}
// Regression test for https://crbug.com/667683.
TEST_F(HttpNetworkTransactionSSLTest, TokenBindingAsync) {
// Create a separate thread for ChannelIDService
// so that asynchronous Channel ID creation can be delayed.
base::Thread channel_id_thread("ThreadForChannelIDService");
channel_id_thread.Start();
scoped_refptr<base::DeferredSequencedTaskRunner> channel_id_runner =
new base::DeferredSequencedTaskRunner(channel_id_thread.task_runner());
ChannelIDService channel_id_service(new DefaultChannelIDStore(nullptr));
channel_id_service.set_task_runner_for_testing(channel_id_runner);
session_params_.channel_id_service = &channel_id_service;
SSLSocketDataProvider ssl_data(ASYNC, OK);
ssl_data.token_binding_negotiated = true;
ssl_data.token_binding_key_param = TB_PARAM_ECDSAP256;
ssl_data.next_proto = kProtoHTTP2;
mock_socket_factory_.AddSSLSocketDataProvider(&ssl_data);
MockRead reads[] = {MockRead(ASYNC, OK, 0)};
StaticSocketDataProvider data(reads, arraysize(reads), nullptr, 0);
mock_socket_factory_.AddSocketDataProvider(&data);
HttpRequestInfo request_info;
request_info.url = GURL("https://www.example.com/");
request_info.method = "GET";
request_info.token_binding_referrer = "encrypted.example.com";
HttpNetworkSession session(session_params_);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, &session);
TestCompletionCallback callback;
int rv = trans.Start(&request_info, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
base::RunLoop().RunUntilIdle();
// When ChannelIdService calls back to HttpNetworkSession,
// SpdyHttpStream should not crash.
channel_id_runner->Start();
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CONNECTION_CLOSED));
}
#endif // !defined(OS_IOS)
} // namespace net
| [
"2100639007@qq.com"
] | 2100639007@qq.com |
2fc672844e63177f9bd2dece3703f924426eef42 | 9c16d6b984c9a22c219bd2a20a02db21a51ba8d7 | /components/signin/core/browser/account_tracker_service.h | 327124e18a9ba7f0cfd17c94efc226ed70d16190 | [
"BSD-3-Clause"
] | permissive | nv-chromium/chromium-crosswalk | fc6cc201cb1d6a23d5f52ffd3a553c39acd59fa7 | b21ec2ffe3a13b6a8283a002079ee63b60e1dbc5 | refs/heads/nv-crosswalk-17 | 2022-08-25T01:23:53.343546 | 2019-01-16T21:35:23 | 2019-01-16T21:35:23 | 63,197,891 | 0 | 0 | NOASSERTION | 2019-01-16T21:38:06 | 2016-07-12T22:58:43 | null | UTF-8 | C++ | false | false | 5,894 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_TRACKER_SERVICE_H_
#define COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_TRACKER_SERVICE_H_
#include <list>
#include <map>
#include <string>
#include <vector>
#include "base/memory/ref_counted.h"
#include "base/observer_list.h"
#include "base/threading/non_thread_safe.h"
#include "base/timer/timer.h"
#include "components/keyed_service/core/keyed_service.h"
#include "google_apis/gaia/gaia_auth_util.h"
class PrefService;
class SigninClient;
namespace base {
class DictionaryValue;
}
namespace user_prefs {
class PrefRegistrySyncable;
}
// AccountTrackerService is a KeyedService that retrieves and caches GAIA
// information about Google Accounts.
class AccountTrackerService : public KeyedService,
public base::NonThreadSafe {
public:
// Name of the preference property that persists the account information
// tracked by this service.
static const char kAccountInfoPref[];
// TODO(mlerman): Remove all references to Profile::kNoHostedDomainFound in
// favour of this.
// Value representing no hosted domain in the kProfileHostedDomain preference.
static const char kNoHostedDomainFound[];
// Value representing no picture URL associated with an account.
static const char kNoPictureURLFound[];
// TODO(knn): Move to ChildAccountInfoFetcher once deprecated service flags
// have been migrated from preferences.
// Child account service flag name.
static const char kChildAccountServiceFlag[];
// Information about a specific account.
struct AccountInfo {
AccountInfo();
~AccountInfo();
std::string account_id; // The account ID used by OAuth2TokenService.
std::string gaia;
std::string email;
std::string full_name;
std::string given_name;
std::string hosted_domain;
std::string locale;
std::string picture_url;
bool is_child_account;
bool IsValid() const;
};
// Clients of AccountTrackerService can implement this interface and register
// with AddObserver() to learn about account information changes.
class Observer {
public:
virtual ~Observer() {}
virtual void OnAccountUpdated(const AccountInfo& info) {}
virtual void OnAccountUpdateFailed(const std::string& account_id) {}
virtual void OnAccountRemoved(const AccountInfo& info) {}
};
// Possible values for the kAccountIdMigrationState preference.
enum AccountIdMigrationState {
MIGRATION_NOT_STARTED,
MIGRATION_IN_PROGRESS,
MIGRATION_DONE
};
AccountTrackerService();
~AccountTrackerService() override;
// Registers the preferences used by AccountTrackerService.
static void RegisterPrefs(user_prefs::PrefRegistrySyncable* registry);
// KeyedService implementation.
void Shutdown() override;
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
// Take a SigninClient rather than a PrefService and a URLRequestContextGetter
// since RequestContext cannot be created at startup.
// (see http://crbug.com/171406)
void Initialize(SigninClient* signin_client);
// Returns the list of known accounts and for which gaia IDs
// have been fetched.
std::vector<AccountInfo> GetAccounts() const;
AccountInfo GetAccountInfo(const std::string& account_id);
AccountInfo FindAccountInfoByGaiaId(const std::string& gaia_id);
AccountInfo FindAccountInfoByEmail(const std::string& email);
// Picks the correct account_id for the specified account depending on the
// migration state.
std::string PickAccountIdForAccount(const std::string& gaia,
const std::string& email);
static std::string PickAccountIdForAccount(PrefService* pref_service,
const std::string& gaia,
const std::string& email);
// Seeds the account whose account_id is given by PickAccountIdForAccount()
// with its corresponding gaia id and email address. Returns the same
// value PickAccountIdForAccount() when given the same arguments.
std::string SeedAccountInfo(const std::string& gaia,
const std::string& email);
void SeedAccountInfo(AccountInfo info);
AccountIdMigrationState GetMigrationState();
void SetMigrationDone();
static AccountIdMigrationState GetMigrationState(PrefService* pref_service);
protected:
// Available to be called in tests.
void SetAccountStateFromUserInfo(const std::string& account_id,
const base::DictionaryValue* user_info);
void SetIsChildAccount(const std::string& account_id,
const bool& is_child_account);
private:
friend class AccountFetcherService;
friend class FakeAccountFetcherService;
struct AccountState {
AccountInfo info;
};
void NotifyAccountUpdated(const AccountState& state);
void NotifyAccountUpdateFailed(const std::string& account_id);
void NotifyAccountRemoved(const AccountState& state);
void StartTrackingAccount(const std::string& account_id);
void StopTrackingAccount(const std::string& account_id);
// Load the current state of the account info from the preferences file.
void LoadFromPrefs();
void SaveToPrefs(const AccountState& account);
void RemoveFromPrefs(const AccountState& account);
// Gaia id migration.
bool IsMigratable();
void MigrateToGaiaId();
void SetMigrationState(AccountIdMigrationState state);
SigninClient* signin_client_; // Not owned.
std::map<std::string, AccountState> accounts_;
base::ObserverList<Observer> observer_list_;
DISALLOW_COPY_AND_ASSIGN(AccountTrackerService);
};
#endif // COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_TRACKER_SERVICE_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
9cd14cb85c64f5cd228e2c2687b25f4737836c86 | dc9c7c3c48efa0f1c58af04f24cdd726258a8a4d | /PTA作业/数据结构第2章/7-3.cpp | 38dbcd8c1a445c911e4346f1d61403ca094c3e8d | [] | no_license | Whiteyingshan/DataStructureClass | f6373f98ca2f63e74d0d6c688ff2048712e4ca94 | 9decfb85eda9596997cf63a7fe0a847d9e20d139 | refs/heads/master | 2020-07-18T06:59:03.455484 | 2019-11-13T01:29:45 | 2019-11-13T01:29:45 | 206,201,723 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 609 | cpp | #include<iostream>
using namespace std;
#define LL long long
//n个人编号为1到n,从1开始报数,报到k出列,返回m(<=n)个出列的人
LL Josephus(LL n, LL k, LL m) {
if (k == 1)return m;
LL x = (k - 1) % (n + 1 - m);
for (LL i = n + 1 - m; i < n;) {
LL y = min((i - x + k - 2) / (k - 1) - 1, n - i);
if (y)x += y * k, i += y;
else ++i, x = (x + k) % i;
}
return x + 1;
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i < n; i++)
cout << Josephus(n, m, i) << " ";
cout << Josephus(n, m, n) << endl;
return 0;
}
| [
"a1746345173@163.com"
] | a1746345173@163.com |
010f610c7414c1501bf8ba2678920430f12645b8 | e72b9816962f1070b75e8f6c0f1d31663d147aee | /ontap/lthdt-bai2.cpp | 5447995d7bed97f8e09aa6560385770a65710a54 | [] | no_license | DevDKhanh/bai_tap_lthdt | 4afeee468826e45a1d5b270eeb4d1833af141e86 | 37e659feda6f075423329a8e0590b2e5fafa42f5 | refs/heads/master | 2023-08-14T21:13:59.786557 | 2021-10-19T03:51:10 | 2021-10-19T03:51:10 | 397,417,129 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,944 | cpp | /*
Thoi gian co gio, phut. Gio co gia tri tu 0-23, phut co gia tri tu 0-59. Nhap vao thoi gian bat dau va so
phut lam bai thi cua 1 ca thi.
Yeu cau su dung toan tu >> , << de nhap vao va dua ra thoi gian o danh h:mm,
su dung toan tu + de thoi gian voi so phut, thoi gian ban dau
duoc khoi tao gia tri tu dong voi gio phut bang 0
*/
#include <iostream>
#include <stdio.h>
#include<math.h>
using namespace std;
// class ThoiGian
class ThoiGian
{
private:
int gio, phut;
public:
ThoiGian();
ThoiGian(int gio, int phut);
friend istream& operator>>(istream &cin, ThoiGian &tg);
friend ostream& operator<<(ostream &cout, ThoiGian &tg);
ThoiGian operator+(int phut);
};
//===Chuong trinh chinh===
int main()
{
ThoiGian thoigian;
int phutLamBai;
cout<<"Nhap phut lam bai: "<<endl;
cin>>phutLamBai;
cout<<"Nhap lan luot gio va phut bat dau: "<<endl;
cin>>thoigian;
cout<<"Thoi gian bat dau: "<<thoigian;
//Tinh gio ket thuc
thoigian+phutLamBai;
cout<<"Thoi gian ket thuc la: "<< thoigian;
cout << endl;
return 0;
}
//===Dinh nghia ham===
ThoiGian::ThoiGian():gio(0),phut(0)
{
}
ThoiGian::ThoiGian(int gio, int phut):gio(gio),phut(phut)
{
}
istream& operator>>(istream &cin, ThoiGian &tg)
{
while(true)
{
cin>>tg.gio>>tg.phut;
if(tg.gio<0||tg.gio>23||tg.phut<0||tg.phut>59)
{
cout<<"Vui long kiem tra lai gio-phut da nhap\nNhap lai:\n";
}
else
return cin;
}
}
ostream& operator<<(ostream &cout, ThoiGian &tg)
{
char s;
cout<<tg.gio<<":"<<tg.phut<<endl;
return cout;
}
ThoiGian ThoiGian::operator+(int phutLamBai)
{
ThoiGian fake;
if(phut+phutLamBai>59) {
int heSo = ceil((phutLamBai+phut)/60);
gio+=heSo;
phut=phut+phutLamBai-(60*heSo);
}
else
{
phut=phut+phutLamBai;
}
return fake;
} | [
"duykhanh06.work@gmail.com"
] | duykhanh06.work@gmail.com |
83c0df46bef94fc620af13f35f5498ca075d3f88 | 644c0b6d7053bff658bdc58c3eaff3adbe8a1197 | /devices/gizmodev.h | 3c05bb674112c9ab732e0496beb56844b0062a8a | [] | no_license | digetx/tegra2_qemu_trace_viewer | d35a8cb4962d51fcfb9a69c764209ab01e59f36b | 39769ca66b8d0a386fd6760b0362908486672c0a | refs/heads/master | 2020-12-20T21:36:44.116265 | 2017-01-12T13:43:52 | 2017-01-12T13:43:52 | 38,266,845 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,835 | h | /*
* Copyright (c) 2014-2015 Dmitry Osipenko <digetx@gmail.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GIZMODEV_H
#define GIZMODEV_H
#include "device.h"
class GizmoDev : public Device
{
Q_OBJECT
using Device::Device;
signals:
public slots:
private:
void fill_ahb_mem_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_apb_dma_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ide_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_usb_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_xbar_bridge_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_cpu_ahb_bridge_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_cop_ahb_bridge_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_xbar_apb_ctlr_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_vcp_ahb_bridge_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_nand_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_sdmmc4_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_xio_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_bsev_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_bsea_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_nor_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_usb2_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_usb3_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_sdmmc1_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_sdmmc2_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_sdmmc3_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_mem_prefetch_cfg_x_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_arbitration_xbar_ctrl_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_mem_prefetch_cfg3_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_mem_prefetch_cfg4_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_avp_ppcs_rd_coh_status_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_mem_prefetch_cfg1_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_mem_prefetch_cfg2_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_ahbslvmem_status_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_arbitration_ahb_mem_wrque_mst_id_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_arbitration_cpu_abort_info_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_arbitration_cpu_abort_addr_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_arbitration_cop_abort_info_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_arbitration_cop_abort_addr_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_avpc_mccif_fifoctrl_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_timeout_wcoal_avpc_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_arbitration_disable_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_arbitration_priority_ctrl_details(const u_int32_t &value, const u_int32_t &new_value);
void fill_ahb_arbitration_usr_protect_details(const u_int32_t &value, const u_int32_t &new_value);
bool is_offset_valid(const u_int32_t &offset) const;
bool is_undef_changed(const u_int32_t &offset,
const u_int32_t &value,
const u_int32_t &new_value) const;
// Device interface
private:
QString get_register_name(const log_entry &entry) const;
void fill_bits_details(const u_int32_t &offset, const u_int32_t &value,
const u_int32_t &new_value);
};
#endif // GIZMODEV_H
| [
"digetx@gmail.com"
] | digetx@gmail.com |
0d4e384a342e290217465f14bf75d34663ad0c41 | 44b30e2db14761b90f133e86eca8c994261240c9 | /SecB/14-Nov19/bin2stream1.cpp | c1ea380d09df132c83de0a342d8c5235fac4346f | [] | no_license | FahdW/OOP344-20123 | 1edfa66ce2faaf763721d84ba206c8c736b82ca9 | fbfe7fc18e8ef53aedaa4882c5058fb614082331 | refs/heads/master | 2021-01-09T20:32:31.749417 | 2012-12-11T16:00:19 | 2012-12-11T16:00:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,211 | cpp | #include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
class Employee{
char _name[15];
char _lastname[30];
int _empno;
double _salary;
public:
Employee(const char* name="", const char* lastname="", int empno=0, double salary=0.0){
set(name, lastname, empno, salary);
}
void set(const char* name="", const char* lastname="", int empno=0, double salary=0.0){
strcpy(_name, name);
strcpy(_lastname, lastname);
_empno = empno;
_salary = salary;
}
ostream& print(ostream& OS)const{
return OS<<"Name: "<<_name<<" "<<_lastname<<endl<<"EmpNo: "<<_empno
<<", Salary: "<<_salary;
}
virtual ~Employee(){
//print(cout)<<"is dead!!!!"<<endl;
}
};
ostream& operator<<(ostream& OS, const Employee& E){
return E.print(OS);
}
int main(){
Employee E[5]={
Employee("John", "Doe", 1234,12345.67),
Employee("Jack", "Brown", 22345,212345.67),
Employee("Bill", "Red", 3234,32345.67),
Employee("Louis", "Clark", 41234,42345.67),
Employee("Homer", "Simpson", 5234,52345.67)
};
fstream file("emp.bin",ios::out|ios::binary);
for(int i=0;i<5;i++){
file.write((const char*)&E[i], sizeof(Employee));
}
return 0;
} | [
"fardad.soleimanloo@senecacollege.ca"
] | fardad.soleimanloo@senecacollege.ca |
9f8a35eb8d9aa8fb5b47549fa076fb1071f8c7b6 | 777a75e6ed0934c193aece9de4421f8d8db01aac | /src/Providers/UNIXProviders/AssociatedPrivilege/UNIX_AssociatedPrivilege.cpp | e9564eebaab3ecbc083f6ca74658b35ed028ab7c | [
"MIT"
] | permissive | brunolauze/openpegasus-providers-old | 20fc13958016e35dc4d87f93d1999db0eae9010a | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | refs/heads/master | 2021-01-01T20:05:44.559362 | 2014-04-30T17:50:06 | 2014-04-30T17:50:06 | 19,132,738 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,336 | cpp | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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 "UNIX_AssociatedPrivilege.h"
#if defined(PEGASUS_OS_HPUX)
# include "UNIX_AssociatedPrivilege_HPUX.hxx"
# include "UNIX_AssociatedPrivilege_HPUX.hpp"
#elif defined(PEGASUS_OS_LINUX)
# include "UNIX_AssociatedPrivilege_LINUX.hxx"
# include "UNIX_AssociatedPrivilege_LINUX.hpp"
#elif defined(PEGASUS_OS_DARWIN)
# include "UNIX_AssociatedPrivilege_DARWIN.hxx"
# include "UNIX_AssociatedPrivilege_DARWIN.hpp"
#elif defined(PEGASUS_OS_AIX)
# include "UNIX_AssociatedPrivilege_AIX.hxx"
# include "UNIX_AssociatedPrivilege_AIX.hpp"
#elif defined(PEGASUS_OS_FREEBSD)
# include "UNIX_AssociatedPrivilege_FREEBSD.hxx"
# include "UNIX_AssociatedPrivilege_FREEBSD.hpp"
#elif defined(PEGASUS_OS_SOLARIS)
# include "UNIX_AssociatedPrivilege_SOLARIS.hxx"
# include "UNIX_AssociatedPrivilege_SOLARIS.hpp"
#elif defined(PEGASUS_OS_ZOS)
# include "UNIX_AssociatedPrivilege_ZOS.hxx"
# include "UNIX_AssociatedPrivilege_ZOS.hpp"
#elif defined(PEGASUS_OS_VMS)
# include "UNIX_AssociatedPrivilege_VMS.hxx"
# include "UNIX_AssociatedPrivilege_VMS.hpp"
#elif defined(PEGASUS_OS_TRU64)
# include "UNIX_AssociatedPrivilege_TRU64.hxx"
# include "UNIX_AssociatedPrivilege_TRU64.hpp"
#else
# include "UNIX_AssociatedPrivilege_STUB.hxx"
# include "UNIX_AssociatedPrivilege_STUB.hpp"
#endif
Boolean UNIX_AssociatedPrivilege::validateKey(CIMKeyBinding &kb) const
{
/* Keys */
//Subject
//Target
//UseKey
CIMName name = kb.getName();
if (name.equal(PROPERTY_SUBJECT) ||
name.equal(PROPERTY_TARGET) ||
name.equal(PROPERTY_USE_KEY)
)
return true;
return false;
}
void UNIX_AssociatedPrivilege::setScope(CIMName scope)
{
currentScope = scope;
}
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
7a69abd44b5ff01f1293035e69a97afc0f50c705 | 8c3e8be610ee359b81348112eafad82c606dfa54 | /Code/RDGeneral/catch_logs.cpp | 6e1891cc0433ec7856ac8972153d730baacc742f | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | rvianello/rdkit | db67adf0ad6441438516448d89b6846ee8f91b72 | a384878fbe368807cc417cbb5fc492bc89f9ec3f | refs/heads/master | 2023-08-22T15:03:58.579271 | 2023-08-15T02:59:14 | 2023-08-15T02:59:14 | 169,120,054 | 2 | 1 | BSD-3-Clause | 2023-08-19T14:41:18 | 2019-02-04T17:40:31 | HTML | UTF-8 | C++ | false | false | 3,763 | cpp | //
// Copyright (C) 2022 Greg Landrum
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include "catch.hpp"
#include "RDLog.h"
TEST_CASE("LogStateSetter") {
RDLog::RDLoggerList allLogs({rdErrorLog, rdWarningLog, rdInfoLog});
SECTION("disable all") {
for (auto strm : allLogs) {
// explicitly enable the stream so that we know something is happening
std::stringstream ostrm;
strm->df_enabled = true;
strm->SetTee(ostrm);
{
RDLog::LogStateSetter disabler;
BOOST_LOG(strm) << "should be silent" << std::endl;
auto txt = ostrm.str();
CHECK(txt.find("should") == std::string::npos);
}
BOOST_LOG(strm) << "should not be silent" << std::endl;
auto txt = ostrm.str();
CHECK(txt.find("should") != std::string::npos);
strm->ClearTee();
}
}
SECTION("enable one") {
for (auto strm : allLogs) {
strm->df_enabled = true;
RDLog::LogStateSetter disabler;
{
RDLog::LogStateSetter justone(RDLog::RDLoggerList({strm}));
for (auto strm2 : allLogs) {
std::stringstream ostrm;
strm2->SetTee(ostrm);
BOOST_LOG(strm2) << "should not be silent" << std::endl;
auto txt = ostrm.str();
if (strm == strm2) {
CHECK(txt.find("should") != std::string::npos);
} else {
CHECK(txt.find("should") == std::string::npos);
}
strm2->ClearTee();
}
}
// should be disabled again
std::stringstream ostrm;
strm->SetTee(ostrm);
BOOST_LOG(strm) << "should be silent" << std::endl;
auto txt = ostrm.str();
CHECK(txt.find("should") == std::string::npos);
strm->ClearTee();
}
}
}
TEST_CASE("GitHub Issue #5172", "[bug][logging]") {
std::stringstream err_ostrm;
std::stringstream warn_ostrm;
rdErrorLog->df_enabled = true;
rdWarningLog->df_enabled = true;
rdErrorLog->SetTee(err_ostrm);
rdWarningLog->SetTee(warn_ostrm);
{
RDLog::LogStateSetter disabler;
BOOST_LOG(rdErrorLog) << "should be silent" << std::endl;
auto txt = err_ostrm.str();
CHECK(txt.find("should") == std::string::npos);
BOOST_LOG(rdWarningLog) << "should be silent" << std::endl;
txt = warn_ostrm.str();
CHECK(txt.find("should") == std::string::npos);
{
// The second setter overrides the first one:
RDLog::LogStateSetter disabler2({rdWarningLog});
BOOST_LOG(rdErrorLog) << "should be silent" << std::endl;
txt = err_ostrm.str();
CHECK(txt.find("should") == std::string::npos);
BOOST_LOG(rdWarningLog) << "should not be silent" << std::endl;
txt = warn_ostrm.str();
CHECK(txt.find("should") != std::string::npos);
warn_ostrm.clear();
}
}
// Both setters are destroyed, and we revert to initial state
BOOST_LOG(rdErrorLog) << "should not be silent" << std::endl;
auto txt = err_ostrm.str();
CHECK(txt.find("should") != std::string::npos);
BOOST_LOG(rdWarningLog) << "should not be silent" << std::endl;
txt = warn_ostrm.str();
CHECK(txt.find("should") != std::string::npos);
rdErrorLog->ClearTee();
rdWarningLog->ClearTee();
}
TEST_CASE("Tee to file") {
const std::string filename = "error_log.txt";
rdErrorLog->SetTee(filename);
BOOST_LOG(rdErrorLog) << "should not be silent" << std::endl;
std::ifstream istrm(filename);
std::string txt;
CHECK(std::getline(istrm, txt));
CHECK(txt.find("should") != std::string::npos);
}
| [
"noreply@github.com"
] | noreply@github.com |
1a3e0b4309003e4fa8dee234891d4c3a8234d280 | 88d287769d6d4bd4140082857ce1eb7edad5d31f | /leetcode-cpp/530. Minimum Absolute Difference in BST[e].cpp | c45add49884e9c87be55baca0b586c63ed904882 | [] | no_license | xhygh/hello-world | 618fbf4e8aa9bfc8cb8937c552a70e5e6e437753 | ba3eadd3953535dad76e4690fb2fb40305f254f0 | refs/heads/master | 2020-12-06T14:44:44.030545 | 2017-07-11T10:23:21 | 2017-07-11T10:23:21 | 65,993,930 | 2 | 0 | null | 2016-08-19T14:52:50 | 2016-08-18T12:07:48 | Python | UTF-8 | C++ | false | false | 2,871 | cpp | /*
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input:
1
\
3
/
2
Output:
1
Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
tags: binary search tree;532e
*/
/*******************************
solution:
一个二叉搜索树,节点值大于等于0,找到差值绝对值最小的二个节点。
根据BST的定义,最小绝对差值应该存在于大小相邻的两个节点之间,因为中序遍历得出有序节点,
所以按照中序便利树,计算节点间的差值即可。
中序遍历时,先遍历较小的,再遍历较大的,所以差值即root->val - last;
因为是遍历,所以每次只要计算当前root值和上一个遍历的节点的val的差值即可,这样肯定时用比上一个val大的数里最小的相减。
186 / 186 test cases passed.
Status: Accepted
Runtime: 19 ms
42.85%
时间复杂度O(n),空间复杂度O(1)
******************************/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
int res = INT_MAX, last = -1;
inTravel(root, res, last);
return res;
}
void inTravel(TreeNode* root,int& res, int& last){
if (!root) return;//如果节点不存在直接不考虑
if(root->left) inTravel(root->left,res,last);//遍历左子树
if(last>=0) res = min(res, root->val-last);//当前值和上一个节点的值做差,root->val肯定比上一个val大
last = root->val;//更新val
if(root->right) inTravel(root->right, res, last);//遍历右子树
}
};
/*********************上面答案的缩减版,然而时间并未减小***************************/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int res=INT_MAX, last=-1;
public:
int getMinimumDifference(TreeNode* root) {
//不能检查root,否则return无int值报错
//尝试加if(root) 发现!root没有返回也没报错,测试样例中没有root=null的情况
//if (!root) return;//如果节点不存在直接不考虑
if(root->left) getMinimumDifference(root->left);//遍历左子树
if(last>=0) res = min(res, root->val-last);//当前值和上一个节点的值做差,root->val肯定比上一个val大
last = root->val;//更新val
if(root->right) getMinimumDifference(root->right);//遍历右子树
return res;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
af1d14dfdfa01df6f0e15c910ed06700e264c611 | 1305023dc5933375d916d3d0221fa8b5f8526628 | /Practicum/week 13/Examples/Visitor/Rectangle.cpp | a79044b736312c8489687fcd1edaf7a80cbfb458 | [] | no_license | RosinaGeorgieva/ObjectOrientedProgramming2021 | 60720fbd9f5e4d3532c747ff3ec20324c1411ec7 | 5ae0ca4b553e10df1e7a5d6566932c68643402da | refs/heads/main | 2023-05-23T18:18:46.296181 | 2021-06-21T16:44:03 | 2021-06-21T16:44:03 | 341,258,041 | 0 | 0 | null | 2021-02-22T16:08:18 | 2021-02-22T16:08:17 | null | UTF-8 | C++ | false | false | 631 | cpp | #ifndef __RECTANGLE_CPP
#define __RECTANGLE_CPP
#include "Visitor.h"
#include "Rectangle.h"
Rectangle::Rectangle(int x, int y, int width, int height, const char* text) : Shape(x, y, text), mWidth(width), mHeight(height) {
}
Shape* Rectangle::clone() const {
return new Rectangle(*this);
}
void Rectangle::accept(Visitor* visitor) {
visitor->visitRectangle(this);
}
void Rectangle::setWidth(int width) {
this->mWidth = width;
}
void Rectangle::setHeight(int height) {
this->mHeight = height;
}
int Rectangle::getWidth() const {
return this->mWidth;
}
int Rectangle::getHeight() const {
return this->mHeight;
}
#endif | [
"g.shavov@abv.bg"
] | g.shavov@abv.bg |
6f04089dcadeb0fd1cad82c05acea748d6f0816c | 1768e2512411b9aa987aacdbe38a0201c0db404b | /sgd-comm/test_hash.cpp | 6b6cb08511912e357c00ef7cf0d846e0c370c2be | [
"MIT"
] | permissive | a1exwang/dirty-linux-experiments | f424d055cbb177e7b98ff13d8ab0993fb3400172 | fb7f89e32e066e764045ab5a50f96d11d6173afe | refs/heads/master | 2021-06-04T06:21:17.103885 | 2020-08-10T05:09:21 | 2020-08-10T05:09:21 | 150,535,300 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,748 | cpp | #include "cache.hpp"
#include <cassert>
using namespace std;
int main() {
std::vector<std::pair<std::set<int>, std::tuple<int64_t, int64_t, int64_t, int64_t, int64_t>>> table = {
// total_images > total_cached_images
{{}, {90, 8, 1, 2, 100}},
// one replication
{{0}, {0, 2, 1, 2, 4}},
{{1}, {1, 2, 1, 2, 4}},
{{0}, {2, 2, 1, 2, 4}},
{{1}, {3, 2, 1, 2, 4}},
// 2 replications
{{0, 1}, {0, 3, 1, 4, 6}},
{{2, 0}, {1, 3, 1, 4, 6}},
{{1, 2}, {2, 3, 1, 4, 6}},
{{0, 1}, {3, 3, 1, 4, 6}},
{{2, 0}, {4, 3, 1, 4, 6}},
{{1, 2}, {5, 3, 1, 4, 6}},
// 2 replications + 1 * 3 replications
{{0, 1, 2}, {0, 3, 1, 3, 4}},
{{0, 1}, {1, 3, 1, 3, 4}},
{{2, 0}, {2, 3, 1, 3, 4}},
{{1, 2}, {3, 3, 1, 3, 4}},
// 2 replications + 2 * 3 replications
{{0, 1, 2}, {0, 5, 1, 2, 4}},
{{3, 4, 0}, {1, 5, 1, 2, 4}},
{{1, 2}, {2, 5, 1, 2, 4}},
{{3, 4}, {3, 5, 1, 2, 4}},
};
int i = 0;
for (auto test_case : table) {
int64_t image_id, process_per_node, nodes, cached_images_per_process, total_images;
std::tie(image_id, process_per_node, nodes, cached_images_per_process, total_images) = test_case.second;
auto expected = test_case.first;
auto actual = caffe::DefaultDistributionHash(0, image_id, process_per_node, nodes, cached_images_per_process, total_images);
if (expected != actual) {
fprintf(stderr, "asserted failed\n");
fprintf(stderr, "expected: (");
for (auto x : expected) {
fprintf(stderr, "%d, ", x);
}
fprintf(stderr, "), actual: (");
for (auto x : actual) {
fprintf(stderr, "%d, ", x);
}
fprintf(stderr, ")\n");
}
i++;
printf("%d passed\n", i);
}
} | [
"ice_b0und@hotmail.com"
] | ice_b0und@hotmail.com |
b8dd2ac1158de1687206157bfb6450574ea9c11f | 203d7b7e3792acb8e7ccf0ca6feda8dc5b70ce60 | /srcAmiga/modeler/opengl.cpp | 7d2a57b70638cb1b48af8a43d4b87ebb4d708224 | [
"MIT"
] | permissive | Kalamatee/RayStorm | 44e40882b5aff6fbefa3209bf6706cd402868dc3 | 1adb8f50478f795973aa51dcceb02682d671b41d | refs/heads/master | 2020-12-11T03:38:15.490729 | 2019-06-21T15:32:22 | 2019-06-21T15:32:22 | 37,782,719 | 4 | 0 | null | 2015-06-20T19:22:47 | 2015-06-20T19:22:47 | null | UTF-8 | C++ | false | false | 1,850 | cpp | /***************
* PROGRAM: Modeler
* NAME: opengl.cpp
* DESCRIPTION: OpenGL platform specific implementation
* AUTHORS: Andreas Heumann, Mike Hesser
* HISTORY:
* DATE NAME COMMENT
* 02.03.98 ah initial release
***************/
#ifndef OPENGL_H
#include "opengl.h"
#endif
#ifndef OBJECT_H
#include "object.h"
#endif
BOOL OPENGL::CreateContext(ULONG left, ULONG top, ULONG width, ULONG height, BOOL directrender)
{
ULONG bottom;
struct TagItem tags[] =
{
{(long)AMA_Window, (long)_window(win)},
{AMA_Left, _mleft(win)+left},
{AMA_Bottom, (_window(win))->Height-(top+height)-_mtop(win) - 1},
{AMA_Width, width + 1},
{AMA_Height, height + 1},
{AMA_DoubleBuf, TRUE},
{AMA_RGBMode, TRUE},
{AMA_DirectRender, directrender},
{TAG_DONE, NULL},
};
left = _mleft(win)+left;
bottom = (_window(win))->Height-(top+height)-_mtop(win) - 1;
width = width + 1;
height = height + 1;
if(!context || (left != this->left) || (bottom != this->bottom) || (width != this->width) || (height != this->height))
{
this->left = left;
this->bottom = bottom;
this->width = width;
this->height = height;
if(context)
DestroyContext();
context = PPC_STUB(AmigaMesaCreateContext)(tags);
if(!context)
return FALSE;
}
return TRUE;
}
void OPENGL::SwapBuffers()
{
PPC_STUB(AmigaMesaSwapBuffers)(context);
}
void OPENGL::DestroyContext()
{
if(context)
{
PPC_STUB(AmigaMesaDestroyContext)(context);
context = NULL;
}
}
void OPENGL::MakeCurrent()
{
if(context)
PPC_STUB(AmigaMesaMakeCurrent)(context, context->buffer);
}
void OPENGL::Viewport(int left, int top, int width, int height)
{
if(context)
{
MakeCurrent();
PPC_STUB(glViewport)(
left - (this->left - _mleft(win)),
this->height - height,
width, height);
}
}
| [
"andreasheu@gmail.com"
] | andreasheu@gmail.com |
5a2ec1b9006fd071806755c576092e993e2adef4 | fdecb4cfcf13c8113fd741b2976b2daf208a9e26 | /src/scheme_resolver.cpp | b6bf4aa6350d5c81646e47552012696d25ee8148 | [
"MIT"
] | permissive | zionlang/zion | cb1a3a50ff51775e042c89933571fe1d19017f15 | 5b4df370766e342fd4efffff34cd8966990f9ac4 | refs/heads/master | 2023-01-04T21:56:43.501770 | 2023-01-02T17:07:56 | 2023-01-02T22:48:50 | 184,154,262 | 49 | 2 | NOASSERTION | 2020-08-27T04:35:04 | 2019-04-29T22:42:36 | C++ | UTF-8 | C++ | false | false | 2,838 | cpp | #include "scheme_resolver.h"
#include "dbg.h"
#include "tld.h"
#include "unification.h"
#include "user_error.h"
namespace types {
SchemeResolver::SchemeResolver(const SchemeResolver *parent) : parent(parent) {
}
bool SchemeResolver::scheme_exists(std::string name) const {
return (state.count(name) == 1) ||
(parent != nullptr && parent->scheme_exists(name));
}
void SchemeResolver::insert_scheme(std::string name,
const types::SchemeRef &scheme) {
if (state.count(name) != 0) {
debug_above(3,
log("attempt to insert scheme %s for preexisting name %s :: %s",
scheme->str().c_str(), name.c_str(),
state.at(name)->str().c_str()));
assert(scheme_equality(state.at(name), scheme));
}
debug_above(5, log("SchemeResolver::insert_scheme(%s, %s)", name.c_str(),
scheme->str().c_str()));
state[name] = scheme;
}
types::SchemeRef SchemeResolver::lookup_scheme(
const Identifier &id,
std::set<Identifier> &candidates) const {
auto iter = state.find(id.name);
if (iter != state.end()) {
return iter->second;
} else {
std::string upper_name = to_upper(id.name);
for (auto &pair : state) {
/* look for a substring match in another symbol */
std::string regex = "[^.]+\\.?" + regex_sanitize(upper_name);
if (regex_match(to_upper(pair.first), regex)) {
candidates.insert(Identifier{pair.first, pair.second->get_location()});
}
}
if (parent != nullptr) {
return parent->lookup_scheme(id, candidates);
} else {
auto user_error = zion::user_error(
id.location, "symbol " c_id("%s") " is undefined",
zion::tld::strip_prefix(id.name).c_str());
for (auto &id : candidates) {
user_error.add_info(id.location, "did you mean %s?", id.str().c_str());
}
throw user_error;
}
}
}
void SchemeResolver::rebind(const types::Map &bindings) const {
if (parent != nullptr) {
parent->rebind(bindings);
}
types::Scheme::Map new_state;
for (const auto &pair : state) {
const auto &name = pair.first;
const auto &scheme = pair.second;
assert(scheme != nullptr);
if (!set_intersect(scheme->ftvs(), set_keys(bindings)).empty()) {
log("there is an intersection on %s between %s and %s", name.c_str(),
scheme->str().c_str(), ::str(bindings).c_str());
dbg();
}
}
}
std::string SchemeResolver::str() const {
std::stringstream ss;
ss << "{";
const char *delim = "";
for (auto &pair : state) {
ss << delim;
delim = ", ";
ss << pair.first << ": " << pair.second->str();
}
if (parent != nullptr) {
ss << delim << "parent: " << parent->str();
delim = ", ";
}
ss << "}";
return ss.str();
}
} // namespace types
| [
"williambbradley@gmail.com"
] | williambbradley@gmail.com |
e422cf8973762334893f9545cd78bbc035845917 | 1fccc3615b400a119e43ee85d10b739430ee17d4 | /tests/integration/cancel_integration.cpp | bfb37e06d3894af0c45ff23c80fe5ae655436b1d | [] | permissive | yandex/ozo | c34de66e75dc8c11ed211e933149c498966cb272 | abb098aea4b992b6d06391f892e100d829e50188 | refs/heads/master | 2023-03-20T07:40:24.181802 | 2023-03-10T07:33:30 | 2023-03-10T11:40:08 | 106,461,599 | 229 | 48 | PostgreSQL | 2023-03-10T11:40:09 | 2017-10-10T19:24:45 | C++ | UTF-8 | C++ | false | false | 3,074 | cpp | #include <ozo/connection_info.h>
#include <ozo/cancel.h>
#include <ozo/execute.h>
#include <ozo/shortcuts.h>
#include <boost/asio/spawn.hpp>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#define ASSERT_REQUEST_OK(ec, conn)\
ASSERT_FALSE(ec) << ec.message() \
<< "|" << ozo::error_message(conn) \
<< "|" << ozo::get_error_context(conn) << std::endl
namespace {
namespace hana = boost::hana;
using namespace testing;
TEST(cancel, should_cancel_operation) {
using namespace ozo::literals;
using namespace std::chrono_literals;
using namespace hana::literals;
ozo::io_context io;
boost::asio::steady_timer timer(io);
boost::asio::spawn(io, [&io, &timer](auto yield){
const ozo::connection_info conn_info(OZO_PG_TEST_CONNINFO);
ozo::error_code ec;
auto conn = ozo::get_connection(conn_info[io], yield[ec]);
EXPECT_FALSE(ec);
boost::asio::spawn(yield, [&io, &timer, handle = get_cancel_handle(conn)](auto yield) mutable {
timer.expires_after(1s);
ozo::error_code ec;
timer.async_wait(yield[ec]);
if (!ec) {
// Guard is needed since cancel will be served with external
// system executor, so we need to preserve our io_context from
// stop until all the operation processed properly
auto guard = boost::asio::make_work_guard(io);
ozo::cancel(std::move(handle), io, 5s, yield[ec]);
}
});
ozo::execute(conn, "SELECT pg_sleep(1000000)"_SQL, yield[ec]);
EXPECT_EQ(ec, ozo::sqlstate::query_canceled);
});
io.run();
}
TEST(cancel, should_stop_cancel_operation_on_zero_timeout) {
using namespace ozo::literals;
using namespace std::chrono_literals;
using namespace hana::literals;
ozo::io_context io;
ozo::io_context dummy_io;
boost::asio::steady_timer timer(io);
boost::asio::spawn(io, [&io, &timer, &dummy_io](auto yield){
const ozo::connection_info conn_info(OZO_PG_TEST_CONNINFO);
ozo::error_code ec;
auto conn = ozo::get_connection(conn_info[io], yield[ec]);
EXPECT_FALSE(ec);
boost::asio::spawn(yield, [&io, &timer, handle = get_cancel_handle(conn, dummy_io.get_executor())](auto yield) mutable {
timer.expires_after(1s);
ozo::error_code ec;
timer.async_wait(yield[ec]);
if (!ec) {
// Guard is needed since cancel will be served with external
// system executor, so we need to preserve our io_context from
// stop until all the operation processed properly
auto guard = boost::asio::make_work_guard(io);
ozo::cancel(std::move(handle), io, 0s, yield[ec]);
EXPECT_EQ(ec, boost::asio::error::timed_out);
}
});
ozo::execute(conn, "SELECT pg_sleep(1000000)"_SQL, 2s, yield[ec]);
EXPECT_EQ(ec, boost::asio::error::timed_out);
});
io.run();
}
} // namespace
| [
"orionstation@yandex.ru"
] | orionstation@yandex.ru |
3b486eb9bbf895a91e6cde8be00cc5d7510445f4 | a7db885685690fdf9bceaff5e9fc5aa39b293304 | /1176c.cpp | 4b3a44202044e3d474552c112bc4b6f51d6f2764 | [] | no_license | vikas0o7/important_cpp_questions | 825aafdaf5efceff7f599a450c77ef68620396a2 | 557b5299dd6d181505cc6580e9cb948476a94102 | refs/heads/master | 2020-10-02T01:56:15.566418 | 2019-12-12T18:48:51 | 2019-12-12T18:48:51 | 227,674,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 867 | cpp | #include<bits/stdc++.h>
#define io ios_base::sync_with_stdio(false)
#define mp make_pair
#define pb push_back
using namespace std;
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << endl;
err(++it, args...);
}
typedef long long int ll;
typedef vector< int > vi;
typedef vector< vi > vvi;
typedef pair<int,int> ii;
int c[99],r[7];
int main()
{
io;
int n; cin>>n;
int a[n];
for(int i=0;i<n;i++) cin>>a[i];
c[4]=1; c[8]=2; c[15]=3; c[16]=4; c[23]=5;c[42]=6;
for(int i=0;i<n;i++){
int y=c[a[i]];
if(y==1) r[1]++;
if(r[y-1]>0) r[y-1]--,r[y]++;
}
cout<< n- 6* r[6];
return 0;
} | [
"vikasdevil.singh834@gmail.com"
] | vikasdevil.singh834@gmail.com |
f68759451c13ef9ad3a21eda82d68e743b9db2a3 | e5720f95696653b496e5f927eac7492bfb9f132c | /0501-1000/0941-Valid-Mountain-Array/cpp_0941/Solution1.h | 7c4fc14cf2717376ba75537de442daacc62b22fd | [
"MIT"
] | permissive | ooooo-youwillsee/leetcode | 818cca3dd1fd07caf186ab6d41fb8c44f6cc9bdc | 2cabb7e3e2465e33e4c96f0ad363cf6ce6976288 | refs/heads/master | 2022-05-24T15:37:19.652999 | 2022-05-15T01:25:31 | 2022-05-15T01:25:31 | 218,205,693 | 12 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | h | /**
* @author ooooo
* @date 2020/9/30 16:54
*/
#ifndef CPP_0941__SOLUTION1_H_
#define CPP_0941__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool validMountainArray(vector<int> &A) {
if (A.size() < 3) return false;
bool incr = false, decr = false;
for (int i = 1; i < A.size(); ++i) {
if (A[i] == A[i - 1]) return false;
if (A[i] > A[i - 1]) {
if (decr) return false;
incr = true;
} else {
if (!incr) return false;
decr = true;
}
}
return incr && decr;
}
};
#endif //CPP_0941__SOLUTION1_H_
| [
"297872913@qq.com"
] | 297872913@qq.com |
af7b360364d0dedfc625591e5aa8b80a3702bce8 | 5f4b7ca9260a8731419d6e1ca3acc7ed287f0327 | /parse_vpk.h | 01cf5d355d8d48464ea70814d85b82a84f8b44f1 | [] | no_license | Elbagast/tf2_mdl_dirs | a4efa18167da9d04ad4177b2a59c14af69f3403f | 9042f470bdd3551539bb5184142477da3d651f51 | refs/heads/master | 2016-09-06T04:05:04.659897 | 2014-10-28T22:41:39 | 2014-10-28T22:41:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | h | #ifndef PARSE_VPK_H
#define PARSE_VPK_H
/*
PURPOSE
Run "dir\vpk.exe l [file.vpk]" and capture the result for analysis.
Alternatively parse a given dir structure in the same way.
*/
#include <boost/filesystem.hpp> // boost v 1.55.0
std::list<std::wstring> parse_dir(
boost::filesystem::path const& dir
);
std::list<std::wstring> parse_vpk(
boost::filesystem::path const& file,
boost::filesystem::path const& exe
);
#endif | [
"elbagast@gmail.com"
] | elbagast@gmail.com |
21737f2ab887f3eedd8227180bf7243b4f48f5c5 | cbb23371035ec1db7dba1d9c856de79f100695d2 | /automobile/plugins/robot_windows/automobile_window/AbstractWidget.cpp | 545fe94cd0c9f5bb3cdd7e1b0f697df643a692a4 | [] | no_license | mahfuz195/CAVSimulationPlatform | f7c152f472fd5e068992c9faeefad14e44b848b8 | 1b2ab7406131e828da92a0afc3b8127450330284 | refs/heads/master | 2021-07-07T15:12:22.136572 | 2017-10-05T02:09:22 | 2017-10-05T02:09:22 | 105,838,599 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 789 | cpp | #include "AbstractWidget.hpp"
AbstractWidget::AbstractWidget(QWidget *parent):
QWidget(parent)
{
mLayout = new QGridLayout(this);
mEnableCheckBox = new QCheckBox("Disabled", this);
connect(mEnableCheckBox, &QCheckBox::stateChanged, this, &AbstractWidget::updateEnableCheckBoxText);
mLayout->addWidget(mEnableCheckBox, 0, 0);
mValueLabel = new QLabel("", this);
mLayout->addWidget(mValueLabel, 0, 1, Qt::AlignRight);
mGraph = new Graph2D(this);
mGraph->setYRange(0, 0);
mLayout->addWidget(mGraph, 1, 0, 1, 2);
}
AbstractWidget::~AbstractWidget() {
}
void AbstractWidget::updateEnableCheckBoxText() {
if (mEnableCheckBox->isChecked())
mEnableCheckBox->setText("Enabled");
else {
mEnableCheckBox->setText("Disabled");
mValueLabel->setText("");
}
}
| [
"mahfuj.islam28@gmail.com"
] | mahfuj.islam28@gmail.com |
907c8fcf5ab44d5e2fcb23f54ac839d981a982c6 | 1d4c692cf81d201166a14f469b9637b3283f1a0a | /src/d3d/d3d8render.cpp | cf09199a14a8f7a4f2eb468156d20c7946e49b73 | [
"MIT"
] | permissive | madebr/librw | 00af21e7fbee417d1734043ed4f9da3db8589a4b | b1c3c1dca8c5c2244ba7ecfacd50310f27a31b8e | refs/heads/master | 2022-06-20T23:31:07.841909 | 2018-07-04T17:21:34 | 2018-07-04T17:21:34 | 111,781,141 | 3 | 0 | MIT | 2021-07-07T01:41:31 | 2017-11-23T08:07:46 | C++ | UTF-8 | C++ | false | false | 1,842 | cpp | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include "../rwbase.h"
#include "../rwplg.h"
#include "../rwpipeline.h"
#include "../rwobjects.h"
#include "../rwengine.h"
#include "rwd3d.h"
#include "rwd3d8.h"
namespace rw {
namespace d3d8 {
using namespace d3d;
#ifndef RW_D3D9
void defaultRenderCB(Atomic*, InstanceDataHeader*) {}
#else
// This is a bit abandoned, use d3d9 instead
void
defaultRenderCB(Atomic *atomic, InstanceDataHeader *header)
{
RawMatrix world;
d3d::lightingCB(!!(atomic->geometry->flags & Geometry::NORMALS));
Geometry *geo = atomic->geometry;
d3d::setRenderState(D3DRS_LIGHTING, !!(geo->flags & rw::Geometry::LIGHT));
Frame *f = atomic->getFrame();
convMatrix(&world, f->getLTM());
d3ddevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&world);
InstanceData *inst = header->inst;
for(uint32 i = 0; i < header->numMeshes; i++){
d3d::setTexture(0, inst->material->texture);
d3d::setMaterial(inst->material->surfaceProps, inst->material->color);
d3d::setRenderState(D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL);
d3d::setRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL);
if(geo->flags & Geometry::PRELIT)
d3d::setRenderState(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_COLOR1);
else
d3d::setRenderState(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL);
d3ddevice->SetFVF(inst->vertexShader);
d3ddevice->SetStreamSource(0, (IDirect3DVertexBuffer9*)inst->vertexBuffer, 0, inst->stride);
d3ddevice->SetIndices((IDirect3DIndexBuffer9*)inst->indexBuffer);
uint32 numPrim = inst->primType == D3DPT_TRIANGLESTRIP ? inst->numIndices-2 : inst->numIndices/3;
d3d::flushCache();
d3ddevice->DrawIndexedPrimitive((D3DPRIMITIVETYPE)inst->primType, inst->baseIndex,
0, inst->numVertices, 0, numPrim);
inst++;
}
}
#endif
}
}
| [
"aap@papnet.eu"
] | aap@papnet.eu |
64bf3625f4b2679bac53ecf9a0b3c9d93148e225 | a977211952cdbee0cf246ba86e02735b6d4d7174 | /nyx/Nyx.hpp | 431f2bbcc02be19816e6a17beae5b53169d4c9ae | [
"MIT"
] | permissive | SpecialYang/nyx | b2eebaef850def60dc865633dd00dd2a17966a3c | 81c01aefd851926697d1f00dee089f42e501024c | refs/heads/master | 2020-08-12T17:27:28.823890 | 2019-01-07T08:46:28 | 2019-01-07T08:46:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,741 | hpp | #pragma once
#include <any>
#include <deque>
#include <string>
#include <unordered_map>
#include <vector>
struct Statement;
struct Expression;
namespace nyx {
struct Context;
enum ValueType { Int, Double, String, Bool, Char, Null, Array, Closure };
enum ExecutionResultType { ExecNormal, ExecReturn, ExecBreak, ExecContinue };
struct Block {
explicit Block() = default;
std::vector<Statement*> stmts;
};
struct Function {
explicit Function() = default;
std::string name;
std::deque<Context*>* outerContext{};
std::vector<std::string> params;
Block* block{};
};
struct Value {
explicit Value() {}
explicit Value(nyx::ValueType type) : type(type) {}
explicit Value(nyx::ValueType type, std::any data)
: type(type), data(std::move(data)) {}
template <int _NyxType>
inline bool isType() const;
template <typename _CastingType>
inline _CastingType cast();
template <typename _CastingType>
inline _CastingType cast() const;
template <typename _DataType>
inline void set(_DataType data);
Value operator+(const Value& rhs) const;
Value operator-(const Value& rhs) const;
Value operator*(const Value& rhs) const;
Value operator/(const Value& rhs) const;
Value operator%(const Value& rhs) const;
Value operator&&(const Value& rhs) const;
Value operator||(const Value& rhs) const;
Value operator==(const Value& rhs) const;
Value operator!=(const Value& rhs) const;
Value operator>(const Value& rhs) const;
Value operator>=(const Value& rhs) const;
Value operator<(const Value& rhs) const;
Value operator<=(const Value& rhs) const;
Value operator&(const Value& rhs) const;
Value operator|(const Value& rhs) const;
nyx::ValueType type{};
std::any data;
};
struct ExecResult {
explicit ExecResult(ExecutionResultType execType) : execType(execType) {}
explicit ExecResult(ExecutionResultType execType, Value retValue)
: execType(execType), retValue(retValue) {}
ExecutionResultType execType;
Value retValue;
};
struct Variable {
explicit Variable() = default;
std::string name;
Value value;
};
class Context {
public:
explicit Context() = default;
virtual ~Context();
bool hasVariable(const std::string& identName);
void createVariable(const std::string& identName, const Value& value);
Variable* getVariable(const std::string& identName);
void addFunction(const std::string& name, Function* f);
bool hasFunction(const std::string& name);
Function* getFunction(const std::string& name);
private:
std::unordered_map<std::string, Variable*> vars;
std::unordered_map<std::string, Function*> funcs;
};
class Runtime : public Context {
using BuiltinFuncType = Value (*)(Runtime*, std::deque<Context*>*,
std::vector<Value>);
public:
explicit Runtime();
bool hasBuiltinFunction(const std::string& name);
BuiltinFuncType getBuiltinFunction(const std::string& name);
void addStatement(Statement* stmt);
std::vector<Statement*>& getStatements();
private:
std::unordered_map<std::string, BuiltinFuncType> builtin;
std::vector<Statement*> stmts;
};
template <int _NyxType>
inline bool Value::isType() const {
return this->type == _NyxType;
}
template <typename _CastingType>
inline _CastingType Value::cast() {
return std::any_cast<_CastingType>(data);
}
template <typename _CastingType>
inline _CastingType Value::cast() const {
return std::any_cast<_CastingType>(data);
}
template <typename _DataType>
inline void Value::set(_DataType data) {
this->data = std::make_any<_DataType>(std::move(data));
}
} // namespace nyx
| [
"1948638989@qq.com"
] | 1948638989@qq.com |
e2fcda8ce95c4f7e15e981aeea8eb0c2c88816fe | 9ff69f2638fe679b9fbb3ac682d356b59c50b068 | /code archive/bigint.h | efe677ab62e22ced0e177b2b362a7e2e9b4d1981 | [
"MIT"
] | permissive | brianbbsu/program | 7f7c3d4aacea32ada7f74cf5caffa9931be280c4 | c4505f2b8c0b91010e157db914a63c49638516bc | refs/heads/master | 2021-05-23T04:53:49.618057 | 2020-04-18T15:21:10 | 2020-04-18T15:21:10 | 81,056,684 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,516 | h | #ifndef BIGINT
#define BIGINT
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <iomanip>
class bigint{
typedef long long ll;
private:
const ll base=1000000,ln=6;
std::vector<ll> d;
bool neg;
public:
bigint():neg(0){};
bigint(ll di);
bigint(std::string di);
~bigint();
bool s()const{
return neg;
}
bool &sref(){
return neg;
}
int size()const{
return (int)d.size();
}
void shrink()
{
while(d.size()&&!d.back())d.pop_back();
}
void resize(int sz)
{
d.resize(sz,0);
}
bigint &operator = (const bigint &_d)
{
d=_d.d;
neg=_d.s();
return (*this);
}
friend std::ostream &operator << (std::ostream&,const bigint&);
friend std::istream &operator >> (std::istream&,const bigint&);
ll &operator [](size_t t)
{
if(d.size()<=t)d.resize(t+1,0);
return d[t];
}
ll get(size_t t)const
{
if(d.size()<=t)return 0;
else return d[t];
}
void adj(int l,int r)
{
bigint &a=(*this);
for(int i=l;i<r;i++)
{
if(a[i]<0||a[i]>=base)
{
a[i+1]+=a[i]/base;
a[i]%=base;
if(a[i]<0)a[i+1]--,a[i]+=base;
}
}
}
int cmp(const bigint &b)const
{
const bigint &a=(*this);
int fg;
if(a.s()^b.s())return (a.s()?-1:1);
else fg=(a.s()?-1:1);
if(a.size()!=b.size())return (a.size()>b.size()?fg:-fg);
for(int i=a.size()-1;i>=0;i--)
{
if(a.get(i)==b.get(i))continue;
else if(a.get(i)>b.get(i))return fg;
else return -fg;
}
return 0;
}
bool operator < (const bigint &b)const{
return cmp(b)<0;
}
bool operator > (const bigint &b)const{
return cmp(b)>0;
}
bool operator == (const bigint &b)const{
return cmp(b)==0;
}
bool operator <= (const bigint &b)const{
return cmp(b)<=0;
}
bool operator >= (const bigint &b)const{
return cmp(b)>=0;
}
bigint operator + (const bigint &b)const;
bigint operator - (const bigint &b)const;
bigint operator - ()const;
bigint operator * (const bigint &b)const;
bigint operator / (const bigint &b)const;
bigint operator % (const bigint &b)const
{
return (*this)-((*this)/b)*b;
}
bigint operator += (const bigint &b)
{
return (*this)=(*this)+b;
}
bigint operator -= (const bigint &b)
{
return (*this)=(*this)-b;
}
bigint operator *= (const bigint &b)
{
return (*this)=(*this)*b;
}
bigint operator /= (const bigint &b)
{
return (*this)=(*this)/b;
}
bigint operator %= (const bigint &b)
{
return (*this)=(*this)%b;
}
};
bigint::bigint(ll di)
{
if(di<0)neg=1,di=-di;
else neg=0;
while(di>0)
{
d.push_back(di%base);
di/=base;
}
}
bigint::bigint(std::string di)
{
if(di[0]=='-')neg=1,di=di.substr(1);
else neg=0;
std::reverse(di.begin(),di.end());
ll tmp=0,bs=1;
for(char c:di)
{
tmp=tmp+bs*(c-'0');
bs*=10;
if(bs>=base)
{
d.push_back(tmp);
tmp=0;bs=1;
}
}
if(tmp)d.push_back(tmp);
this->shrink();
}
bigint::~bigint()
{
d.clear();
d.shrink_to_fit();
}
std::ostream &operator << (std::ostream &_ss,const bigint &d)
{
if(!d.size())
{
_ss<<"0";
return _ss;
}
if(d.s())_ss<<"-";
_ss<<d.d.back();
for(int i=d.size()-2;i>=0;i--)_ss<<std::setw(d.ln)<<std::setfill('0')<<d.d[i];
return _ss;
}
std::istream &operator >> (std::istream &_ss,bigint &d)
{
std::string s;
_ss>>s;
d=bigint(s);
return _ss;
}
bigint bigint::operator + (const bigint &b)const{
const bigint &a=(*this);
if(a.s())return b-(-a);
if(b.s())return a-(-b);
bigint rt;
ll t=std::max(a.size(),b.size());
rt.resize(t+1);
for(int i=0;i<t;i++)rt[i]=a.get(i)+b.get(i);
rt.adj(0,t);
rt.shrink();
return rt;
};
bigint bigint::operator - (const bigint &b)const{
const bigint &a=(*this);
if(b.s())return a+(-b);
if(a.s())return -((-a)+b);
if(a<b)return -(b-a);
bigint rt;
ll t=std::max(a.size(),b.size());
rt.resize(t+1);
for(int i=0;i<t;i++)rt[i]=a.get(i)-b.get(i);
rt.adj(0,t);
rt.shrink();
return rt;
};
bigint bigint::operator - ()const{
bigint rt=(*this);
rt.sref()=!rt.s();
return rt;
}
bigint bigint::operator * (const bigint &b)const{
const bigint &a=(*this);
bigint rt;
ll t=a.size()+b.size();
rt.resize(t+1);
rt.sref()=a.s()^b.s();
for(int i=0;i<a.size();i++)
for(int j=0;j<b.size();j++)rt[i+j]+=a.get(i)*b.get(j);
rt.adj(0,t);
rt.shrink();
return rt;
};
bigint bigint::operator / (const bigint &b)const{
const bigint &a=(*this);
bigint rt;
int t=std::max(a.size()-b.size()+1,0);
rt.resize(t);
rt.sref()=a.s()^b.s();
if(!b.size())return bigint();
else if(b.size()==1)
{
ll tmp=0,dv=b.get(0);
for(int i=a.size()-1;i>=0;i--)
{
tmp=tmp*base+a.get(i);
rt[i]=tmp/dv;
tmp%=dv;
}
rt.shrink();
return rt;
}
bigint a2=a;
ll tmpb=b.get(b.size()-1)*base+b.get(b.size()-2);
for(int i=t-1;i>=0;i--)
{
ll tmpa=a2.get(i+b.size())*base*base+a2.get(i+b.size()-1)*base+a2.get(i+b.size()-2);
rt[i]=std::max(tmpa/tmpb-1,0LL);
for(int j=b.size()-1;j>=0;j--)a2[i+j]-=rt[i]*b.get(j);
a2.adj(i,i+b.size());
bool ok=1;
for(int j=b.size();j>=0;j--)
{
if(a2.get(i+j)==b.get(j))continue;
else if(a2.get(i+j)>b.get(j))ok=1;
else ok=0;
break;
}
if(ok)
{
rt[i]++;
for(int j=b.size()-1;j>=0;j--)a2[i+j]-=b.get(j);
a2.adj(i,i+b.size());
}
}
rt.adj(0,t);
rt.shrink();
return rt;
};
#endif
| [
"brianbb.su@gmail.com"
] | brianbb.su@gmail.com |
8b2b88a8a78d597b4c78a22c2d04b4df6972d51e | 99e85aedc7899806a9a98a8f1f1a9c131e67b0da | /204/Lab06/publication.cpp | 4b97c509cdfe5b269064b517b37c9dfd88c4d3ab | [] | no_license | LexiMuMu/cpp | 41fb95a8a17b50a758ebe9fc51d965c26ad2b83e | 84d36e8b4606c4210f4a6399180852d8d2f5eb03 | refs/heads/master | 2021-01-11T05:40:40.819541 | 2016-10-21T13:36:17 | 2016-10-21T13:36:17 | 71,566,106 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,599 | cpp | /********************************************************************************
* Filename: publication.cpp
* Name & Student No.: Yanhong Ben, 4845675
* Lab No: 6
* File Description: implementation file of publication
* Date Last Modified: 06/09/2015
*********************************************************************************/
#include <iostream>
#include <string>
using namespace std;
#include "publication.h"
Publication::Publication(string tit, int pYear, string publ)
{
title = tit;
publishYear = pYear;
publisher = publ;
}
void Publication::print(ostream& out)
{
out << "Title: " << title << endl;
out << "Published in " << publishYear << endl;
out << "Publisher: " << publisher << endl;
}
Book::Book(string tit, int pYear, string publ, string newISBN, string auth[3])
: Publication(tit, pYear, publ)
{
NoOfISBN = newISBN;
for (int i = 0; i < 3; i++)
authors[i] = auth[i];
}
void Book::print(ostream& out)
{
Publication::print(out);
out << "ISBN: " << NoOfISBN << endl;
out << "Authors: ";
for (int i=0; i<3; i++)
out << authors[i] << " ";
out << endl;
}
Journal::Journal(string tit, int pYear, string publ, string newISSN, string chieE, int vol)
: Publication(tit, pYear, publ)
{
NoOfISSN = newISSN;
chiefEditor = chieE;
volume = vol;
}
void Journal::print(ostream& out)
{
Publication::print(out);
out << "ISSN: " << NoOfISSN << endl;
out << "Editor in Chief: " << chiefEditor << endl;
out << "Volume: " << volume << endl;
}
| [
"mulan@Lexi.local"
] | mulan@Lexi.local |
21f476e8bc3604ec0831d23c60e19ad005b52fe9 | 1f24d714981216b782299f0ad965d43b5ee06f2c | /project_euler_cpp/project_euler_cpp/pb024.cpp | 2c115657a7f9ca09b4a1273e3c87baf5dec9234f | [] | no_license | alexmaraval/projecteuler | 096b6508648c13e5b1f993678bddbd7707825a18 | 9476efeeb3bb4cd06c7358510b0490da863ae3c6 | refs/heads/master | 2021-09-10T13:13:41.482868 | 2018-03-26T21:25:37 | 2018-03-26T21:25:37 | 103,399,389 | 0 | 0 | null | 2017-12-18T18:46:59 | 2017-09-13T12:52:31 | C++ | UTF-8 | C++ | false | false | 334 | cpp | //
// pb024.cpp
// project_euler_cpp
//
// Created by Alexandre Maraval on 14.12.17.
// Copyright © 2017 Alexandre Maraval. All rights reserved.
//
#include "pb024.hpp"
void pb024()
{
std::cout << "The 1'000'000th permutation in the lexicographic order of the digits {0,1,2,3,4,5,6,7,8,9} is '2783915460'." << std::endl;
}
| [
"maraval.alexandre@gmail.com"
] | maraval.alexandre@gmail.com |
495f0342df49bd76fecc3d3a6f4e0c70714c5762 | d2d4347bf574b525d42e41bd9ec6f25c3e9cca6a | /list/list.hpp | e59457911147b1329839f0c0b59bea59e2928ac6 | [] | no_license | Vonrisen/cpp-linked-list-implementation | 70f0516e6275d61557885c234e118521a5f60184 | bdb3bb081828123ef791c088022e82201d1fc421 | refs/heads/main | 2023-04-22T16:11:38.803483 | 2021-05-08T10:44:21 | 2021-05-08T10:44:21 | 365,487,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,879 | hpp |
#ifndef LIST_HPP
#define LIST_HPP
/* ************************************************************************** */
#include "../container/container.hpp"
/* ************************************************************************** */
namespace vlnk {
/* ************************************************************************** */
template <typename Data>
class List: virtual public LinearContainer<Data>,
virtual public MappableContainer<Data>,
virtual public FoldableContainer<Data> {
protected:
using LinearContainer<Data>::size;
struct Node
{
// Data
Data value;
Node* nextptr = nullptr;
Node() = default;
// Specific constructors
Node(const Data&);
// Copy constructor
Node(const Node&);
// Move constructor
Node(Node&&) noexcept;
// Destructor
virtual ~Node() = default;
};
Node* head = nullptr;
Node* tail = nullptr;
public:
// Default constructor
List() = default;
// Specific constructor
List(const LinearContainer<Data>&);
/* ************************************************************************ */
// Copy constructor
List(const List&);
// Move constructor
List(List&&) noexcept;
/* ************************************************************************ */
// Destructor
virtual ~List();
/* ************************************************************************ */
// Copy assignment
List& operator=(const List&);
// Move assignment
List& operator=(List&&) noexcept;
/* ************************************************************************ */
// Comparison operators
bool operator==(const List&) const noexcept;
inline bool operator!=(const List&) const noexcept;
/* ************************************************************************ */
// Specific member functions
void InsertAtFront(const Data&);
void InsertAtFront(Data&&) noexcept;
void InsertAtBack(const Data&);
void InsertAtBack(Data&&) noexcept;
void RemoveFromFront();
Data FrontNRemove();
/* ************************************************************************ */
// Specific member functions (inherited from Container)
void Clear() override;
// Specific member functions (inherited from LinearContainer)
Data& Front() const override;
Data& Back() const override;
Data& operator[](const ulong) const override;
/* ************************************************************************ */
// Specific member functions (inherited from MappableContainer)
using typename MappableContainer<Data>::MapFunctor;
void MapPreOrder(const MapFunctor, void*) override;
void MapPostOrder(const MapFunctor, void*) override;
/* ************************************************************************ */
// Specific member functions (inherited from FoldableContainer)
using typename FoldableContainer<Data>::FoldFunctor;
void FoldPreOrder(const FoldFunctor, const void*, void*) const override;
void FoldPostOrder(const FoldFunctor, const void*, void*) const override;
protected:
// Auxiliary member functions (for MappableContainer) (Recursive use)
// type MapPreOrder(arguments) specifiers; // Accessory function executing from one point of the list onwards
// type MapPostOrder(arguments) specifiers; // Accessory function executing from one point of the list onwards
/* ************************************************************************ */
// Auxiliary member functions (for FoldableContainer) (Recursive use)
// type FoldPreOrder(arguments) specifiers; // Accessory function executing from one point of the list onwards
// type FoldPostOrder(arguments) specifiers; // Accessory function executing from one point of the list onwards
};
/* ************************************************************************** */
}
#include "list.cpp"
#endif
| [
"noreply@github.com"
] | noreply@github.com |
486fa8eefaaff7bb54ddcf07d4c0877655dd3df1 | 21ea26bdef186ad666f4692322d3560404c281bf | /DX12Stats.cpp | 7e6fe19c8044ce388e65f266be33418aeae9c7d6 | [
"MIT"
] | permissive | RedPandaProjects/BearDirectx | dee2f2748b51b589f20c3712d7ebe0fc21c6dc5c | 1fdeaeea37d7669361972f6a59d9a1ddc7c29429 | refs/heads/master | 2023-01-22T08:40:53.636966 | 2020-11-27T17:27:53 | 2020-11-27T17:27:53 | 164,384,251 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 855 | cpp | #include "DX12PCH.h"
#define RENDER_BEGIN_CLASS_REGISTRATION1(Name,...) extern bsize Name ## Counter;
#define RENDER_BEGIN_CLASS_REGISTRATION2(Name,Parent,...) RENDER_BEGIN_CLASS_REGISTRATION1(Name)
#define RENDER_BEGIN_CLASS_REGISTRATION1_WITHOUT_FACTORY(Name,...)
#define RENDER_BEGIN_CLASS_REGISTRATION2_WITHOUT_FACTORY(Name,Parent,...)
#include "..\BearGraphics\BearTemplate\BearGraphicsObjectsList.h"
#define RENDER_BEGIN_CLASS_REGISTRATION1(Name,...) bsize DX12Stats::Count ## Name(){return Name ## Counter;}
#define RENDER_BEGIN_CLASS_REGISTRATION2(Name,Parent,...) RENDER_BEGIN_CLASS_REGISTRATION1(Name)
#define RENDER_BEGIN_CLASS_REGISTRATION1_WITHOUT_FACTORY(Name,...)
#define RENDER_BEGIN_CLASS_REGISTRATION2_WITHOUT_FACTORY(Name,Parent,...)
#include "..\BearGraphics\BearTemplate\BearGraphicsObjectsList.h"
DX12Stats::~DX12Stats()
{
}
| [
"i-sobolevskiy@mail.ru"
] | i-sobolevskiy@mail.ru |
04a8eeb7d52b8688aba26e73728e32efd11dfd53 | 70c2645aab2d095e71ad7b891361566cfe0cb6da | /VulnDB/FileSamples/firefox/CVE-2018-5187/CVE-2018-5187_CWE-119_1395246_bugzilla0_DataChannel.cpp_4.0_OLD.cpp | 570396faf8353ecfa4bcf537c0067966f08d09f8 | [] | no_license | Raymiii/SCVDT | ee43c39720780e52d3de252c211fa5a7b4bd6dc2 | 0a30f2e59f45168407cb520e16479d53d7a8845b | refs/heads/main | 2023-05-30T20:00:52.723562 | 2021-06-21T05:24:20 | 2021-06-21T05:24:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 109,430 | cpp | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#if !defined(__Userspace_os_Windows)
#include <arpa/inet.h>
#endif
// usrsctp.h expects to have errno definitions prior to its inclusion.
#include <errno.h>
#define SCTP_DEBUG 1
#define SCTP_STDINT_INCLUDE <stdint.h>
#ifdef _MSC_VER
// Disable "warning C4200: nonstandard extension used : zero-sized array in
// struct/union"
// ...which the third-party file usrsctp.h runs afoul of.
#pragma warning(push)
#pragma warning(disable:4200)
#endif
#include "usrsctp.h"
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "DataChannelLog.h"
#include "nsServiceManagerUtils.h"
#include "nsIObserverService.h"
#include "nsIObserver.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "mozilla/Services.h"
#include "mozilla/Sprintf.h"
#include "nsProxyRelease.h"
#include "nsThread.h"
#include "nsThreadUtils.h"
#include "nsAutoPtr.h"
#include "nsNetUtil.h"
#include "nsNetCID.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/StaticMutex.h"
#include "mozilla/Unused.h"
#ifdef MOZ_PEERCONNECTION
#include "mtransport/runnable_utils.h"
#endif
#define DATACHANNEL_LOG(args) LOG(args)
#include "DataChannel.h"
#include "DataChannelProtocol.h"
// Let us turn on and off important assertions in non-debug builds
#ifdef DEBUG
#define ASSERT_WEBRTC(x) MOZ_ASSERT((x))
#elif defined(MOZ_WEBRTC_ASSERT_ALWAYS)
#define ASSERT_WEBRTC(x) do { if (!(x)) { MOZ_CRASH(); } } while (0)
#endif
static bool sctp_initialized;
namespace mozilla {
LazyLogModule gDataChannelLog("DataChannel");
static LazyLogModule gSCTPLog("SCTP");
#define SCTP_LOG(args) MOZ_LOG(mozilla::gSCTPLog, mozilla::LogLevel::Debug, args)
class DataChannelConnectionShutdown : public nsITimerCallback
{
public:
explicit DataChannelConnectionShutdown(DataChannelConnection* aConnection)
: mConnection(aConnection)
{
mTimer = NS_NewTimer(); // we'll crash if this fails
mTimer->InitWithCallback(this, 30*1000, nsITimer::TYPE_ONE_SHOT);
}
NS_IMETHODIMP Notify(nsITimer* aTimer) override;
NS_DECL_THREADSAFE_ISUPPORTS
private:
virtual ~DataChannelConnectionShutdown()
{
mTimer->Cancel();
}
RefPtr<DataChannelConnection> mConnection;
nsCOMPtr<nsITimer> mTimer;
};
class DataChannelShutdown;
StaticRefPtr<DataChannelShutdown> sDataChannelShutdown;
class DataChannelShutdown : public nsIObserver
{
public:
// This needs to be tied to some object that is guaranteed to be
// around (singleton likely) unless we want to shutdown sctp whenever
// we're not using it (and in which case we'd keep a refcnt'd object
// ref'd by each DataChannelConnection to release the SCTP usrlib via
// sctp_finish). Right now, the single instance of this class is
// owned by the observer service and a StaticRefPtr.
NS_DECL_ISUPPORTS
DataChannelShutdown() = default;
void Init()
{
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (!observerService)
return;
nsresult rv = observerService->AddObserver(this,
"xpcom-will-shutdown",
false);
MOZ_ASSERT(rv == NS_OK);
(void) rv;
}
NS_IMETHOD Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) override
{
// Note: MainThread
if (strcmp(aTopic, "xpcom-will-shutdown") == 0) {
LOG(("Shutting down SCTP"));
if (sctp_initialized) {
usrsctp_finish();
sctp_initialized = false;
}
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (!observerService)
return NS_ERROR_FAILURE;
nsresult rv = observerService->RemoveObserver(this,
"xpcom-will-shutdown");
MOZ_ASSERT(rv == NS_OK);
(void) rv;
{
StaticMutexAutoLock lock(sLock);
sConnections = nullptr; // clears as well
}
sDataChannelShutdown = nullptr;
}
return NS_OK;
}
void CreateConnectionShutdown(DataChannelConnection* aConnection)
{
StaticMutexAutoLock lock(sLock);
if (!sConnections) {
sConnections = new nsTArray<RefPtr<DataChannelConnectionShutdown>>();
}
sConnections->AppendElement(new DataChannelConnectionShutdown(aConnection));
}
void RemoveConnectionShutdown(DataChannelConnectionShutdown* aConnectionShutdown)
{
StaticMutexAutoLock lock(sLock);
if (sConnections) {
sConnections->RemoveElement(aConnectionShutdown);
}
}
private:
// The only instance of DataChannelShutdown is owned by the observer
// service, so there is no need to call RemoveObserver here.
virtual ~DataChannelShutdown() = default;
// protects sConnections
static StaticMutex sLock;
static StaticAutoPtr<nsTArray<RefPtr<DataChannelConnectionShutdown>>> sConnections;
};
StaticMutex DataChannelShutdown::sLock;
StaticAutoPtr<nsTArray<RefPtr<DataChannelConnectionShutdown>>> DataChannelShutdown::sConnections;
NS_IMPL_ISUPPORTS(DataChannelShutdown, nsIObserver);
NS_IMPL_ISUPPORTS(DataChannelConnectionShutdown, nsITimerCallback)
NS_IMETHODIMP
DataChannelConnectionShutdown::Notify(nsITimer* aTimer)
{
// safely release reference to ourself
RefPtr<DataChannelConnectionShutdown> grip(this);
// Might not be set. We don't actually use the |this| pointer in
// RemoveConnectionShutdown right now, which makes this a bit gratuitous
// anyway...
if (sDataChannelShutdown) {
sDataChannelShutdown->RemoveConnectionShutdown(this);
}
return NS_OK;
}
OutgoingMsg::OutgoingMsg(struct sctp_sendv_spa &info, const uint8_t *data,
size_t length)
: mLength(length)
, mData(data)
{
mInfo = &info;
mPos = 0;
}
void OutgoingMsg::Advance(size_t offset)
{
mPos += offset;
if (mPos > mLength) {
mPos = mLength;
}
}
BufferedOutgoingMsg::BufferedOutgoingMsg(OutgoingMsg &msg)
{
size_t length = msg.GetLeft();
auto *tmp = new uint8_t[length]; // infallible malloc!
memcpy(tmp, msg.GetData(), length);
mLength = length;
mData = tmp;
mInfo = new sctp_sendv_spa;
*mInfo = msg.GetInfo();
mPos = 0;
}
BufferedOutgoingMsg::~BufferedOutgoingMsg()
{
delete mInfo;
delete mData;
}
static int
receive_cb(struct socket* sock, union sctp_sockstore addr,
void *data, size_t datalen,
struct sctp_rcvinfo rcv, int flags, void *ulp_info)
{
DataChannelConnection *connection = static_cast<DataChannelConnection*>(ulp_info);
return connection->ReceiveCallback(sock, data, datalen, rcv, flags);
}
static
DataChannelConnection *
GetConnectionFromSocket(struct socket* sock)
{
struct sockaddr *addrs = nullptr;
int naddrs = usrsctp_getladdrs(sock, 0, &addrs);
if (naddrs <= 0 || addrs[0].sa_family != AF_CONN) {
return nullptr;
}
// usrsctp_getladdrs() returns the addresses bound to this socket, which
// contains the SctpDataMediaChannel* as sconn_addr. Read the pointer,
// then free the list of addresses once we have the pointer. We only open
// AF_CONN sockets, and they should all have the sconn_addr set to the
// pointer that created them, so [0] is as good as any other.
struct sockaddr_conn *sconn = reinterpret_cast<struct sockaddr_conn *>(&addrs[0]);
DataChannelConnection *connection =
reinterpret_cast<DataChannelConnection *>(sconn->sconn_addr);
usrsctp_freeladdrs(addrs);
return connection;
}
// called when the buffer empties to the threshold value
static int
threshold_event(struct socket* sock, uint32_t sb_free)
{
DataChannelConnection *connection = GetConnectionFromSocket(sock);
if (connection) {
connection->SendDeferredMessages();
} else {
LOG(("Can't find connection for socket %p", sock));
}
return 0;
}
static void
debug_printf(const char *format, ...)
{
va_list ap;
char buffer[1024];
if (MOZ_LOG_TEST(gSCTPLog, LogLevel::Debug)) {
va_start(ap, format);
#ifdef _WIN32
if (vsnprintf_s(buffer, sizeof(buffer), _TRUNCATE, format, ap) > 0) {
#else
if (VsprintfLiteral(buffer, format, ap) > 0) {
#endif
SCTP_LOG(("%s", buffer));
}
va_end(ap);
}
}
DataChannelConnection::DataChannelConnection(DataConnectionListener *listener,
nsIEventTarget *aTarget)
: NeckoTargetHolder(aTarget)
, mLock("netwerk::sctp::DataChannelConnection")
{
mCurrentStream = 0;
mState = CLOSED;
mSocket = nullptr;
mMasterSocket = nullptr;
mListener = listener;
mLocalPort = 0;
mRemotePort = 0;
mPendingType = PENDING_NONE;
LOG(("Constructor DataChannelConnection=%p, listener=%p", this, mListener.get()));
mInternalIOThread = nullptr;
}
DataChannelConnection::~DataChannelConnection()
{
LOG(("Deleting DataChannelConnection %p", (void *) this));
// This may die on the MainThread, or on the STS thread
ASSERT_WEBRTC(mState == CLOSED);
MOZ_ASSERT(!mMasterSocket);
MOZ_ASSERT(mPending.GetSize() == 0);
MOZ_ASSERT(!mTransportFlow);
// Already disconnected from sigslot/mTransportFlow
// TransportFlows must be released from the STS thread
if (!IsSTSThread()) {
ASSERT_WEBRTC(NS_IsMainThread());
if (mInternalIOThread) {
// Avoid spinning the event thread from here (which if we're mainthread
// is in the event loop already)
nsCOMPtr<nsIRunnable> r = WrapRunnable(nsCOMPtr<nsIThread>(mInternalIOThread),
&nsIThread::Shutdown);
Dispatch(r.forget());
}
} else {
// on STS, safe to call shutdown
if (mInternalIOThread) {
mInternalIOThread->Shutdown();
}
}
}
void
DataChannelConnection::Destroy()
{
// Though it's probably ok to do this and close the sockets;
// if we really want it to do true clean shutdowns it can
// create a dependant Internal object that would remain around
// until the network shut down the association or timed out.
LOG(("Destroying DataChannelConnection %p", (void *) this));
ASSERT_WEBRTC(NS_IsMainThread());
CloseAll();
MutexAutoLock lock(mLock);
// If we had a pending reset, we aren't waiting for it - clear the list so
// we can deregister this DataChannelConnection without leaking.
ClearResets();
MOZ_ASSERT(mSTS);
ASSERT_WEBRTC(NS_IsMainThread());
// Finish Destroy on STS thread to avoid bug 876167 - once that's fixed,
// the usrsctp_close() calls can move back here (and just proxy the
// disconnect_all())
RUN_ON_THREAD(mSTS, WrapRunnable(RefPtr<DataChannelConnection>(this),
&DataChannelConnection::DestroyOnSTS,
mSocket, mMasterSocket),
NS_DISPATCH_NORMAL);
// These will be released on STS
mSocket = nullptr;
mMasterSocket = nullptr; // also a flag that we've Destroyed this connection
// We can't get any more new callbacks from the SCTP library
// All existing callbacks have refs to DataChannelConnection
// nsDOMDataChannel objects have refs to DataChannels that have refs to us
}
void DataChannelConnection::DestroyOnSTS(struct socket *aMasterSocket,
struct socket *aSocket)
{
if (aSocket && aSocket != aMasterSocket)
usrsctp_close(aSocket);
if (aMasterSocket)
usrsctp_close(aMasterSocket);
usrsctp_deregister_address(static_cast<void *>(this));
LOG(("Deregistered %p from the SCTP stack.", static_cast<void *>(this)));
disconnect_all();
// we may have queued packet sends on STS after this; dispatch to ourselves before finishing here
// so we can be sure there aren't anymore runnables active that can try to touch the flow.
// DON'T use RUN_ON_THREAD, it queue-jumps!
mSTS->Dispatch(WrapRunnable(RefPtr<DataChannelConnection>(this),
&DataChannelConnection::DestroyOnSTSFinal),
NS_DISPATCH_NORMAL);
}
void DataChannelConnection::DestroyOnSTSFinal()
{
mTransportFlow = nullptr;
sDataChannelShutdown->CreateConnectionShutdown(this);
}
bool
DataChannelConnection::Init(unsigned short aPort, uint16_t aNumStreams, bool aMaxMessageSizeSet,
uint64_t aMaxMessageSize)
{
struct sctp_initmsg initmsg;
struct sctp_assoc_value av;
struct sctp_event event;
socklen_t len;
uint16_t event_types[] = {SCTP_ASSOC_CHANGE,
SCTP_PEER_ADDR_CHANGE,
SCTP_REMOTE_ERROR,
SCTP_SHUTDOWN_EVENT,
SCTP_ADAPTATION_INDICATION,
SCTP_PARTIAL_DELIVERY_EVENT,
SCTP_SEND_FAILED_EVENT,
SCTP_STREAM_RESET_EVENT,
SCTP_STREAM_CHANGE_EVENT};
{
ASSERT_WEBRTC(NS_IsMainThread());
// MutexAutoLock lock(mLock); Not needed since we're on mainthread always
mSendInterleaved = false;
mPpidFragmentation = false;
mMaxMessageSizeSet = false;
SetMaxMessageSize(aMaxMessageSizeSet, aMaxMessageSize);
if (!sctp_initialized) {
LOG(("sctp_init"));
#ifdef MOZ_PEERCONNECTION
usrsctp_init(0,
DataChannelConnection::SctpDtlsOutput,
debug_printf
);
#else
MOZ_CRASH("Trying to use SCTP/DTLS without mtransport");
#endif
// Set logging to SCTP:LogLevel::Debug to get SCTP debugs
if (MOZ_LOG_TEST(gSCTPLog, LogLevel::Debug)) {
usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL);
}
// Do not send ABORTs in response to INITs (1).
// Do not send ABORTs for received Out of the Blue packets (2).
usrsctp_sysctl_set_sctp_blackhole(2);
// Disable the Explicit Congestion Notification extension (currently not supported by the
// Firefox code)
usrsctp_sysctl_set_sctp_ecn_enable(0);
// Enable interleaving messages for different streams (incoming)
// See: https://tools.ietf.org/html/rfc6458#section-8.1.20
usrsctp_sysctl_set_sctp_default_frag_interleave(2);
sctp_initialized = true;
sDataChannelShutdown = new DataChannelShutdown();
sDataChannelShutdown->Init();
}
}
// XXX FIX! make this a global we get once
// Find the STS thread
nsresult rv;
mSTS = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
MOZ_ASSERT(NS_SUCCEEDED(rv));
// Open sctp with a callback
if ((mMasterSocket = usrsctp_socket(
AF_CONN, SOCK_STREAM, IPPROTO_SCTP, receive_cb, threshold_event,
usrsctp_sysctl_get_sctp_sendspace() / 2, this)) == nullptr) {
return false;
}
// Make non-blocking for bind/connect. SCTP over UDP defaults to non-blocking
// in associations for normal IO
if (usrsctp_set_non_blocking(mMasterSocket, 1) < 0) {
LOG(("Couldn't set non_blocking on SCTP socket"));
// We can't handle connect() safely if it will block, not that this will
// even happen.
goto error_cleanup;
}
// Make sure when we close the socket, make sure it doesn't call us back again!
// This would cause it try to use an invalid DataChannelConnection pointer
struct linger l;
l.l_onoff = 1;
l.l_linger = 0;
if (usrsctp_setsockopt(mMasterSocket, SOL_SOCKET, SO_LINGER,
(const void *)&l, (socklen_t)sizeof(struct linger)) < 0) {
LOG(("Couldn't set SO_LINGER on SCTP socket"));
// unsafe to allow it to continue if this fails
goto error_cleanup;
}
// XXX Consider disabling this when we add proper SDP negotiation.
// We may want to leave enabled for supporting 'cloning' of SDP offers, which
// implies re-use of the same pseudo-port number, or forcing a renegotiation.
{
const int option_value = 1;
if (usrsctp_setsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_REUSE_PORT,
(const void *)&option_value, (socklen_t)sizeof(option_value)) < 0) {
LOG(("Couldn't set SCTP_REUSE_PORT on SCTP socket"));
}
if (usrsctp_setsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_NODELAY,
(const void *)&option_value, (socklen_t)sizeof(option_value)) < 0) {
LOG(("Couldn't set SCTP_NODELAY on SCTP socket"));
}
}
// Set explicit EOR
{
const int option_value = 1;
if (usrsctp_setsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_EXPLICIT_EOR,
(const void *)&option_value, (socklen_t)sizeof(option_value)) < 0) {
LOG(("*** failed enable explicit EOR mode %d", errno));
goto error_cleanup;
}
}
// Enable ndata
// TODO: Bug 1381145, enable this once ndata has been deployed
#if 0
av.assoc_id = SCTP_FUTURE_ASSOC;
av.assoc_value = 1;
if (usrsctp_setsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_INTERLEAVING_SUPPORTED, &av,
(socklen_t)sizeof(struct sctp_assoc_value)) < 0) {
LOG(("*** failed enable ndata errno %d", errno));
goto error_cleanup;
}
#endif
av.assoc_id = SCTP_ALL_ASSOC;
av.assoc_value = SCTP_ENABLE_RESET_STREAM_REQ | SCTP_ENABLE_CHANGE_ASSOC_REQ;
if (usrsctp_setsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET, &av,
(socklen_t)sizeof(struct sctp_assoc_value)) < 0) {
LOG(("*** failed enable stream reset errno %d", errno));
goto error_cleanup;
}
/* Enable the events of interest. */
memset(&event, 0, sizeof(event));
event.se_assoc_id = SCTP_ALL_ASSOC;
event.se_on = 1;
for (unsigned short event_type : event_types) {
event.se_type = event_type;
if (usrsctp_setsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(event)) < 0) {
LOG(("*** failed setsockopt SCTP_EVENT errno %d", errno));
goto error_cleanup;
}
}
// Update number of streams
mStreams.AppendElements(aNumStreams);
for (uint32_t i = 0; i < aNumStreams; ++i) {
mStreams[i] = nullptr;
}
memset(&initmsg, 0, sizeof(initmsg));
len = sizeof(initmsg);
if (usrsctp_getsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_INITMSG, &initmsg, &len) < 0) {
LOG(("*** failed getsockopt SCTP_INITMSG"));
goto error_cleanup;
}
LOG(("Setting number of SCTP streams to %u, was %u/%u", aNumStreams,
initmsg.sinit_num_ostreams, initmsg.sinit_max_instreams));
initmsg.sinit_num_ostreams = aNumStreams;
initmsg.sinit_max_instreams = MAX_NUM_STREAMS;
if (usrsctp_setsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_INITMSG, &initmsg,
(socklen_t)sizeof(initmsg)) < 0) {
LOG(("*** failed setsockopt SCTP_INITMSG, errno %d", errno));
goto error_cleanup;
}
mSocket = nullptr;
usrsctp_register_address(static_cast<void *>(this));
LOG(("Registered %p within the SCTP stack.", static_cast<void *>(this)));
return true;
error_cleanup:
usrsctp_close(mMasterSocket);
mMasterSocket = nullptr;
return false;
}
void
DataChannelConnection::SetMaxMessageSize(bool aMaxMessageSizeSet, uint64_t aMaxMessageSize)
{
MutexAutoLock lock(mLock); // TODO: Needed?
if (mMaxMessageSizeSet && !aMaxMessageSizeSet) {
// Don't overwrite already set MMS with default values
return;
}
mMaxMessageSizeSet = aMaxMessageSizeSet;
mMaxMessageSize = aMaxMessageSize;
bool ppidFragmentationEnforced = false;
nsresult rv;
nsCOMPtr<nsIPrefService> prefs = do_GetService("@mozilla.org/preferences-service;1", &rv);
if (!NS_WARN_IF(NS_FAILED(rv))) {
nsCOMPtr<nsIPrefBranch> branch = do_QueryInterface(prefs);
if (branch) {
if (!NS_FAILED(branch->GetBoolPref(
"media.peerconnection.sctp.force_ppid_fragmentation", &mPpidFragmentation))) {
// Ensure that forced on/off PPID fragmentation does not get overridden when Firefox has
// been detected.
mMaxMessageSizeSet = true;
ppidFragmentationEnforced = true;
}
int32_t temp;
if (!NS_FAILED(branch->GetIntPref(
"media.peerconnection.sctp.force_maximum_message_size", &temp))) {
if (temp >= 0) {
mMaxMessageSize = (uint64_t)temp;
}
}
}
}
// Fix remote MMS. This code exists, so future implementations of RTCSctpTransport.maxMessageSize
// can simply provide that value from GetMaxMessageSize.
// TODO: Bug 1382779, once resolved, can be increased to min(Uint8ArrayMaxSize, UINT32_MAX)
// TODO: Bug 1381146, once resolved, can be increased to whatever we support then (hopefully
// SIZE_MAX)
if (mMaxMessageSize == 0 || mMaxMessageSize > WEBRTC_DATACHANNEL_MAX_MESSAGE_SIZE_REMOTE) {
mMaxMessageSize = WEBRTC_DATACHANNEL_MAX_MESSAGE_SIZE_REMOTE;
}
LOG(("Use PPID-based fragmentation/reassembly: %s (enforced=%s)",
mPpidFragmentation ? "yes" : "no", ppidFragmentationEnforced ? "yes" : "no"));
LOG(("Maximum message size (outgoing data): %" PRIu64 " (set=%s, enforced=%s)",
mMaxMessageSize, mMaxMessageSizeSet ? "yes" : "no",
aMaxMessageSize != mMaxMessageSize ? "yes" : "no"));
}
uint64_t
DataChannelConnection::GetMaxMessageSize()
{
return mMaxMessageSize;
}
#ifdef MOZ_PEERCONNECTION
void
DataChannelConnection::SetEvenOdd()
{
ASSERT_WEBRTC(IsSTSThread());
TransportLayerDtls *dtls = static_cast<TransportLayerDtls *>(
mTransportFlow->GetLayer(TransportLayerDtls::ID()));
MOZ_ASSERT(dtls); // DTLS is mandatory
mAllocateEven = (dtls->role() == TransportLayerDtls::CLIENT);
}
bool
DataChannelConnection::ConnectViaTransportFlow(TransportFlow *aFlow, uint16_t localport, uint16_t remoteport)
{
LOG(("Connect DTLS local %u, remote %u", localport, remoteport));
NS_PRECONDITION(mMasterSocket, "SCTP wasn't initialized before ConnectViaTransportFlow!");
if (NS_WARN_IF(!aFlow)) {
return false;
}
mTransportFlow = aFlow;
mLocalPort = localport;
mRemotePort = remoteport;
mState = CONNECTING;
RUN_ON_THREAD(mSTS, WrapRunnable(RefPtr<DataChannelConnection>(this),
&DataChannelConnection::SetSignals),
NS_DISPATCH_NORMAL);
return true;
}
void
DataChannelConnection::SetSignals()
{
ASSERT_WEBRTC(IsSTSThread());
ASSERT_WEBRTC(mTransportFlow);
LOG(("Setting transport signals, state: %d", mTransportFlow->state()));
mTransportFlow->SignalPacketReceived.connect(this, &DataChannelConnection::SctpDtlsInput);
// SignalStateChange() doesn't call you with the initial state
mTransportFlow->SignalStateChange.connect(this, &DataChannelConnection::CompleteConnect);
CompleteConnect(mTransportFlow, mTransportFlow->state());
}
void
DataChannelConnection::CompleteConnect(TransportFlow *flow, TransportLayer::State state)
{
LOG(("Data transport state: %d", state));
MutexAutoLock lock(mLock);
ASSERT_WEBRTC(IsSTSThread());
// We should abort connection on TS_ERROR.
// Note however that the association will also fail (perhaps with a delay) and
// notify us in that way
if (state != TransportLayer::TS_OPEN || !mMasterSocket)
return;
struct sockaddr_conn addr;
memset(&addr, 0, sizeof(addr));
addr.sconn_family = AF_CONN;
#if defined(__Userspace_os_Darwin)
addr.sconn_len = sizeof(addr);
#endif
addr.sconn_port = htons(mLocalPort);
addr.sconn_addr = static_cast<void *>(this);
LOG(("Calling usrsctp_bind"));
int r = usrsctp_bind(mMasterSocket, reinterpret_cast<struct sockaddr *>(&addr),
sizeof(addr));
if (r < 0) {
LOG(("usrsctp_bind failed: %d", r));
} else {
// This is the remote addr
addr.sconn_port = htons(mRemotePort);
LOG(("Calling usrsctp_connect"));
r = usrsctp_connect(mMasterSocket, reinterpret_cast<struct sockaddr *>(&addr),
sizeof(addr));
if (r >= 0 || errno == EINPROGRESS) {
struct sctp_paddrparams paddrparams;
socklen_t opt_len;
memset(&paddrparams, 0, sizeof(struct sctp_paddrparams));
memcpy(&paddrparams.spp_address, &addr, sizeof(struct sockaddr_conn));
opt_len = (socklen_t)sizeof(struct sctp_paddrparams);
r = usrsctp_getsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS,
&paddrparams, &opt_len);
if (r < 0) {
LOG(("usrsctp_getsockopt failed: %d", r));
} else {
// draft-ietf-rtcweb-data-channel-13 section 5: max initial MTU IPV4 1200, IPV6 1280
paddrparams.spp_pathmtu = 1200; // safe for either
paddrparams.spp_flags &= ~SPP_PMTUD_ENABLE;
paddrparams.spp_flags |= SPP_PMTUD_DISABLE;
opt_len = (socklen_t)sizeof(struct sctp_paddrparams);
r = usrsctp_setsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS,
&paddrparams, opt_len);
if (r < 0) {
LOG(("usrsctp_getsockopt failed: %d", r));
} else {
LOG(("usrsctp: PMTUD disabled, MTU set to %u", paddrparams.spp_pathmtu));
}
}
}
if (r < 0) {
if (errno == EINPROGRESS) {
// non-blocking
return;
}
LOG(("usrsctp_connect failed: %d", errno));
mState = CLOSED;
} else {
// We set Even/Odd and fire ON_CONNECTION via SCTP_COMM_UP when we get that
// This also avoids issues with calling TransportFlow stuff on Mainthread
return;
}
}
// Note: currently this doesn't actually notify the application
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CONNECTION,
this)));
}
// Process any pending Opens
void
DataChannelConnection::ProcessQueuedOpens()
{
// The nsDeque holds channels with an AddRef applied. Another reference
// (may) be held by the DOMDataChannel, unless it's been GC'd. No other
// references should exist.
// Can't copy nsDeque's. Move into temp array since any that fail will
// go back to mPending
nsDeque temp;
DataChannel *temp_channel; // really already_AddRefed<>
while (nullptr != (temp_channel = static_cast<DataChannel *>(mPending.PopFront()))) {
temp.Push(static_cast<void *>(temp_channel));
}
RefPtr<DataChannel> channel;
// All these entries have an AddRef(); make that explicit now via the dont_AddRef()
while (nullptr != (channel = dont_AddRef(static_cast<DataChannel *>(temp.PopFront())))) {
if (channel->mFlags & DATA_CHANNEL_FLAGS_FINISH_OPEN) {
LOG(("Processing queued open for %p (%u)", channel.get(), channel->mStream));
channel->mFlags &= ~DATA_CHANNEL_FLAGS_FINISH_OPEN;
// OpenFinish returns a reference itself, so we need to take it can Release it
channel = OpenFinish(channel.forget()); // may reset the flag and re-push
} else {
NS_ASSERTION(false, "How did a DataChannel get queued without the FINISH_OPEN flag?");
}
}
}
void
DataChannelConnection::SctpDtlsInput(TransportFlow *flow,
const unsigned char *data, size_t len)
{
if (MOZ_LOG_TEST(gSCTPLog, LogLevel::Debug)) {
char *buf;
if ((buf = usrsctp_dumppacket((void *)data, len, SCTP_DUMP_INBOUND)) != nullptr) {
SCTP_LOG(("%s", buf));
usrsctp_freedumpbuffer(buf);
}
}
// Pass the data to SCTP
MutexAutoLock lock(mLock);
usrsctp_conninput(static_cast<void *>(this), data, len, 0);
}
int
DataChannelConnection::SendPacket(unsigned char data[], size_t len, bool release)
{
//LOG(("%p: SCTP/DTLS sent %ld bytes", this, len));
int res = mTransportFlow->SendPacket(data, len) < 0 ? 1 : 0;
if (release)
delete [] data;
return res;
}
/* static */
int
DataChannelConnection::SctpDtlsOutput(void *addr, void *buffer, size_t length,
uint8_t tos, uint8_t set_df)
{
DataChannelConnection *peer = static_cast<DataChannelConnection *>(addr);
int res;
if (MOZ_LOG_TEST(gSCTPLog, LogLevel::Debug)) {
char *buf;
if ((buf = usrsctp_dumppacket(buffer, length, SCTP_DUMP_OUTBOUND)) != nullptr) {
SCTP_LOG(("%s", buf));
usrsctp_freedumpbuffer(buf);
}
}
// We're async proxying even if on the STSThread because this is called
// with internal SCTP locks held in some cases (such as in usrsctp_connect()).
// SCTP has an option for Apple, on IP connections only, to release at least
// one of the locks before calling a packet output routine; with changes to
// the underlying SCTP stack this might remove the need to use an async proxy.
if ((false /*peer->IsSTSThread()*/)) {
res = peer->SendPacket(static_cast<unsigned char *>(buffer), length, false);
} else {
auto *data = new unsigned char[length];
memcpy(data, buffer, length);
// Commented out since we have to Dispatch SendPacket to avoid deadlock"
// res = -1;
// XXX It might be worthwhile to add an assertion against the thread
// somehow getting into the DataChannel/SCTP code again, as
// DISPATCH_SYNC is not fully blocking. This may be tricky, as it
// needs to be a per-thread check, not a global.
peer->mSTS->Dispatch(WrapRunnable(
RefPtr<DataChannelConnection>(peer),
&DataChannelConnection::SendPacket, data, length, true),
NS_DISPATCH_NORMAL);
res = 0; // cheat! Packets can always be dropped later anyways
}
return res;
}
#endif
#ifdef ALLOW_DIRECT_SCTP_LISTEN_CONNECT
// listen for incoming associations
// Blocks! - Don't call this from main thread!
#error This code will not work as-is since SetEvenOdd() runs on Mainthread
bool
DataChannelConnection::Listen(unsigned short port)
{
struct sockaddr_in addr;
socklen_t addr_len;
NS_WARNING_ASSERTION(!NS_IsMainThread(),
"Blocks, do not call from main thread!!!");
/* Acting as the 'server' */
memset((void *)&addr, 0, sizeof(addr));
#ifdef HAVE_SIN_LEN
addr.sin_len = sizeof(struct sockaddr_in);
#endif
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
LOG(("Waiting for connections on port %u", ntohs(addr.sin_port)));
mState = CONNECTING;
if (usrsctp_bind(mMasterSocket, reinterpret_cast<struct sockaddr *>(&addr), sizeof(struct sockaddr_in)) < 0) {
LOG(("***Failed userspace_bind"));
return false;
}
if (usrsctp_listen(mMasterSocket, 1) < 0) {
LOG(("***Failed userspace_listen"));
return false;
}
LOG(("Accepting connection"));
addr_len = 0;
if ((mSocket = usrsctp_accept(mMasterSocket, nullptr, &addr_len)) == nullptr) {
LOG(("***Failed accept"));
return false;
}
mState = OPEN;
struct linger l;
l.l_onoff = 1;
l.l_linger = 0;
if (usrsctp_setsockopt(mSocket, SOL_SOCKET, SO_LINGER,
(const void *)&l, (socklen_t)sizeof(struct linger)) < 0) {
LOG(("Couldn't set SO_LINGER on SCTP socket"));
}
SetEvenOdd();
// Notify Connection open
// XXX We need to make sure connection sticks around until the message is delivered
LOG(("%s: sending ON_CONNECTION for %p", __FUNCTION__, this));
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CONNECTION,
this, (DataChannel *) nullptr)));
return true;
}
// Blocks! - Don't call this from main thread!
bool
DataChannelConnection::Connect(const char *addr, unsigned short port)
{
struct sockaddr_in addr4;
struct sockaddr_in6 addr6;
NS_WARNING_ASSERTION(!NS_IsMainThread(),
"Blocks, do not call from main thread!!!");
/* Acting as the connector */
LOG(("Connecting to %s, port %u", addr, port));
memset((void *)&addr4, 0, sizeof(struct sockaddr_in));
memset((void *)&addr6, 0, sizeof(struct sockaddr_in6));
#ifdef HAVE_SIN_LEN
addr4.sin_len = sizeof(struct sockaddr_in);
#endif
#ifdef HAVE_SIN6_LEN
addr6.sin6_len = sizeof(struct sockaddr_in6);
#endif
addr4.sin_family = AF_INET;
addr6.sin6_family = AF_INET6;
addr4.sin_port = htons(port);
addr6.sin6_port = htons(port);
mState = CONNECTING;
#if !defined(__Userspace_os_Windows)
if (inet_pton(AF_INET6, addr, &addr6.sin6_addr) == 1) {
if (usrsctp_connect(mMasterSocket, reinterpret_cast<struct sockaddr *>(&addr6), sizeof(struct sockaddr_in6)) < 0) {
LOG(("*** Failed userspace_connect"));
return false;
}
} else if (inet_pton(AF_INET, addr, &addr4.sin_addr) == 1) {
if (usrsctp_connect(mMasterSocket, reinterpret_cast<struct sockaddr *>(&addr4), sizeof(struct sockaddr_in)) < 0) {
LOG(("*** Failed userspace_connect"));
return false;
}
} else {
LOG(("*** Illegal destination address."));
}
#else
{
struct sockaddr_storage ss;
int sslen = sizeof(ss);
if (!WSAStringToAddressA(const_cast<char *>(addr), AF_INET6, nullptr, (struct sockaddr*)&ss, &sslen)) {
addr6.sin6_addr = (reinterpret_cast<struct sockaddr_in6 *>(&ss))->sin6_addr;
if (usrsctp_connect(mMasterSocket, reinterpret_cast<struct sockaddr *>(&addr6), sizeof(struct sockaddr_in6)) < 0) {
LOG(("*** Failed userspace_connect"));
return false;
}
} else if (!WSAStringToAddressA(const_cast<char *>(addr), AF_INET, nullptr, (struct sockaddr*)&ss, &sslen)) {
addr4.sin_addr = (reinterpret_cast<struct sockaddr_in *>(&ss))->sin_addr;
if (usrsctp_connect(mMasterSocket, reinterpret_cast<struct sockaddr *>(&addr4), sizeof(struct sockaddr_in)) < 0) {
LOG(("*** Failed userspace_connect"));
return false;
}
} else {
LOG(("*** Illegal destination address."));
}
}
#endif
mSocket = mMasterSocket;
LOG(("connect() succeeded! Entering connected mode"));
mState = OPEN;
SetEvenOdd();
// Notify Connection open
// XXX We need to make sure connection sticks around until the message is delivered
LOG(("%s: sending ON_CONNECTION for %p", __FUNCTION__, this));
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CONNECTION,
this, (DataChannel *) nullptr)));
return true;
}
#endif
DataChannel *
DataChannelConnection::FindChannelByStream(uint16_t stream)
{
return mStreams.SafeElementAt(stream);
}
uint16_t
DataChannelConnection::FindFreeStream()
{
uint32_t i, j, limit;
limit = mStreams.Length();
if (limit > MAX_NUM_STREAMS)
limit = MAX_NUM_STREAMS;
for (i = (mAllocateEven ? 0 : 1); i < limit; i += 2) {
if (!mStreams[i]) {
// Verify it's not still in the process of closing
for (j = 0; j < mStreamsResetting.Length(); ++j) {
if (mStreamsResetting[j] == i) {
break;
}
}
if (j == mStreamsResetting.Length())
break;
}
}
if (i >= limit) {
return INVALID_STREAM;
}
return i;
}
uint32_t
DataChannelConnection::UpdateCurrentStreamIndex()
{
if (mCurrentStream == mStreams.Length() - 1) {
mCurrentStream = 0;
} else {
++mCurrentStream;
}
return mCurrentStream;
}
uint32_t
DataChannelConnection::GetCurrentStreamIndex()
{
// Fix current stream index (in case #streams decreased)
if (mCurrentStream >= mStreams.Length()) {
mCurrentStream = 0;
}
return mCurrentStream;
}
bool
DataChannelConnection::RequestMoreStreams(int32_t aNeeded)
{
struct sctp_status status;
struct sctp_add_streams sas;
uint32_t outStreamsNeeded;
socklen_t len;
if (aNeeded + mStreams.Length() > MAX_NUM_STREAMS) {
aNeeded = MAX_NUM_STREAMS - mStreams.Length();
}
if (aNeeded <= 0) {
return false;
}
len = (socklen_t)sizeof(struct sctp_status);
if (usrsctp_getsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_STATUS, &status, &len) < 0) {
LOG(("***failed: getsockopt SCTP_STATUS"));
return false;
}
outStreamsNeeded = aNeeded; // number to add
// Note: if multiple channel opens happen when we don't have enough space,
// we'll call RequestMoreStreams() multiple times
memset(&sas, 0, sizeof(sas));
sas.sas_instrms = 0;
sas.sas_outstrms = (uint16_t)outStreamsNeeded; /* XXX error handling */
// Doesn't block, we get an event when it succeeds or fails
if (usrsctp_setsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_ADD_STREAMS, &sas,
(socklen_t) sizeof(struct sctp_add_streams)) < 0) {
if (errno == EALREADY) {
LOG(("Already have %u output streams", outStreamsNeeded));
return true;
}
LOG(("***failed: setsockopt ADD errno=%d", errno));
return false;
}
LOG(("Requested %u more streams", outStreamsNeeded));
// We add to mStreams when we get a SCTP_STREAM_CHANGE_EVENT and the
// values are larger than mStreams.Length()
return true;
}
// Returns a POSIX error code.
int
DataChannelConnection::SendControlMessage(const uint8_t *data, uint32_t len, uint16_t stream)
{
struct sctp_sendv_spa info = {0};
// General flags
info.sendv_flags = SCTP_SEND_SNDINFO_VALID;
// Set stream identifier, protocol identifier and flags
info.sendv_sndinfo.snd_sid = stream;
info.sendv_sndinfo.snd_flags = SCTP_EOR;
info.sendv_sndinfo.snd_ppid = htonl(DATA_CHANNEL_PPID_CONTROL);
// Create message instance and send
// Note: Main-thread IO, but doesn't block
#if (UINT32_MAX > SIZE_MAX)
if (len > SIZE_MAX) {
return EMSGSIZE;
}
#endif
OutgoingMsg msg(info, data, (size_t)len);
bool buffered;
int error = SendMsgInternalOrBuffer(mBufferedControl, msg, buffered);
// Set pending type (if buffered)
if (!error && buffered && !mPendingType) {
mPendingType = PENDING_DCEP;
}
return error;
}
// Returns a POSIX error code.
int
DataChannelConnection::SendOpenAckMessage(uint16_t stream)
{
struct rtcweb_datachannel_ack ack;
memset(&ack, 0, sizeof(struct rtcweb_datachannel_ack));
ack.msg_type = DATA_CHANNEL_ACK;
return SendControlMessage((const uint8_t *)&ack, sizeof(ack), stream);
}
// Returns a POSIX error code.
int
DataChannelConnection::SendOpenRequestMessage(const nsACString& label,
const nsACString& protocol,
uint16_t stream, bool unordered,
uint16_t prPolicy, uint32_t prValue)
{
const int label_len = label.Length(); // not including nul
const int proto_len = protocol.Length(); // not including nul
// careful - request struct include one char for the label
const int req_size = sizeof(struct rtcweb_datachannel_open_request) - 1 +
label_len + proto_len;
struct rtcweb_datachannel_open_request *req =
(struct rtcweb_datachannel_open_request*) moz_xmalloc(req_size);
memset(req, 0, req_size);
req->msg_type = DATA_CHANNEL_OPEN_REQUEST;
switch (prPolicy) {
case SCTP_PR_SCTP_NONE:
req->channel_type = DATA_CHANNEL_RELIABLE;
break;
case SCTP_PR_SCTP_TTL:
req->channel_type = DATA_CHANNEL_PARTIAL_RELIABLE_TIMED;
break;
case SCTP_PR_SCTP_RTX:
req->channel_type = DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT;
break;
default:
free(req);
return EINVAL;
}
if (unordered) {
// Per the current types, all differ by 0x80 between ordered and unordered
req->channel_type |= 0x80; // NOTE: be careful if new types are added in the future
}
req->reliability_param = htonl(prValue);
req->priority = htons(0); /* XXX: add support */
req->label_length = htons(label_len);
req->protocol_length = htons(proto_len);
memcpy(&req->label[0], PromiseFlatCString(label).get(), label_len);
memcpy(&req->label[label_len], PromiseFlatCString(protocol).get(), proto_len);
// TODO: req_size is an int... that looks hairy
int error = SendControlMessage((const uint8_t *)req, req_size, stream);
free(req);
return error;
}
// XXX This should use a separate thread (outbound queue) which should
// select() to know when to *try* to send data to the socket again.
// Alternatively, it can use a timeout, but that's guaranteed to be wrong
// (just not sure in what direction). We could re-implement NSPR's
// PR_POLL_WRITE/etc handling... with a lot of work.
// Better yet, use the SCTP stack's notifications on buffer state to avoid
// filling the SCTP's buffers.
// returns if we're still blocked (true)
bool
DataChannelConnection::SendDeferredMessages()
{
RefPtr<DataChannel> channel; // we may null out the refs to this
// This may block while something is modifying channels, but should not block for IO
mLock.AssertCurrentThreadOwns();
LOG(("SendDeferredMessages called, pending type: %d", mPendingType));
if (!mPendingType) {
return false;
}
// Send pending control messages
// Note: If ndata is not active, check if DCEP messages are currently outstanding. These need to
// be sent first before other streams can be used for sending.
if (!mBufferedControl.IsEmpty() && (mSendInterleaved || mPendingType == PENDING_DCEP)) {
if (SendBufferedMessages(mBufferedControl)) {
return true;
}
// Note: There may or may not be pending data messages
mPendingType = PENDING_DATA;
}
bool blocked = false;
uint32_t i = GetCurrentStreamIndex();
uint32_t end = i;
do {
channel = mStreams[i];
if (!channel || channel->mBufferedData.IsEmpty()) {
i = UpdateCurrentStreamIndex();
continue;
}
// Clear if closing/closed
if (channel->mState == CLOSED || channel->mState == CLOSING) {
channel->mBufferedData.Clear();
i = UpdateCurrentStreamIndex();
continue;
}
size_t bufferedAmount = channel->GetBufferedAmountLocked();
size_t threshold = channel->mBufferedThreshold;
bool wasOverThreshold = bufferedAmount >= threshold;
// Send buffered data messages
// Warning: This will fail in case ndata is inactive and a previously deallocated data channel
// has not been closed properly. If you ever see that no messages can be sent on any
// channel, this is likely the cause (an explicit EOR message partially sent whose
// remaining chunks are still being waited for).
blocked = SendBufferedMessages(channel->mBufferedData);
bufferedAmount = channel->GetBufferedAmountLocked();
// can never fire with default threshold of 0
if (wasOverThreshold && bufferedAmount < threshold) {
LOG(("%s: sending BUFFER_LOW_THRESHOLD for %s/%s: %u", __FUNCTION__,
channel->mLabel.get(), channel->mProtocol.get(), channel->mStream));
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::BUFFER_LOW_THRESHOLD,
this, channel)));
}
if (bufferedAmount == 0) {
// buffered-to-not-buffered transition; tell the DOM code in case this makes it
// available for GC
LOG(("%s: sending NO_LONGER_BUFFERED for %s/%s: %u", __FUNCTION__,
channel->mLabel.get(), channel->mProtocol.get(), channel->mStream));
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::NO_LONGER_BUFFERED,
this, channel)));
}
// Update current stream index
// Note: If ndata is not active, the outstanding data messages on this stream need to be sent
// first before other streams can be used for sending.
if (mSendInterleaved || !blocked) {
i = UpdateCurrentStreamIndex();
}
} while (!blocked && i != end);
if (!blocked) {
mPendingType = mBufferedControl.IsEmpty() ? PENDING_NONE : PENDING_DCEP;
}
return blocked;
}
// Called with mLock locked!
// buffer MUST have at least one item!
// returns if we're still blocked (true)
bool
DataChannelConnection::SendBufferedMessages(nsTArray<nsAutoPtr<BufferedOutgoingMsg>> &buffer)
{
do {
// Re-send message
int error = SendMsgInternal(*buffer[0]);
switch (error) {
case 0:
buffer.RemoveElementAt(0);
break;
case EAGAIN:
#if (EAGAIN != EWOULDBLOCK)
case EWOULDBLOCK:
#endif
return true;
default:
buffer.RemoveElementAt(0);
LOG(("error on sending: %d", error));
break;
}
} while (!buffer.IsEmpty());
return false;
}
// Caller must ensure that length <= SIZE_MAX
void
DataChannelConnection::HandleOpenRequestMessage(const struct rtcweb_datachannel_open_request *req,
uint32_t length, uint16_t stream)
{
RefPtr<DataChannel> channel;
uint32_t prValue;
uint16_t prPolicy;
uint32_t flags;
mLock.AssertCurrentThreadOwns();
const size_t requiredLength =
(sizeof(*req) - 1) + ntohs(req->label_length) + ntohs(req->protocol_length);
if (((size_t)length) != requiredLength) {
LOG(("%s: Inconsistent length: %u, should be %zu",
__FUNCTION__, length, requiredLength));
if (((size_t)length) < requiredLength)
return;
}
LOG(("%s: length %u, sizeof(*req) = %zu", __FUNCTION__, length, sizeof(*req)));
switch (req->channel_type) {
case DATA_CHANNEL_RELIABLE:
case DATA_CHANNEL_RELIABLE_UNORDERED:
prPolicy = SCTP_PR_SCTP_NONE;
break;
case DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT:
case DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED:
prPolicy = SCTP_PR_SCTP_RTX;
break;
case DATA_CHANNEL_PARTIAL_RELIABLE_TIMED:
case DATA_CHANNEL_PARTIAL_RELIABLE_TIMED_UNORDERED:
prPolicy = SCTP_PR_SCTP_TTL;
break;
default:
LOG(("Unknown channel type %d", req->channel_type));
/* XXX error handling */
return;
}
prValue = ntohl(req->reliability_param);
flags = (req->channel_type & 0x80) ? DATA_CHANNEL_FLAGS_OUT_OF_ORDER_ALLOWED : 0;
if ((channel = FindChannelByStream(stream))) {
if (!(channel->mFlags & DATA_CHANNEL_FLAGS_EXTERNAL_NEGOTIATED)) {
LOG(("ERROR: HandleOpenRequestMessage: channel for stream %u is in state %d instead of CLOSED.",
stream, channel->mState));
/* XXX: some error handling */
} else {
LOG(("Open for externally negotiated channel %u", stream));
// XXX should also check protocol, maybe label
if (prPolicy != channel->mPrPolicy ||
prValue != channel->mPrValue ||
flags != (channel->mFlags & DATA_CHANNEL_FLAGS_OUT_OF_ORDER_ALLOWED))
{
LOG(("WARNING: external negotiation mismatch with OpenRequest:"
"channel %u, policy %u/%u, value %u/%u, flags %x/%x",
stream, prPolicy, channel->mPrPolicy,
prValue, channel->mPrValue, flags, channel->mFlags));
}
}
return;
}
if (stream >= mStreams.Length()) {
LOG(("%s: stream %u out of bounds (%zu)", __FUNCTION__, stream, mStreams.Length()));
return;
}
nsCString label(nsDependentCSubstring(&req->label[0], ntohs(req->label_length)));
nsCString protocol(nsDependentCSubstring(&req->label[ntohs(req->label_length)],
ntohs(req->protocol_length)));
channel = new DataChannel(this,
stream,
DataChannel::CONNECTING,
label,
protocol,
prPolicy, prValue,
flags,
nullptr, nullptr);
mStreams[stream] = channel;
channel->mState = DataChannel::WAITING_TO_OPEN;
LOG(("%s: sending ON_CHANNEL_CREATED for %s/%s: %u (state %u)", __FUNCTION__,
channel->mLabel.get(), channel->mProtocol.get(), stream, channel->mState));
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CHANNEL_CREATED,
this, channel)));
LOG(("%s: deferring sending ON_CHANNEL_OPEN for %p", __FUNCTION__, channel.get()));
int error = SendOpenAckMessage(stream);
if (error) {
LOG(("SendOpenRequest failed, error = %d", error));
// Close the channel, inform the user
CloseInt(channel);
// XXX send error via DataChannelOnMessageAvailable (bug 843625)
return;
}
// Now process any queued data messages for the channel (which will
// themselves likely get queued until we leave WAITING_TO_OPEN, plus any
// more that come in before that happens)
DeliverQueuedData(stream);
}
// NOTE: the updated spec from the IETF says we should set in-order until we receive an ACK.
// That would make this code moot. Keep it for now for backwards compatibility.
void
DataChannelConnection::DeliverQueuedData(uint16_t stream)
{
mLock.AssertCurrentThreadOwns();
uint32_t i = 0;
while (i < mQueuedData.Length()) {
// Careful! we may modify the array length from within the loop!
if (mQueuedData[i]->mStream == stream) {
LOG(("Delivering queued data for stream %u, length %u",
stream, mQueuedData[i]->mLength));
// Deliver the queued data
HandleDataMessage(mQueuedData[i]->mData, mQueuedData[i]->mLength,
mQueuedData[i]->mPpid, mQueuedData[i]->mStream,
mQueuedData[i]->mFlags);
mQueuedData.RemoveElementAt(i);
continue; // don't bump index since we removed the element
}
i++;
}
}
// Caller must ensure that length <= SIZE_MAX
void
DataChannelConnection::HandleOpenAckMessage(const struct rtcweb_datachannel_ack *ack,
uint32_t length, uint16_t stream)
{
DataChannel *channel;
mLock.AssertCurrentThreadOwns();
channel = FindChannelByStream(stream);
if (NS_WARN_IF(!channel)) {
return;
}
LOG(("OpenAck received for stream %u, waiting=%d", stream,
(channel->mFlags & DATA_CHANNEL_FLAGS_WAITING_ACK) ? 1 : 0));
channel->mFlags &= ~DATA_CHANNEL_FLAGS_WAITING_ACK;
}
// Caller must ensure that length <= SIZE_MAX
void
DataChannelConnection::HandleUnknownMessage(uint32_t ppid, uint32_t length, uint16_t stream)
{
/* XXX: Send an error message? */
LOG(("unknown DataChannel message received: %u, len %u on stream %d", ppid, length, stream));
// XXX Log to JS error console if possible
}
uint8_t
DataChannelConnection::BufferMessage(nsACString& recvBuffer, const void *data,
uint32_t length, uint32_t ppid, int flags)
{
const char *buffer = (const char *) data;
uint8_t bufferFlags = 0;
if ((flags & MSG_EOR) &&
ppid != DATA_CHANNEL_PPID_BINARY_PARTIAL &&
ppid != DATA_CHANNEL_PPID_DOMSTRING_PARTIAL) {
bufferFlags |= DATA_CHANNEL_BUFFER_MESSAGE_FLAGS_COMPLETE;
// Return directly if nothing has been buffered
if (recvBuffer.IsEmpty()) {
return bufferFlags;
}
}
// Ensure it doesn't blow up our buffer
// TODO: Change 'WEBRTC_DATACHANNEL_MAX_MESSAGE_SIZE_LOCAL' to whatever the new buffer is capable
// of holding.
if (((uint64_t) recvBuffer.Length()) + ((uint64_t) length) > WEBRTC_DATACHANNEL_MAX_MESSAGE_SIZE_LOCAL) {
bufferFlags |= DATA_CHANNEL_BUFFER_MESSAGE_FLAGS_TOO_LARGE;
return bufferFlags;
}
// Copy & add to receive buffer
recvBuffer.Append(buffer, length);
bufferFlags |= DATA_CHANNEL_BUFFER_MESSAGE_FLAGS_BUFFERED;
return bufferFlags;
}
void
DataChannelConnection::HandleDataMessage(const void *data, size_t length, uint32_t ppid,
uint16_t stream, int flags)
{
DataChannel *channel;
const char *buffer = (const char *) data;
mLock.AssertCurrentThreadOwns();
channel = FindChannelByStream(stream);
// Note: Until we support SIZE_MAX sized messages, we need this check
#if (SIZE_MAX > UINT32_MAX)
if (length > UINT32_MAX) {
LOG(("DataChannel: Cannot handle message of size %zu (max=%" PRIu32 ")",
length, UINT32_MAX));
CloseInt(channel);
return;
}
#endif
uint32_t data_length = (uint32_t)length;
// XXX A closed channel may trip this... check
// NOTE: the updated spec from the IETF says we should set in-order until we receive an ACK.
// That would make this code moot. Keep it for now for backwards compatibility.
if (!channel) {
// In the updated 0-RTT open case, the sender can send data immediately
// after Open, and doesn't set the in-order bit (since we don't have a
// response or ack). Also, with external negotiation, data can come in
// before we're told about the external negotiation. We need to buffer
// data until either a) Open comes in, if the ordering get messed up,
// or b) the app tells us this channel was externally negotiated. When
// these occur, we deliver the data.
// Since this is rare and non-performance, keep a single list of queued
// data messages to deliver once the channel opens.
LOG(("Queuing data for stream %u, length %u", stream, data_length));
// Copies data
mQueuedData.AppendElement(new QueuedDataMessage(stream, ppid, flags, data, data_length));
return;
}
// Ignore incoming data in case the channel is closed
if (channel->mState == CLOSED) {
return;
}
bool is_binary = true;
uint8_t bufferFlags;
int32_t type;
const char* info = "";
if (ppid == DATA_CHANNEL_PPID_DOMSTRING_PARTIAL ||
ppid == DATA_CHANNEL_PPID_DOMSTRING) {
is_binary = false;
}
if (is_binary != channel->mIsRecvBinary && !channel->mRecvBuffer.IsEmpty()) {
NS_WARNING("DataChannel message aborted by fragment type change!");
// TODO: Maybe closing would be better as this is a hard to detect protocol violation?
channel->mRecvBuffer.Truncate(0);
}
channel->mIsRecvBinary = is_binary;
// Remaining chunks of previously truncated message (due to the buffer being full)?
if (channel->mFlags & DATA_CHANNEL_FLAGS_CLOSING_TOO_LARGE) {
LOG(("DataChannel: Ignoring partial message of length %u, buffer full and closing",
data_length));
// Only unblock if unordered
if ((channel->mFlags & DATA_CHANNEL_FLAGS_OUT_OF_ORDER_ALLOWED) && (flags & MSG_EOR)) {
channel->mFlags &= ~DATA_CHANNEL_FLAGS_CLOSING_TOO_LARGE;
}
}
// Buffer message until complete
bufferFlags = BufferMessage(channel->mRecvBuffer, buffer, data_length, ppid, flags);
if (bufferFlags & DATA_CHANNEL_BUFFER_MESSAGE_FLAGS_TOO_LARGE) {
LOG(("DataChannel: Buffered message would become too large to handle, closing channel"));
channel->mRecvBuffer.Truncate(0);
channel->mFlags |= DATA_CHANNEL_FLAGS_CLOSING_TOO_LARGE;
CloseInt(channel);
return;
}
if (!(bufferFlags & DATA_CHANNEL_BUFFER_MESSAGE_FLAGS_COMPLETE)) {
LOG(("DataChannel: Partial %s message of length %u (total %u) on channel id %u",
is_binary ? "binary" : "string", data_length, channel->mRecvBuffer.Length(),
channel->mStream));
return; // Not ready to notify application
}
if (bufferFlags & DATA_CHANNEL_BUFFER_MESSAGE_FLAGS_BUFFERED) {
data_length = channel->mRecvBuffer.Length();
}
// Complain about large messages (only complain - we can handle it)
if (data_length > WEBRTC_DATACHANNEL_MAX_MESSAGE_SIZE_LOCAL) {
LOG(("DataChannel: Received message of length %u is > announced maximum message size (%u)",
data_length, WEBRTC_DATACHANNEL_MAX_MESSAGE_SIZE_LOCAL));
}
switch (ppid) {
case DATA_CHANNEL_PPID_DOMSTRING:
LOG(("DataChannel: Received string message of length %u on channel %u",
data_length, channel->mStream));
type = DataChannelOnMessageAvailable::ON_DATA_STRING;
if (bufferFlags & DATA_CHANNEL_BUFFER_MESSAGE_FLAGS_BUFFERED) {
info = " (string fragmented)";
}
// else send using recvData normally
// WebSockets checks IsUTF8() here; we can try to deliver it
break;
case DATA_CHANNEL_PPID_BINARY:
LOG(("DataChannel: Received binary message of length %u on channel id %u",
data_length, channel->mStream));
type = DataChannelOnMessageAvailable::ON_DATA_BINARY;
if (bufferFlags & DATA_CHANNEL_BUFFER_MESSAGE_FLAGS_BUFFERED) {
info = " (binary fragmented)";
}
// else send using recvData normally
break;
default:
NS_ERROR("Unknown data PPID");
return;
}
// Notify onmessage
LOG(("%s: sending ON_DATA_%s%s for %p", __FUNCTION__,
(type == DataChannelOnMessageAvailable::ON_DATA_STRING) ? "STRING" : "BINARY",
info, channel));
if (bufferFlags & DATA_CHANNEL_BUFFER_MESSAGE_FLAGS_BUFFERED) {
channel->SendOrQueue(new DataChannelOnMessageAvailable(
type, this, channel, channel->mRecvBuffer));
channel->mRecvBuffer.Truncate(0);
} else {
nsAutoCString recvData(buffer, data_length); // copies (<64) or allocates
channel->SendOrQueue(new DataChannelOnMessageAvailable(
type, this, channel, recvData));
}
}
void
DataChannelConnection::HandleDCEPMessage(const void *buffer, size_t length, uint32_t ppid,
uint16_t stream, int flags)
{
const struct rtcweb_datachannel_open_request *req;
const struct rtcweb_datachannel_ack *ack;
// Note: Until we support SIZE_MAX sized messages, we need this check
#if (SIZE_MAX > UINT32_MAX)
if (length > UINT32_MAX) {
LOG(("DataChannel: Cannot handle message of size %zu (max=%u)", length, UINT32_MAX));
Stop();
return;
}
#endif
uint32_t data_length = (uint32_t)length;
mLock.AssertCurrentThreadOwns();
// Buffer message until complete
const uint8_t bufferFlags = BufferMessage(mRecvBuffer, buffer, data_length, ppid, flags);
if (bufferFlags & DATA_CHANNEL_BUFFER_MESSAGE_FLAGS_TOO_LARGE) {
LOG(("DataChannel: Buffered message would become too large to handle, closing connection"));
mRecvBuffer.Truncate(0);
Stop();
return;
}
if (!(bufferFlags & DATA_CHANNEL_BUFFER_MESSAGE_FLAGS_COMPLETE)) {
LOG(("Buffered partial DCEP message of length %u", data_length));
return;
}
if (bufferFlags & DATA_CHANNEL_BUFFER_MESSAGE_FLAGS_BUFFERED) {
buffer = reinterpret_cast<const void *>(mRecvBuffer.BeginReading());
data_length = mRecvBuffer.Length();
}
req = static_cast<const struct rtcweb_datachannel_open_request *>(buffer);
LOG(("Handling DCEP message of length %u", data_length));
// Ensure minimum message size (ack is the smallest DCEP message)
if ((size_t)data_length < sizeof(*ack)) {
LOG(("Ignored invalid DCEP message (too short)"));
return;
}
switch (req->msg_type) {
case DATA_CHANNEL_OPEN_REQUEST:
// structure includes a possibly-unused char label[1] (in a packed structure)
if (NS_WARN_IF((size_t)data_length < sizeof(*req) - 1)) {
return;
}
HandleOpenRequestMessage(req, data_length, stream);
break;
case DATA_CHANNEL_ACK:
// >= sizeof(*ack) checked above
ack = static_cast<const struct rtcweb_datachannel_ack *>(buffer);
HandleOpenAckMessage(ack, data_length, stream);
break;
default:
HandleUnknownMessage(ppid, data_length, stream);
break;
}
// Reset buffer
mRecvBuffer.Truncate(0);
}
// Called with mLock locked!
void
DataChannelConnection::HandleMessage(const void *buffer, size_t length, uint32_t ppid,
uint16_t stream, int flags)
{
mLock.AssertCurrentThreadOwns();
switch (ppid) {
case DATA_CHANNEL_PPID_CONTROL:
HandleDCEPMessage(buffer, length, ppid, stream, flags);
break;
case DATA_CHANNEL_PPID_DOMSTRING_PARTIAL:
case DATA_CHANNEL_PPID_DOMSTRING:
case DATA_CHANNEL_PPID_BINARY_PARTIAL:
case DATA_CHANNEL_PPID_BINARY:
HandleDataMessage(buffer, length, ppid, stream, flags);
break;
default:
LOG(("Message of length %zu PPID %u on stream %u received (%s).",
length, ppid, stream, (flags & MSG_EOR) ? "complete" : "partial"));
break;
}
}
void
DataChannelConnection::HandleAssociationChangeEvent(const struct sctp_assoc_change *sac)
{
uint32_t i, n;
switch (sac->sac_state) {
case SCTP_COMM_UP:
LOG(("Association change: SCTP_COMM_UP"));
if (mState == CONNECTING) {
mSocket = mMasterSocket;
mState = OPEN;
// Check for older Firefox by looking at the amount of incoming streams
LOG(("Negotiated number of incoming streams: %" PRIu16, sac->sac_inbound_streams));
if (!mMaxMessageSizeSet
&& sac->sac_inbound_streams == WEBRTC_DATACHANNEL_STREAMS_OLDER_FIREFOX) {
LOG(("Older Firefox detected, using PPID-based fragmentation"));
mPpidFragmentation = true;
}
SetEvenOdd();
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CONNECTION,
this)));
LOG(("DTLS connect() succeeded! Entering connected mode"));
// Open any streams pending...
ProcessQueuedOpens();
} else if (mState == OPEN) {
LOG(("DataConnection Already OPEN"));
} else {
LOG(("Unexpected state: %d", mState));
}
break;
case SCTP_COMM_LOST:
LOG(("Association change: SCTP_COMM_LOST"));
// This association is toast, so also close all the channels -- from mainthread!
Stop();
break;
case SCTP_RESTART:
LOG(("Association change: SCTP_RESTART"));
break;
case SCTP_SHUTDOWN_COMP:
LOG(("Association change: SCTP_SHUTDOWN_COMP"));
Stop();
break;
case SCTP_CANT_STR_ASSOC:
LOG(("Association change: SCTP_CANT_STR_ASSOC"));
break;
default:
LOG(("Association change: UNKNOWN"));
break;
}
LOG(("Association change: streams (in/out) = (%u/%u)",
sac->sac_inbound_streams, sac->sac_outbound_streams));
if (NS_WARN_IF(!sac)) {
return;
}
n = sac->sac_length - sizeof(*sac);
if ((sac->sac_state == SCTP_COMM_UP) || (sac->sac_state == SCTP_RESTART)) {
if (n > 0) {
for (i = 0; i < n; ++i) {
switch (sac->sac_info[i]) {
case SCTP_ASSOC_SUPPORTS_PR:
LOG(("Supports: PR"));
break;
case SCTP_ASSOC_SUPPORTS_AUTH:
LOG(("Supports: AUTH"));
break;
case SCTP_ASSOC_SUPPORTS_ASCONF:
LOG(("Supports: ASCONF"));
break;
case SCTP_ASSOC_SUPPORTS_MULTIBUF:
LOG(("Supports: MULTIBUF"));
break;
case SCTP_ASSOC_SUPPORTS_RE_CONFIG:
LOG(("Supports: RE-CONFIG"));
break;
#if defined(SCTP_ASSOC_SUPPORTS_INTERLEAVING)
case SCTP_ASSOC_SUPPORTS_INTERLEAVING:
LOG(("Supports: NDATA"));
// TODO: This should probably be set earlier above in 'case SCTP_COMM_UP' but we also
// need this for 'SCTP_RESTART'.
mSendInterleaved = true;
break;
#endif
default:
LOG(("Supports: UNKNOWN(0x%02x)", sac->sac_info[i]));
break;
}
}
}
} else if (((sac->sac_state == SCTP_COMM_LOST) ||
(sac->sac_state == SCTP_CANT_STR_ASSOC)) && (n > 0)) {
LOG(("Association: ABORT ="));
for (i = 0; i < n; ++i) {
LOG((" 0x%02x", sac->sac_info[i]));
}
}
if ((sac->sac_state == SCTP_CANT_STR_ASSOC) ||
(sac->sac_state == SCTP_SHUTDOWN_COMP) ||
(sac->sac_state == SCTP_COMM_LOST)) {
return;
}
}
void
DataChannelConnection::HandlePeerAddressChangeEvent(const struct sctp_paddr_change *spc)
{
const char *addr = "";
#if !defined(__Userspace_os_Windows)
char addr_buf[INET6_ADDRSTRLEN];
struct sockaddr_in *sin;
struct sockaddr_in6 *sin6;
#endif
switch (spc->spc_aaddr.ss_family) {
case AF_INET:
#if !defined(__Userspace_os_Windows)
sin = (struct sockaddr_in *)&spc->spc_aaddr;
addr = inet_ntop(AF_INET, &sin->sin_addr, addr_buf, INET6_ADDRSTRLEN);
#endif
break;
case AF_INET6:
#if !defined(__Userspace_os_Windows)
sin6 = (struct sockaddr_in6 *)&spc->spc_aaddr;
addr = inet_ntop(AF_INET6, &sin6->sin6_addr, addr_buf, INET6_ADDRSTRLEN);
#endif
break;
case AF_CONN:
addr = "DTLS connection";
break;
default:
break;
}
LOG(("Peer address %s is now ", addr));
switch (spc->spc_state) {
case SCTP_ADDR_AVAILABLE:
LOG(("SCTP_ADDR_AVAILABLE"));
break;
case SCTP_ADDR_UNREACHABLE:
LOG(("SCTP_ADDR_UNREACHABLE"));
break;
case SCTP_ADDR_REMOVED:
LOG(("SCTP_ADDR_REMOVED"));
break;
case SCTP_ADDR_ADDED:
LOG(("SCTP_ADDR_ADDED"));
break;
case SCTP_ADDR_MADE_PRIM:
LOG(("SCTP_ADDR_MADE_PRIM"));
break;
case SCTP_ADDR_CONFIRMED:
LOG(("SCTP_ADDR_CONFIRMED"));
break;
default:
LOG(("UNKNOWN"));
break;
}
LOG((" (error = 0x%08x).\n", spc->spc_error));
}
void
DataChannelConnection::HandleRemoteErrorEvent(const struct sctp_remote_error *sre)
{
size_t i, n;
n = sre->sre_length - sizeof(struct sctp_remote_error);
LOG(("Remote Error (error = 0x%04x): ", sre->sre_error));
for (i = 0; i < n; ++i) {
LOG((" 0x%02x", sre-> sre_data[i]));
}
}
void
DataChannelConnection::HandleShutdownEvent(const struct sctp_shutdown_event *sse)
{
LOG(("Shutdown event."));
/* XXX: notify all channels. */
// Attempts to actually send anything will fail
}
void
DataChannelConnection::HandleAdaptationIndication(const struct sctp_adaptation_event *sai)
{
LOG(("Adaptation indication: %x.", sai-> sai_adaptation_ind));
}
void
DataChannelConnection::HandlePartialDeliveryEvent(const struct sctp_pdapi_event *spde)
{
// Note: Be aware that stream and sequence number being u32 instead of u16 is
// a bug in the SCTP API. This may change in the future.
LOG(("Partial delivery event: "));
switch (spde->pdapi_indication) {
case SCTP_PARTIAL_DELIVERY_ABORTED:
LOG(("delivery aborted "));
break;
default:
LOG(("??? "));
break;
}
LOG(("(flags = %x), stream = %" PRIu32 ", sn = %" PRIu32, spde->pdapi_flags, spde->pdapi_stream,
spde->pdapi_seq));
// Validate stream ID
if (spde->pdapi_stream >= UINT16_MAX) {
LOG(("Invalid stream id in partial delivery event: %" PRIu32 "\n", spde->pdapi_stream));
return;
}
// Find channel and reset buffer
DataChannel *channel = FindChannelByStream((uint16_t)spde->pdapi_stream);
if (channel) {
LOG(("Abort partially delivered message of %u bytes\n", channel->mRecvBuffer.Length()));
channel->mRecvBuffer.Truncate(0);
}
}
void
DataChannelConnection::HandleSendFailedEvent(const struct sctp_send_failed_event *ssfe)
{
size_t i, n;
if (ssfe->ssfe_flags & SCTP_DATA_UNSENT) {
LOG(("Unsent "));
}
if (ssfe->ssfe_flags & SCTP_DATA_SENT) {
LOG(("Sent "));
}
if (ssfe->ssfe_flags & ~(SCTP_DATA_SENT | SCTP_DATA_UNSENT)) {
LOG(("(flags = %x) ", ssfe->ssfe_flags));
}
LOG(("message with PPID = %u, SID = %d, flags: 0x%04x due to error = 0x%08x",
ntohl(ssfe->ssfe_info.snd_ppid), ssfe->ssfe_info.snd_sid,
ssfe->ssfe_info.snd_flags, ssfe->ssfe_error));
n = ssfe->ssfe_length - sizeof(struct sctp_send_failed_event);
for (i = 0; i < n; ++i) {
LOG((" 0x%02x", ssfe->ssfe_data[i]));
}
}
void
DataChannelConnection::ClearResets()
{
// Clear all pending resets
if (!mStreamsResetting.IsEmpty()) {
LOG(("Clearing resets for %zu streams", mStreamsResetting.Length()));
}
for (uint32_t i = 0; i < mStreamsResetting.Length(); ++i) {
RefPtr<DataChannel> channel;
channel = FindChannelByStream(mStreamsResetting[i]);
if (channel) {
LOG(("Forgetting channel %u (%p) with pending reset",channel->mStream, channel.get()));
mStreams[channel->mStream] = nullptr;
}
}
mStreamsResetting.Clear();
}
void
DataChannelConnection::ResetOutgoingStream(uint16_t stream)
{
uint32_t i;
mLock.AssertCurrentThreadOwns();
LOG(("Connection %p: Resetting outgoing stream %u",
(void *) this, stream));
// Rarely has more than a couple items and only for a short time
for (i = 0; i < mStreamsResetting.Length(); ++i) {
if (mStreamsResetting[i] == stream) {
return;
}
}
mStreamsResetting.AppendElement(stream);
}
void
DataChannelConnection::SendOutgoingStreamReset()
{
struct sctp_reset_streams *srs;
uint32_t i;
size_t len;
LOG(("Connection %p: Sending outgoing stream reset for %zu streams",
(void *) this, mStreamsResetting.Length()));
mLock.AssertCurrentThreadOwns();
if (mStreamsResetting.IsEmpty()) {
LOG(("No streams to reset"));
return;
}
len = sizeof(sctp_assoc_t) + (2 + mStreamsResetting.Length()) * sizeof(uint16_t);
srs = static_cast<struct sctp_reset_streams *> (moz_xmalloc(len)); // infallible malloc
memset(srs, 0, len);
srs->srs_flags = SCTP_STREAM_RESET_OUTGOING;
srs->srs_number_streams = mStreamsResetting.Length();
for (i = 0; i < mStreamsResetting.Length(); ++i) {
srs->srs_stream_list[i] = mStreamsResetting[i];
}
if (usrsctp_setsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_RESET_STREAMS, srs, (socklen_t)len) < 0) {
LOG(("***failed: setsockopt RESET, errno %d", errno));
// if errno == EALREADY, this is normal - we can't send another reset
// with one pending.
// When we get an incoming reset (which may be a response to our
// outstanding one), see if we have any pending outgoing resets and
// send them
} else {
mStreamsResetting.Clear();
}
free(srs);
}
void
DataChannelConnection::HandleStreamResetEvent(const struct sctp_stream_reset_event *strrst)
{
uint32_t n, i;
RefPtr<DataChannel> channel; // since we may null out the ref to the channel
if (!(strrst->strreset_flags & SCTP_STREAM_RESET_DENIED) &&
!(strrst->strreset_flags & SCTP_STREAM_RESET_FAILED)) {
n = (strrst->strreset_length - sizeof(struct sctp_stream_reset_event)) / sizeof(uint16_t);
for (i = 0; i < n; ++i) {
if (strrst->strreset_flags & SCTP_STREAM_RESET_INCOMING_SSN) {
channel = FindChannelByStream(strrst->strreset_stream_list[i]);
if (channel) {
// The other side closed the channel
// We could be in three states:
// 1. Normal state (input and output streams (OPEN)
// Notify application, send a RESET in response on our
// outbound channel. Go to CLOSED
// 2. We sent our own reset (CLOSING); either they crossed on the
// wire, or this is a response to our Reset.
// Go to CLOSED
// 3. We've sent a open but haven't gotten a response yet (CONNECTING)
// I believe this is impossible, as we don't have an input stream yet.
LOG(("Incoming: Channel %u closed, state %d",
channel->mStream, channel->mState));
ASSERT_WEBRTC(channel->mState == DataChannel::OPEN ||
channel->mState == DataChannel::CLOSING ||
channel->mState == DataChannel::CONNECTING ||
channel->mState == DataChannel::WAITING_TO_OPEN);
if (channel->mState == DataChannel::OPEN ||
channel->mState == DataChannel::WAITING_TO_OPEN) {
// Mark the stream for reset (the reset is sent below)
ResetOutgoingStream(channel->mStream);
}
mStreams[channel->mStream] = nullptr;
LOG(("Disconnected DataChannel %p from connection %p",
(void *) channel.get(), (void *) channel->mConnection.get()));
// This sends ON_CHANNEL_CLOSED to mainthread
channel->StreamClosedLocked();
} else {
LOG(("Can't find incoming channel %d",i));
}
}
}
}
// Process any pending resets now:
if (!mStreamsResetting.IsEmpty()) {
LOG(("Sending %zu pending resets", mStreamsResetting.Length()));
SendOutgoingStreamReset();
}
}
void
DataChannelConnection::HandleStreamChangeEvent(const struct sctp_stream_change_event *strchg)
{
uint16_t stream;
RefPtr<DataChannel> channel;
if (strchg->strchange_flags == SCTP_STREAM_CHANGE_DENIED) {
LOG(("*** Failed increasing number of streams from %zu (%u/%u)",
mStreams.Length(),
strchg->strchange_instrms,
strchg->strchange_outstrms));
// XXX FIX! notify pending opens of failure
return;
}
if (strchg->strchange_instrms > mStreams.Length()) {
LOG(("Other side increased streams from %zu to %u",
mStreams.Length(), strchg->strchange_instrms));
}
if (strchg->strchange_outstrms > mStreams.Length() ||
strchg->strchange_instrms > mStreams.Length()) {
uint16_t old_len = mStreams.Length();
uint16_t new_len = std::max(strchg->strchange_outstrms,
strchg->strchange_instrms);
LOG(("Increasing number of streams from %u to %u - adding %u (in: %u)",
old_len, new_len, new_len - old_len,
strchg->strchange_instrms));
// make sure both are the same length
mStreams.AppendElements(new_len - old_len);
LOG(("New length = %zu (was %d)", mStreams.Length(), old_len));
for (size_t i = old_len; i < mStreams.Length(); ++i) {
mStreams[i] = nullptr;
}
// Re-process any channels waiting for streams.
// Linear search, but we don't increase channels often and
// the array would only get long in case of an app error normally
// Make sure we request enough streams if there's a big jump in streams
// Could make a more complex API for OpenXxxFinish() and avoid this loop
size_t num_needed = mPending.GetSize();
LOG(("%zu of %d new streams already needed", num_needed,
new_len - old_len));
num_needed -= (new_len - old_len); // number we added
if (num_needed > 0) {
if (num_needed < 16)
num_needed = 16;
LOG(("Not enough new streams, asking for %zu more", num_needed));
// TODO: parameter is an int32_t but we pass size_t
RequestMoreStreams(num_needed);
} else if (strchg->strchange_outstrms < strchg->strchange_instrms) {
LOG(("Requesting %d output streams to match partner",
strchg->strchange_instrms - strchg->strchange_outstrms));
RequestMoreStreams(strchg->strchange_instrms - strchg->strchange_outstrms);
}
ProcessQueuedOpens();
}
// else probably not a change in # of streams
for (uint32_t i = 0; i < mStreams.Length(); ++i) {
channel = mStreams[i];
if (!channel)
continue;
if ((channel->mState == CONNECTING) &&
(channel->mStream == INVALID_STREAM)) {
if ((strchg->strchange_flags & SCTP_STREAM_CHANGE_DENIED) ||
(strchg->strchange_flags & SCTP_STREAM_CHANGE_FAILED)) {
/* XXX: Signal to the other end. */
channel->mState = CLOSED;
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CHANNEL_CLOSED, this,
channel)));
// maybe fire onError (bug 843625)
} else {
stream = FindFreeStream();
if (stream != INVALID_STREAM) {
channel->mStream = stream;
mStreams[stream] = channel;
// Send open request
int error = SendOpenRequestMessage(
channel->mLabel, channel->mProtocol, channel->mStream,
!!(channel->mFlags & DATA_CHANNEL_FLAGS_OUT_OF_ORDER_ALLOWED), channel->mPrPolicy,
channel->mPrValue);
if (error) {
LOG(("SendOpenRequest failed, error = %d", error));
// Close the channel, inform the user
mStreams[channel->mStream] = nullptr;
channel->mState = CLOSED;
// Don't need to reset; we didn't open it
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CHANNEL_CLOSED, this,
channel)));
} else {
channel->mState = OPEN;
channel->mFlags |= DATA_CHANNEL_FLAGS_READY;
LOG(("%s: sending ON_CHANNEL_OPEN for %p", __FUNCTION__, channel.get()));
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CHANNEL_OPEN, this,
channel)));
}
} else {
/* We will not find more ... */
break;
}
}
}
}
}
// Called with mLock locked!
void
DataChannelConnection::HandleNotification(const union sctp_notification *notif, size_t n)
{
mLock.AssertCurrentThreadOwns();
if (notif->sn_header.sn_length != (uint32_t)n) {
return;
}
switch (notif->sn_header.sn_type) {
case SCTP_ASSOC_CHANGE:
HandleAssociationChangeEvent(&(notif->sn_assoc_change));
break;
case SCTP_PEER_ADDR_CHANGE:
HandlePeerAddressChangeEvent(&(notif->sn_paddr_change));
break;
case SCTP_REMOTE_ERROR:
HandleRemoteErrorEvent(&(notif->sn_remote_error));
break;
case SCTP_SHUTDOWN_EVENT:
HandleShutdownEvent(&(notif->sn_shutdown_event));
break;
case SCTP_ADAPTATION_INDICATION:
HandleAdaptationIndication(&(notif->sn_adaptation_event));
break;
case SCTP_AUTHENTICATION_EVENT:
LOG(("SCTP_AUTHENTICATION_EVENT"));
break;
case SCTP_SENDER_DRY_EVENT:
//LOG(("SCTP_SENDER_DRY_EVENT"));
break;
case SCTP_NOTIFICATIONS_STOPPED_EVENT:
LOG(("SCTP_NOTIFICATIONS_STOPPED_EVENT"));
break;
case SCTP_PARTIAL_DELIVERY_EVENT:
HandlePartialDeliveryEvent(&(notif->sn_pdapi_event));
break;
case SCTP_SEND_FAILED_EVENT:
HandleSendFailedEvent(&(notif->sn_send_failed_event));
break;
case SCTP_STREAM_RESET_EVENT:
HandleStreamResetEvent(&(notif->sn_strreset_event));
break;
case SCTP_ASSOC_RESET_EVENT:
LOG(("SCTP_ASSOC_RESET_EVENT"));
break;
case SCTP_STREAM_CHANGE_EVENT:
HandleStreamChangeEvent(&(notif->sn_strchange_event));
break;
default:
LOG(("unknown SCTP event: %u", (uint32_t)notif->sn_header.sn_type));
break;
}
}
int
DataChannelConnection::ReceiveCallback(struct socket* sock, void *data, size_t datalen,
struct sctp_rcvinfo rcv, int flags)
{
ASSERT_WEBRTC(!NS_IsMainThread());
if (!data) {
LOG(("ReceiveCallback: SCTP has finished shutting down"));
} else {
mLock.AssertCurrentThreadOwns();
if (flags & MSG_NOTIFICATION) {
HandleNotification(static_cast<union sctp_notification *>(data), datalen);
} else {
HandleMessage(data, datalen, ntohl(rcv.rcv_ppid), rcv.rcv_sid, flags);
}
}
// sctp allocates 'data' with malloc(), and expects the receiver to free
// it (presumably with free).
// XXX future optimization: try to deliver messages without an internal
// alloc/copy, and if so delay the free until later.
free(data);
// usrsctp defines the callback as returning an int, but doesn't use it
return 1;
}
already_AddRefed<DataChannel>
DataChannelConnection::Open(const nsACString& label, const nsACString& protocol,
Type type, bool inOrder,
uint32_t prValue, DataChannelListener *aListener,
nsISupports *aContext, bool aExternalNegotiated,
uint16_t aStream)
{
// aStream == INVALID_STREAM to have the protocol allocate
uint16_t prPolicy = SCTP_PR_SCTP_NONE;
uint32_t flags;
LOG(("DC Open: label %s/%s, type %u, inorder %d, prValue %u, listener %p, context %p, external: %s, stream %u",
PromiseFlatCString(label).get(), PromiseFlatCString(protocol).get(),
type, inOrder, prValue, aListener, aContext,
aExternalNegotiated ? "true" : "false", aStream));
switch (type) {
case DATA_CHANNEL_RELIABLE:
prPolicy = SCTP_PR_SCTP_NONE;
break;
case DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT:
prPolicy = SCTP_PR_SCTP_RTX;
break;
case DATA_CHANNEL_PARTIAL_RELIABLE_TIMED:
prPolicy = SCTP_PR_SCTP_TTL;
break;
default:
LOG(("ERROR: unsupported channel type: %u", type));
MOZ_ASSERT(false);
return nullptr;
}
if ((prPolicy == SCTP_PR_SCTP_NONE) && (prValue != 0)) {
return nullptr;
}
// Don't look past currently-negotiated streams
if (aStream != INVALID_STREAM && aStream < mStreams.Length() && mStreams[aStream]) {
LOG(("ERROR: external negotiation of already-open channel %u", aStream));
// XXX How do we indicate this up to the application? Probably the
// caller's job, but we may need to return an error code.
return nullptr;
}
flags = !inOrder ? DATA_CHANNEL_FLAGS_OUT_OF_ORDER_ALLOWED : 0;
RefPtr<DataChannel> channel(new DataChannel(this,
aStream,
DataChannel::CONNECTING,
label, protocol,
prPolicy, prValue,
flags,
aListener, aContext));
if (aExternalNegotiated) {
channel->mFlags |= DATA_CHANNEL_FLAGS_EXTERNAL_NEGOTIATED;
}
MutexAutoLock lock(mLock); // OpenFinish assumes this
return OpenFinish(channel.forget());
}
// Separate routine so we can also call it to finish up from pending opens
already_AddRefed<DataChannel>
DataChannelConnection::OpenFinish(already_AddRefed<DataChannel>&& aChannel)
{
RefPtr<DataChannel> channel(aChannel); // takes the reference passed in
// Normally 1 reference if called from ::Open(), or 2 if called from
// ProcessQueuedOpens() unless the DOMDataChannel was gc'd
uint16_t stream = channel->mStream;
bool queue = false;
mLock.AssertCurrentThreadOwns();
// Cases we care about:
// Pre-negotiated:
// Not Open:
// Doesn't fit:
// -> change initial ask or renegotiate after open
// -> queue open
// Open:
// Doesn't fit:
// -> RequestMoreStreams && queue
// Does fit:
// -> open
// Not negotiated:
// Not Open:
// -> queue open
// Open:
// -> Try to get a stream
// Doesn't fit:
// -> RequestMoreStreams && queue
// Does fit:
// -> open
// So the Open cases are basically the same
// Not Open cases are simply queue for non-negotiated, and
// either change the initial ask or possibly renegotiate after open.
if (mState == OPEN) {
if (stream == INVALID_STREAM) {
stream = FindFreeStream(); // may be INVALID_STREAM if we need more
}
if (stream == INVALID_STREAM || stream >= mStreams.Length()) {
// RequestMoreStreams() limits to MAX_NUM_STREAMS -- allocate extra streams
// to avoid going back immediately for more if the ask to N, N+1, etc
int32_t more_needed = (stream == INVALID_STREAM) ? 16 :
(stream-((int32_t)mStreams.Length())) + 16;
if (!RequestMoreStreams(more_needed)) {
// Something bad happened... we're done
goto request_error_cleanup;
}
queue = true;
}
} else {
// not OPEN
if (stream != INVALID_STREAM && stream >= mStreams.Length() &&
mState == CLOSED) {
// Update number of streams for init message
struct sctp_initmsg initmsg;
socklen_t len = sizeof(initmsg);
int32_t total_needed = stream+16;
memset(&initmsg, 0, sizeof(initmsg));
if (usrsctp_getsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_INITMSG, &initmsg, &len) < 0) {
LOG(("*** failed getsockopt SCTP_INITMSG"));
goto request_error_cleanup;
}
LOG(("Setting number of SCTP streams to %u, was %u/%u", total_needed,
initmsg.sinit_num_ostreams, initmsg.sinit_max_instreams));
initmsg.sinit_num_ostreams = total_needed;
initmsg.sinit_max_instreams = MAX_NUM_STREAMS;
if (usrsctp_setsockopt(mMasterSocket, IPPROTO_SCTP, SCTP_INITMSG, &initmsg,
(socklen_t)sizeof(initmsg)) < 0) {
LOG(("*** failed setsockopt SCTP_INITMSG, errno %d", errno));
goto request_error_cleanup;
}
int32_t old_len = mStreams.Length();
mStreams.AppendElements(total_needed - old_len);
for (int32_t i = old_len; i < total_needed; ++i) {
mStreams[i] = nullptr;
}
}
// else if state is CONNECTING, we'll just re-negotiate when OpenFinish
// is called, if needed
queue = true;
}
if (queue) {
LOG(("Queuing channel %p (%u) to finish open", channel.get(), stream));
// Also serves to mark we told the app
channel->mFlags |= DATA_CHANNEL_FLAGS_FINISH_OPEN;
// we need a ref for the nsDeQue and one to return
DataChannel* rawChannel = channel;
rawChannel->AddRef();
mPending.Push(rawChannel);
return channel.forget();
}
MOZ_ASSERT(stream != INVALID_STREAM);
// just allocated (& OPEN), or externally negotiated
mStreams[stream] = channel; // holds a reference
channel->mStream = stream;
#ifdef TEST_QUEUED_DATA
// It's painful to write a test for this...
channel->mState = OPEN;
channel->mFlags |= DATA_CHANNEL_FLAGS_READY;
SendDataMsgInternalOrBuffer(channel, "Help me!", 8, DATA_CHANNEL_PPID_DOMSTRING);
#endif
if (channel->mFlags & DATA_CHANNEL_FLAGS_OUT_OF_ORDER_ALLOWED) {
// Don't send unordered until this gets cleared
channel->mFlags |= DATA_CHANNEL_FLAGS_WAITING_ACK;
}
if (!(channel->mFlags & DATA_CHANNEL_FLAGS_EXTERNAL_NEGOTIATED)) {
int error = SendOpenRequestMessage(
channel->mLabel, channel->mProtocol, stream,
!!(channel->mFlags & DATA_CHANNEL_FLAGS_OUT_OF_ORDER_ALLOWED), channel->mPrPolicy,
channel->mPrValue);
if (error) {
LOG(("SendOpenRequest failed, error = %d", error));
if (channel->mFlags & DATA_CHANNEL_FLAGS_FINISH_OPEN) {
// We already returned the channel to the app.
NS_ERROR("Failed to send open request");
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CHANNEL_CLOSED, this,
channel)));
}
// If we haven't returned the channel yet, it will get destroyed when we exit
// this function.
mStreams[stream] = nullptr;
channel->mStream = INVALID_STREAM;
// we'll be destroying the channel
channel->mState = CLOSED;
return nullptr;
/* NOTREACHED */
}
}
// Either externally negotiated or we sent Open
channel->mState = OPEN;
channel->mFlags |= DATA_CHANNEL_FLAGS_READY;
// FIX? Move into DOMDataChannel? I don't think we can send it yet here
LOG(("%s: sending ON_CHANNEL_OPEN for %p", __FUNCTION__, channel.get()));
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CHANNEL_OPEN, this,
channel)));
return channel.forget();
request_error_cleanup:
channel->mState = CLOSED;
if (channel->mFlags & DATA_CHANNEL_FLAGS_FINISH_OPEN) {
// We already returned the channel to the app.
NS_ERROR("Failed to request more streams");
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CHANNEL_CLOSED, this,
channel)));
return channel.forget();
}
// we'll be destroying the channel, but it never really got set up
// Alternative would be to RUN_ON_THREAD(channel.forget(),::Destroy,...) and
// Dispatch it to ourselves
return nullptr;
}
// Requires mLock to be locked!
// Returns a POSIX error code directly instead of setting errno.
int
DataChannelConnection::SendMsgInternal(OutgoingMsg &msg)
{
auto &info = msg.GetInfo().sendv_sndinfo;
int error;
// EOR set?
bool eor_set = info.snd_flags & SCTP_EOR ? true : false;
// Send until buffer is empty
size_t left = msg.GetLeft();
do {
size_t length;
// Carefully chunk the buffer
if (left > DATA_CHANNEL_MAX_BINARY_FRAGMENT) {
length = DATA_CHANNEL_MAX_BINARY_FRAGMENT;
// Unset EOR flag
info.snd_flags &= ~SCTP_EOR;
} else {
length = left;
// Set EOR flag
if (eor_set) {
info.snd_flags |= SCTP_EOR;
}
}
// Send (or try at least)
// SCTP will return EMSGSIZE if the message is bigger than the buffer
// size (or EAGAIN if there isn't space). However, we can avoid EMSGSIZE
// by carefully crafting small enough message chunks.
ssize_t written = usrsctp_sendv(
mSocket, msg.GetData(), length, nullptr, 0,
(void *)&msg.GetInfo(), (socklen_t)sizeof(struct sctp_sendv_spa),
SCTP_SENDV_SPA, 0);
if (written < 0) {
error = errno;
goto out;
}
LOG(("Sent buffer (written=%zu, len=%zu, left=%zu)",
(size_t)written, length, left - (size_t)written));
// TODO: Remove once resolved (https://github.com/sctplab/usrsctp/issues/132)
if (written == 0) {
LOG(("@tuexen: usrsctp_sendv returned 0"));
error = EAGAIN;
goto out;
}
// If not all bytes have been written, this obviously means that usrsctp's buffer is full
// and we need to try again later.
if ((size_t)written < length) {
msg.Advance((size_t)written);
error = EAGAIN;
goto out;
}
// Update buffer position
msg.Advance((size_t)written);
// Get amount of bytes left in the buffer
left = msg.GetLeft();
} while (left > 0);
// Done
error = 0;
out:
// Reset EOR flag
if (eor_set) {
info.snd_flags |= SCTP_EOR;
}
return error;
}
// Requires mLock to be locked!
// Returns a POSIX error code directly instead of setting errno.
// IMPORTANT: Ensure that the buffer passed is guarded by mLock!
int
DataChannelConnection::SendMsgInternalOrBuffer(nsTArray<nsAutoPtr<BufferedOutgoingMsg>> &buffer,
OutgoingMsg &msg, bool &buffered)
{
NS_WARNING_ASSERTION(msg.GetLength() > 0, "Length is 0?!");
int error = 0;
bool need_buffering = false;
// Note: Main-thread IO, but doesn't block!
// XXX FIX! to deal with heavy overruns of JS trying to pass data in
// (more than the buffersize) queue data onto another thread to do the
// actual sends. See netwerk/protocol/websocket/WebSocketChannel.cpp
// Avoid a race between buffer-full-failure (where we have to add the
// packet to the buffered-data queue) and the buffer-now-only-half-full
// callback, which happens on a different thread. Otherwise we might
// fail here, then before we add it to the queue get the half-full
// callback, find nothing to do, then on this thread add it to the
// queue - which would sit there. Also, if we later send more data, it
// would arrive ahead of the buffered message, but if the buffer ever
// got to 1/2 full, the message would get sent - but at a semi-random
// time, after other data it was supposed to be in front of.
// Must lock before empty check for similar reasons!
mLock.AssertCurrentThreadOwns();
if (buffer.IsEmpty() && (mSendInterleaved || !mPendingType)) {
error = SendMsgInternal(msg);
switch (error) {
case 0:
break;
case EAGAIN:
#if (EAGAIN != EWOULDBLOCK)
case EWOULDBLOCK:
#endif
need_buffering = true;
break;
default:
LOG(("error %d on sending", error));
break;
}
} else {
need_buffering = true;
}
if (need_buffering) {
// queue data for resend! And queue any further data for the stream until it is...
auto *bufferedMsg = new BufferedOutgoingMsg(msg); // infallible malloc
buffer.AppendElement(bufferedMsg); // owned by mBufferedData array
LOG(("Queued %zu buffers (left=%zu, total=%zu)",
buffer.Length(), msg.GetLeft(), msg.GetLength()));
buffered = true;
return 0;
}
buffered = false;
return error;
}
// Caller must ensure that length <= UINT32_MAX
// Returns a POSIX error code.
int
DataChannelConnection::SendDataMsgInternalOrBuffer(DataChannel &channel, const uint8_t *data,
size_t len, uint32_t ppid)
{
if (NS_WARN_IF(channel.mState != OPEN && channel.mState != CONNECTING)) {
return EINVAL; // TODO: Find a better error code
}
struct sctp_sendv_spa info = {0};
// General flags
info.sendv_flags = SCTP_SEND_SNDINFO_VALID;
// Set stream identifier, protocol identifier and flags
info.sendv_sndinfo.snd_sid = channel.mStream;
info.sendv_sndinfo.snd_flags = SCTP_EOR;
info.sendv_sndinfo.snd_ppid = htonl(ppid);
// Unordered?
// To avoid problems where an in-order OPEN is lost and an
// out-of-order data message "beats" it, require data to be in-order
// until we get an ACK.
if ((channel.mFlags & DATA_CHANNEL_FLAGS_OUT_OF_ORDER_ALLOWED) &&
!(channel.mFlags & DATA_CHANNEL_FLAGS_WAITING_ACK)) {
info.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
}
// Partial reliability policy
if (channel.mPrPolicy != SCTP_PR_SCTP_NONE) {
info.sendv_prinfo.pr_policy = channel.mPrPolicy;
info.sendv_prinfo.pr_value = channel.mPrValue;
info.sendv_flags |= SCTP_SEND_PRINFO_VALID;
}
// Create message instance and send
OutgoingMsg msg(info, data, len);
MutexAutoLock lock(mLock);
bool buffered;
int error = SendMsgInternalOrBuffer(channel.mBufferedData, msg, buffered);
// Set pending type and stream index (if buffered)
if (!error && buffered && !mPendingType) {
mPendingType = PENDING_DATA;
mCurrentStream = channel.mStream;
}
return error;
}
// Caller must ensure that length <= UINT32_MAX
// Returns a POSIX error code.
int
DataChannelConnection::SendDataMsg(DataChannel &channel, const uint8_t *data, size_t len,
uint32_t ppidPartial, uint32_t ppidFinal)
{
// We *really* don't want to do this from main thread! - and
// SendDataMsgInternalOrBuffer avoids blocking.
if (mPpidFragmentation) {
// TODO: Bug 1381136, remove this block and all other code that uses PPIDs for fragmentation
// and reassembly once older Firefoxes without EOR are no longer supported as target
// clients.
// Use the deprecated PPID-level fragmentation if enabled. Should be enabled
// in case we can be certain that the other peer is an older Firefox browser
// that does support PPID-level fragmentation/reassembly.
// PPID-level fragmentation can only be applied on reliable data channels.
if (len > DATA_CHANNEL_MAX_BINARY_FRAGMENT &&
channel.mPrPolicy == DATA_CHANNEL_RELIABLE &&
!(channel.mFlags & DATA_CHANNEL_FLAGS_OUT_OF_ORDER_ALLOWED)) {
LOG(("Sending data message (total=%zu) using deprecated PPID-based chunks", len));
size_t left = len;
while (left > 0) {
// Note: For correctness, chunkLen should also consider mMaxMessageSize as minimum but as
// this block is going to be removed soon, I see no need for it.
size_t chunkLen = std::min<size_t>(left, DATA_CHANNEL_MAX_BINARY_FRAGMENT);
left -= chunkLen;
uint32_t ppid = left > 0 ? ppidPartial : ppidFinal;
// Send the chunk
// Note that these might end up being deferred and queued.
LOG(("Send chunk (len=%zu, left=%zu, total=%zu, ppid %u",
chunkLen, left, len, ppid));
int error = SendDataMsgInternalOrBuffer(channel, data, chunkLen, ppid);
if (error) {
LOG(("*** send chunk fail %d", error));
return error;
}
// Update data position
data += chunkLen;
}
// Sending chunks complete
LOG(("Sent %zu chunks using deprecated PPID-based fragmentation",
(size_t)(len+DATA_CHANNEL_MAX_BINARY_FRAGMENT-1)/DATA_CHANNEL_MAX_BINARY_FRAGMENT));
return 0;
}
// Cannot do PPID-based fragmentaton on unreliable channels
NS_WARNING_ASSERTION(len <= DATA_CHANNEL_MAX_BINARY_FRAGMENT,
"Sending too-large data on unreliable channel!");
} else {
if (mMaxMessageSize != 0 && len > mMaxMessageSize) {
LOG(("Message rejected, too large (%zu > %" PRIu64 ")", len, mMaxMessageSize));
return EMSGSIZE;
}
}
// This will use EOR-based fragmentation if the message is too large (> 64 KiB)
return SendDataMsgInternalOrBuffer(channel, data, len, ppidFinal);
}
class ReadBlobRunnable : public Runnable {
public:
ReadBlobRunnable(DataChannelConnection* aConnection,
uint16_t aStream,
nsIInputStream* aBlob)
: Runnable("ReadBlobRunnable")
, mConnection(aConnection)
, mStream(aStream)
, mBlob(aBlob)
{}
NS_IMETHOD Run() override {
// ReadBlob() is responsible to releasing the reference
DataChannelConnection *self = mConnection;
self->ReadBlob(mConnection.forget(), mStream, mBlob);
return NS_OK;
}
private:
// Make sure the Connection doesn't die while there are jobs outstanding.
// Let it die (if released by PeerConnectionImpl while we're running)
// when we send our runnable back to MainThread. Then ~DataChannelConnection
// can send the IOThread to MainThread to die in a runnable, avoiding
// unsafe event loop recursion. Evil.
RefPtr<DataChannelConnection> mConnection;
uint16_t mStream;
// Use RefCount for preventing the object is deleted when SendBlob returns.
RefPtr<nsIInputStream> mBlob;
};
// Returns a POSIX error code.
int
DataChannelConnection::SendBlob(uint16_t stream, nsIInputStream *aBlob)
{
DataChannel *channel = mStreams[stream];
if (NS_WARN_IF(!channel)) {
return EINVAL; // TODO: Find a better error code
}
// Spawn a thread to send the data
if (!mInternalIOThread) {
nsresult rv = NS_NewNamedThread("DataChannel IO",
getter_AddRefs(mInternalIOThread));
if (NS_FAILED(rv)) {
return EINVAL; // TODO: Find a better error code
}
}
mInternalIOThread->Dispatch(do_AddRef(new ReadBlobRunnable(this, stream, aBlob)), NS_DISPATCH_NORMAL);
return 0;
}
class DataChannelBlobSendRunnable : public Runnable
{
public:
DataChannelBlobSendRunnable(
already_AddRefed<DataChannelConnection>& aConnection,
uint16_t aStream)
: Runnable("DataChannelBlobSendRunnable")
, mConnection(aConnection)
, mStream(aStream)
{}
~DataChannelBlobSendRunnable() override
{
if (!NS_IsMainThread() && mConnection) {
MOZ_ASSERT(false);
// explicitly leak the connection if destroyed off mainthread
Unused << mConnection.forget().take();
}
}
NS_IMETHOD Run() override
{
ASSERT_WEBRTC(NS_IsMainThread());
mConnection->SendBinaryMsg(mStream, mData);
mConnection = nullptr;
return NS_OK;
}
// explicitly public so we can avoid allocating twice and copying
nsCString mData;
private:
// Note: we can be destroyed off the target thread, so be careful not to let this
// get Released()ed on the temp thread!
RefPtr<DataChannelConnection> mConnection;
uint16_t mStream;
};
void
DataChannelConnection::ReadBlob(already_AddRefed<DataChannelConnection> aThis,
uint16_t aStream, nsIInputStream* aBlob)
{
// NOTE: 'aThis' has been forgotten by the caller to avoid releasing
// it off mainthread; if PeerConnectionImpl has released then we want
// ~DataChannelConnection() to run on MainThread
// XXX to do this safely, we must enqueue these atomically onto the
// output socket. We need a sender thread(s?) to enqueue data into the
// socket and to avoid main-thread IO that might block. Even on a
// background thread, we may not want to block on one stream's data.
// I.e. run non-blocking and service multiple channels.
// Must not let Dispatching it cause the DataChannelConnection to get
// released on the wrong thread. Using WrapRunnable(RefPtr<DataChannelConnection>(aThis),...
// will occasionally cause aThis to get released on this thread. Also, an explicit Runnable
// lets us avoid copying the blob data an extra time.
RefPtr<DataChannelBlobSendRunnable> runnable = new DataChannelBlobSendRunnable(aThis,
aStream);
// avoid copying the blob data by passing the mData from the runnable
if (NS_FAILED(NS_ReadInputStreamToString(aBlob, runnable->mData, -1))) {
// Bug 966602: Doesn't return an error to the caller via onerror.
// We must release DataChannelConnection on MainThread to avoid issues (bug 876167)
// aThis is now owned by the runnable; release it there
NS_ReleaseOnMainThreadSystemGroup(
"DataChannelBlobSendRunnable", runnable.forget());
return;
}
aBlob->Close();
Dispatch(runnable.forget());
}
void
DataChannelConnection::GetStreamIds(std::vector<uint16_t>* aStreamList)
{
ASSERT_WEBRTC(NS_IsMainThread());
for (uint32_t i = 0; i < mStreams.Length(); ++i) {
if (mStreams[i]) {
aStreamList->push_back(mStreams[i]->mStream);
}
}
}
// Returns a POSIX error code.
int
DataChannelConnection::SendDataMsgCommon(uint16_t stream, const nsACString &aMsg,
bool isBinary)
{
ASSERT_WEBRTC(NS_IsMainThread());
// We really could allow this from other threads, so long as we deal with
// asynchronosity issues with channels closing, in particular access to
// mStreams, and issues with the association closing (access to mSocket).
const uint8_t *data = (const uint8_t *)aMsg.BeginReading();
uint32_t len = aMsg.Length();
#if (UINT32_MAX > SIZE_MAX)
if (len > SIZE_MAX) {
return EMSGSIZE;
}
#endif
DataChannel *channelPtr;
LOG(("Sending %sto stream %u: %u bytes", isBinary ? "binary " : "", stream, len));
// XXX if we want more efficiency, translate flags once at open time
channelPtr = mStreams[stream];
if (NS_WARN_IF(!channelPtr)) {
return EINVAL; // TODO: Find a better error code
}
auto &channel = *channelPtr;
if (isBinary) {
return SendDataMsg(channel, data, len,
DATA_CHANNEL_PPID_BINARY_PARTIAL, DATA_CHANNEL_PPID_BINARY);
}
return SendDataMsg(channel, data, len,
DATA_CHANNEL_PPID_DOMSTRING_PARTIAL, DATA_CHANNEL_PPID_DOMSTRING);
}
void
DataChannelConnection::Stop()
{
// Note: This will call 'CloseAll' from the main thread
Dispatch(do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_DISCONNECTED,
this)));
}
void
DataChannelConnection::Close(DataChannel *aChannel)
{
MutexAutoLock lock(mLock);
CloseInt(aChannel);
}
// So we can call Close() with the lock already held
// Called from someone who holds a ref via ::Close(), or from ~DataChannel
void
DataChannelConnection::CloseInt(DataChannel *aChannel)
{
MOZ_ASSERT(aChannel);
RefPtr<DataChannel> channel(aChannel); // make sure it doesn't go away on us
mLock.AssertCurrentThreadOwns();
LOG(("Connection %p/Channel %p: Closing stream %u",
channel->mConnection.get(), channel.get(), channel->mStream));
// re-test since it may have closed before the lock was grabbed
if (aChannel->mState == CLOSED || aChannel->mState == CLOSING) {
LOG(("Channel already closing/closed (%u)", aChannel->mState));
if (mState == CLOSED && channel->mStream != INVALID_STREAM) {
// called from CloseAll()
// we're not going to hang around waiting any more
mStreams[channel->mStream] = nullptr;
}
return;
}
aChannel->mBufferedData.Clear();
if (channel->mStream != INVALID_STREAM) {
ResetOutgoingStream(channel->mStream);
if (mState == CLOSED) { // called from CloseAll()
// Let resets accumulate then send all at once in CloseAll()
// we're not going to hang around waiting
mStreams[channel->mStream] = nullptr;
} else {
SendOutgoingStreamReset();
}
}
aChannel->mState = CLOSING;
if (mState == CLOSED) {
// we're not going to hang around waiting
channel->StreamClosedLocked();
}
// At this point when we leave here, the object is a zombie held alive only by the DOM object
}
void DataChannelConnection::CloseAll()
{
LOG(("Closing all channels (connection %p)", (void*) this));
// Don't need to lock here
// Make sure no more channels will be opened
{
MutexAutoLock lock(mLock);
mState = CLOSED;
}
// Close current channels
// If there are runnables, they hold a strong ref and keep the channel
// and/or connection alive (even if in a CLOSED state)
bool closed_some = false;
for (uint32_t i = 0; i < mStreams.Length(); ++i) {
if (mStreams[i]) {
mStreams[i]->Close();
closed_some = true;
}
}
// Clean up any pending opens for channels
RefPtr<DataChannel> channel;
while (nullptr != (channel = dont_AddRef(static_cast<DataChannel *>(mPending.PopFront())))) {
LOG(("closing pending channel %p, stream %u", channel.get(), channel->mStream));
channel->Close(); // also releases the ref on each iteration
closed_some = true;
}
// It's more efficient to let the Resets queue in shutdown and then
// SendOutgoingStreamReset() here.
if (closed_some) {
MutexAutoLock lock(mLock);
SendOutgoingStreamReset();
}
}
DataChannel::~DataChannel()
{
// NS_ASSERTION since this is more "I think I caught all the cases that
// can cause this" than a true kill-the-program assertion. If this is
// wrong, nothing bad happens. A worst it's a leak.
NS_ASSERTION(mState == CLOSED || mState == CLOSING, "unexpected state in ~DataChannel");
}
void
DataChannel::Close()
{
if (mConnection) {
// ensure we don't get deleted
RefPtr<DataChannelConnection> connection(mConnection);
connection->Close(this);
}
}
// Used when disconnecting from the DataChannelConnection
void
DataChannel::StreamClosedLocked()
{
mConnection->mLock.AssertCurrentThreadOwns();
ENSURE_DATACONNECTION;
LOG(("Destroying Data channel %u", mStream));
MOZ_ASSERT_IF(mStream != INVALID_STREAM,
!mConnection->FindChannelByStream(mStream));
mStream = INVALID_STREAM;
mState = CLOSED;
mMainThreadEventTarget->Dispatch(
do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CHANNEL_CLOSED,
mConnection, this)));
// We leave mConnection live until the DOM releases us, to avoid races
}
void
DataChannel::ReleaseConnection()
{
ASSERT_WEBRTC(NS_IsMainThread());
mConnection = nullptr;
}
void
DataChannel::SetListener(DataChannelListener *aListener, nsISupports *aContext)
{
MutexAutoLock mLock(mListenerLock);
mContext = aContext;
mListener = aListener;
}
void
DataChannel::SendErrnoToErrorResult(int error, ErrorResult& aRv)
{
switch (error) {
case 0:
break;
case EMSGSIZE:
aRv.Throw(NS_ERROR_DOM_TYPE_ERR);
break;
default:
aRv.Throw(NS_ERROR_DOM_OPERATION_ERR);
break;
}
}
void
DataChannel::SendMsg(const nsACString &aMsg, ErrorResult& aRv)
{
if (!EnsureValidStream(aRv)) {
return;
}
SendErrnoToErrorResult(mConnection->SendMsg(mStream, aMsg), aRv);
}
void
DataChannel::SendBinaryMsg(const nsACString &aMsg, ErrorResult& aRv)
{
if (!EnsureValidStream(aRv)) {
return;
}
SendErrnoToErrorResult(mConnection->SendBinaryMsg(mStream, aMsg), aRv);
}
void
DataChannel::SendBinaryStream(nsIInputStream *aBlob,ErrorResult& aRv)
{
if (!EnsureValidStream(aRv)) {
return;
}
SendErrnoToErrorResult(mConnection->SendBlob(mStream, aBlob), aRv);
}
// May be called from another (i.e. Main) thread!
void
DataChannel::AppReady()
{
ENSURE_DATACONNECTION;
MutexAutoLock lock(mConnection->mLock);
mFlags |= DATA_CHANNEL_FLAGS_READY;
if (mState == WAITING_TO_OPEN) {
mState = OPEN;
mMainThreadEventTarget->Dispatch(
do_AddRef(new DataChannelOnMessageAvailable(
DataChannelOnMessageAvailable::ON_CHANNEL_OPEN, mConnection,
this)));
for (uint32_t i = 0; i < mQueuedMessages.Length(); ++i) {
nsCOMPtr<nsIRunnable> runnable = mQueuedMessages[i];
MOZ_ASSERT(runnable);
mMainThreadEventTarget->Dispatch(runnable.forget());
}
} else {
NS_ASSERTION(mQueuedMessages.IsEmpty(), "Shouldn't have queued messages if not WAITING_TO_OPEN");
}
mQueuedMessages.Clear();
mQueuedMessages.Compact();
// We never use it again... We could even allocate the array in the odd
// cases we need it.
}
size_t
DataChannel::GetBufferedAmountLocked() const
{
size_t buffered = 0;
for (auto &msg : mBufferedData) {
buffered += msg->GetLeft();
}
// XXX Note: per Michael Tuexen, there's no way to currently get the buffered
// amount from the SCTP stack for a single stream. It is on their to-do
// list, and once we import a stack with support for that, we'll need to
// add it to what we buffer. Also we'll need to ask for notification of a per-
// stream buffer-low event and merge that into the handling of buffer-low
// (the equivalent to TCP_NOTSENT_LOWAT on TCP sockets)
return buffered;
}
uint32_t
DataChannel::GetBufferedAmountLowThreshold()
{
return mBufferedThreshold;
}
// Never fire immediately, as it's defined to fire on transitions, not state
void
DataChannel::SetBufferedAmountLowThreshold(uint32_t aThreshold)
{
mBufferedThreshold = aThreshold;
}
// Called with mLock locked!
void
DataChannel::SendOrQueue(DataChannelOnMessageAvailable *aMessage)
{
if (!(mFlags & DATA_CHANNEL_FLAGS_READY) &&
(mState == CONNECTING || mState == WAITING_TO_OPEN)) {
mQueuedMessages.AppendElement(aMessage);
} else {
nsCOMPtr<nsIRunnable> runnable = aMessage;
mMainThreadEventTarget->Dispatch(runnable.forget());
}
}
bool
DataChannel::EnsureValidStream(ErrorResult& aRv)
{
MOZ_ASSERT(mConnection);
if (mConnection && mStream != INVALID_STREAM) {
return true;
}
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return false;
}
} // namespace mozilla
| [
"jiangchang@jiangchangdeMacBook-Pro.local"
] | jiangchang@jiangchangdeMacBook-Pro.local |
983cc6bf28657c487672a70127f6f6fe744cea79 | b87a7c980819728ef5543e5e533db4f408b6d3b4 | /SourceCode/Cplus/Project1/Backup_New/Animation.h | e1f036f330bfac79aee8377c130ada0731f5a804 | [] | no_license | nitipat009/Project-1-Game | 10c0ea9bc0a3e92fc2e3ef0200c560621df14c39 | f580678c0db5e76dbdee10c5032e2dad1a919ceb | refs/heads/master | 2023-03-01T21:24:35.368554 | 2021-02-07T03:27:45 | 2021-02-07T03:27:45 | 336,690,776 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | h | #pragma once
#include"SFML/Graphics.hpp"
class Animation
{
public:
Animation(sf::Texture* texture,sf ::Vector2u imageCount,float switchTime,bool enemy);
~Animation();
void Update(int row, float deltaTime , bool isLeft, bool enemy);
public:
sf::IntRect uvRect;
private:
//sf::IntRect recta;
sf::Vector2u imageCount;
sf::Vector2u currentImage;
float totalTime;
float switchTime;
bool enemy;
};
| [
"77422675+nitipat009@users.noreply.github.com"
] | 77422675+nitipat009@users.noreply.github.com |
52d11673376b0d0b13eaea74279653017f76928f | 9cb416d345bcfe7669c5cada4b649fc94a32353f | /unit4/4.2_hash.txt/查询正整数是否出现.cpp | e803286fa245f94dc26c4320847645fad6bb8aa3 | [] | no_license | EchoDemo/algorithm-notes | 936f0a231956553a115111c2300fb8ca6bd72d73 | 7bbcbe5f225cb69ad71d4100c0bad2f942d1abbc | refs/heads/master | 2021-01-22T20:29:20.592984 | 2018-04-29T00:35:04 | 2018-04-29T00:35:04 | 85,328,097 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | cpp | //以空间换时间:
#include "stdafx.h"
#include<iostream>
#include<stdlib.h>
using namespace std;
const int maxn = 100010;
bool hashTable[maxn] = { false };
int main() {
int n, m, x;
cin >> n >> m;
for (int i = 0;i < n;i++) {
cin >> x;
hashTable[x] = true; //数字x出现过;
}
for (int i = 0;i < m;i++) {
cin >> x;
if (hashTable[x] == true) {
cout << "Yes\n";
}
else {
cout << "No\n";
}
}
system("pause");
return 0;
}
| [
"1761910310@qq.com"
] | 1761910310@qq.com |
3c94de69c764e5528ccbaf3f72c165241ac6ae0b | 062fe73aef5bd087e88320f0f8ce2023c0981713 | /RyujinrokuMobile/RyujinrokuMobile.NativeActivity/src/ReplaySceneCellUtils.cpp | 817e40d452d6c2e7438b1daaec90ad07ec257406 | [] | no_license | remicalsoft/RyujinrokuMobile | 762c1bc94ab2baf5ebb71ae392f2e1e75c9e9601 | c3bff61dbce2298890954b8bba32da4946c085f9 | refs/heads/master | 2021-05-17T07:39:42.961357 | 2020-04-01T14:42:27 | 2020-04-01T14:42:27 | 250,699,354 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,354 | cpp | #include "ReplaySceneCellUtils.h"
bool is1On(ReplayHeader *header) {
if (!header->isSpellPractice && header->stage == eStage1) {
return true;
}
return false;
}
bool is2On(ReplayHeader *header) {
if (!header->isSpellPractice) {
if (header->stage == eStage1 && header->clearStageN >= 1) {
return true;
}
if (header->stage == eStage2) {
return true;
}
}
return false;
}
bool is3On(ReplayHeader *header) {
if (!header->isSpellPractice) {
if (header->stage == eStage1 && header->clearStageN >= 2) {
return true;
}
if (header->stage == eStage3) {
return true;
}
}
return false;
}
bool is4On(ReplayHeader *header) {
if (!header->isSpellPractice) {
if (header->stage == eStage1 && header->clearStageN >= 3) {
return true;
}
if (header->stage == eStage4) {
return true;
}
}
return false;
}
bool is5On(ReplayHeader *header) {
if (!header->isSpellPractice) {
if (header->stage == eStage1 && header->clearStageN >= 4) {
return true;
}
if (header->stage == eStage5) {
return true;
}
}
return false;
}
bool is6On(ReplayHeader *header) {
if (!header->isSpellPractice) {
if (header->stage == eStageEX) {
return true;
}
}
return false;
}
bool is7On(ReplayHeader *header) {
if (!header->isSpellPractice) {
if (header->stage == eStagePH) {
return true;
}
}
return false;
}
| [
"remicalsoft@gmail.com"
] | remicalsoft@gmail.com |
140ace61bd3c81aed97c5ddc5561e8e9720107af | e339fc7061d6b47f4f8a78d617dc526a64d3ec6c | /native/main.cpp | b7e0c1753d954a81f571a7e91c607db2489d4e1f | [
"MIT"
] | permissive | hamuryen/RawImageVideoStreamer | 30ff33d622088e3a7f290bb6b2d0377acfade459 | b5be917925f754e2ed5c094a718f92499dc3b133 | refs/heads/master | 2020-05-20T00:13:55.031676 | 2019-05-22T08:13:41 | 2019-05-22T08:13:41 | 185,282,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 488 | cpp | #include <thread>
#include <chrono>
#include "VideoStreamer.h"
int main()
{
{
Streamer::VideoStreamer streamer(554, 1920, 1080, 25);
streamer.Run();
int color = 0;
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(40));
unsigned char* data = (unsigned char*)calloc(1, 1080 * 1920 * 3);
for (int i = color; i < (1080 * 1920 * 3); i += 3)
data[i] = 255;
color = (color + 1) % 3;
streamer.SetImage(data);
free(data);
}
}
return 0;
} | [
"burak.hamuryen@pro-line.com.tr"
] | burak.hamuryen@pro-line.com.tr |
74a007e332e462705df479d8b41dc11c9802065e | 6f22a079c0bda728d73a1fdaa6676ee3d634cc26 | /src/plugins/lmp/plugins/ppl/tests/parsertest.cpp | 3b679c170f8885fe426432804f0d3dfdbced761b | [
"BSL-1.0"
] | permissive | wyrover/leechcraft | 8446e4acccb0f12e61fe03e3b5cc83f116ddebb3 | 4b3127afca16010056ff612f406ede2bca66691e | refs/heads/master | 2021-01-19T16:18:36.901249 | 2017-04-14T04:25:15 | 2017-04-14T04:25:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,852 | cpp | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "parsertest.h"
#include <QtTest>
#include "parser.cpp"
QTEST_MAIN (LeechCraft::LMP::PPL::ParserTest)
QDebug operator<< (QDebug dbg, const Media::AudioInfo& info)
{
dbg.nospace () << "Media::AudioInfo { "
<< info.Artist_ << "; "
<< info.Album_ << "; "
<< info.Title_ << "; "
<< info.Genres_ << "; "
<< info.Length_ << "; "
<< info.Year_ << "; "
<< info.TrackNumber_ << "; "
<< info.Other_ << " }";
return dbg.space ();
}
namespace QTest
{
template<>
char* toString (const Media::IAudioScrobbler::BackdatedTracks_t::value_type& pair)
{
QString result;
QDebug { &result } << pair;
return qstrdup (result.toUtf8 ().constData ());
}
}
namespace LeechCraft
{
namespace LMP
{
namespace PPL
{
void ParserTest::testBasicParsing ()
{
const QString data = R"(
#TZ/UNKNOWN
Heart Of A Coward Severance Monstro 1 213 L 1470071135
)";
const auto& result = ParseData (data);
const Media::IAudioScrobbler::BackdatedTracks_t expected
{
{
Media::AudioInfo
{
"Heart Of A Coward",
"Severance",
"Monstro",
{},
213,
0,
1,
{}
},
QDateTime::fromTime_t (1470071135).toUTC ()
}
};
QCOMPARE (result, expected);
}
void ParserTest::testSkipping ()
{
const QString data = R"(
#AUDIOSCROBBLER/1.1
#TZ/UNKNOWN
#CLIENT/Rockbox sansaclipzip $Revision$
Heart Of A Coward Severance Monstro 1 213 S 1470071129
Heart Of A Coward Severance Monstro 1 213 L 1470071135
Heart Of A Coward Severance Prey 2 228 L 1470071375
Heart Of A Coward Severance Distance 3 238 S 470071603
Heart Of A Coward Severance Nauseam 4 218 L 1470072028
)";
const auto& result = ParseData (data);
const Media::IAudioScrobbler::BackdatedTracks_t expected
{
{
Media::AudioInfo
{
"Heart Of A Coward",
"Severance",
"Monstro",
{},
213,
0,
1,
{}
},
QDateTime::fromTime_t (1470071135).toUTC ()
},
{
Media::AudioInfo
{
"Heart Of A Coward",
"Severance",
"Prey",
{},
228,
0,
2,
{}
},
QDateTime::fromTime_t (1470071375).toUTC ()
},
{
Media::AudioInfo
{
"Heart Of A Coward",
"Severance",
"Nauseam",
{},
218,
0,
4,
{}
},
QDateTime::fromTime_t (1470072028).toUTC ()
}
};
QCOMPARE (result, expected);
}
void ParserTest::testSkipMissingFieldsRecords ()
{
const QString data = R"(
#AUDIOSCROBBLER/1.1
#TZ/UNKNOWN
#CLIENT/Rockbox sansaclipzip $Revision$
Heart Of A Coward Severance Monstro 213 S 1470071129
)";
const auto& result = ParseData (data);
const Media::IAudioScrobbler::BackdatedTracks_t expected {};
QCOMPARE (result, expected);
}
void ParserTest::testIgnoreMissingOptionalFields ()
{
const QString data = R"(
#TZ/UNKNOWN
Heart Of A Coward Monstro 213 L 1470071135
)";
const auto& result = ParseData (data);
const Media::IAudioScrobbler::BackdatedTracks_t expected
{
{
Media::AudioInfo
{
"Heart Of A Coward",
{},
"Monstro",
{},
213,
0,
0,
{}
},
QDateTime::fromTime_t (1470071135).toUTC ()
}
};
QCOMPARE (result, expected);
}
}
}
}
| [
"0xd34df00d@gmail.com"
] | 0xd34df00d@gmail.com |
2e6679db6404b115f0a4f9dd5e73512ceec1ca7d | 20694fd072e147ef11124f929eedf83a565bbc0f | /aws-cpp-sdk-kinesis/source/model/EnhancedMetrics.cpp | d9cf9f42a350b1a3312468585c5fd8c440c606ff | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | GREYFOXRGR/aws-sdk-cpp | 1d9a9b2dce4183c6ff6a0b906df189ad69c4db9c | 098116a5e1fe748eefeb3ed97754860b9c3fb942 | refs/heads/master | 2021-01-15T09:32:28.947930 | 2016-05-05T20:57:47 | 2016-05-05T20:57:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,159 | cpp | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#include <aws/kinesis/model/EnhancedMetrics.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Kinesis::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
EnhancedMetrics::EnhancedMetrics() :
m_shardLevelMetricsHasBeenSet(false)
{
}
EnhancedMetrics::EnhancedMetrics(const JsonValue& jsonValue) :
m_shardLevelMetricsHasBeenSet(false)
{
*this = jsonValue;
}
EnhancedMetrics& EnhancedMetrics::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("ShardLevelMetrics"))
{
Array<JsonValue> shardLevelMetricsJsonList = jsonValue.GetArray("ShardLevelMetrics");
for(unsigned shardLevelMetricsIndex = 0; shardLevelMetricsIndex < shardLevelMetricsJsonList.GetLength(); ++shardLevelMetricsIndex)
{
m_shardLevelMetrics.push_back(MetricsNameMapper::GetMetricsNameForName(shardLevelMetricsJsonList[shardLevelMetricsIndex].AsString()));
}
m_shardLevelMetricsHasBeenSet = true;
}
return *this;
}
JsonValue EnhancedMetrics::Jsonize() const
{
JsonValue payload;
if(m_shardLevelMetricsHasBeenSet)
{
Array<JsonValue> shardLevelMetricsJsonList(m_shardLevelMetrics.size());
for(unsigned shardLevelMetricsIndex = 0; shardLevelMetricsIndex < shardLevelMetricsJsonList.GetLength(); ++shardLevelMetricsIndex)
{
shardLevelMetricsJsonList[shardLevelMetricsIndex].AsString(MetricsNameMapper::GetNameForMetricsName(m_shardLevelMetrics[shardLevelMetricsIndex]));
}
payload.WithArray("ShardLevelMetrics", std::move(shardLevelMetricsJsonList));
}
return payload;
} | [
"henso@amazon.com"
] | henso@amazon.com |
3f3c0d26c6e63c7d9b762b9d7c08bf162ea28e1c | b777ee64e9bef153fd131784eab84d9ec6322b3a | /JSK/Algorithms/Sorting/12_Counting Sort 2.cpp | b29fecb50ca0dc0b75e7612500f89919f6f89deb | [] | no_license | goodann/AlgorithmsStudy | aec2b092b68e5cd213bc2d578565673099d0d695 | 39455cb0daf25499a2438740dda4de42f953baa1 | refs/heads/master | 2020-12-02T22:53:17.108162 | 2017-10-16T05:24:45 | 2017-10-16T05:24:45 | 96,196,496 | 1 | 1 | null | 2017-07-10T07:52:05 | 2017-07-04T08:48:24 | C++ | UTF-8 | C++ | false | false | 501 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int N ,num;
cin >> N;
vector<int> numbers(100);
for(int i = 0 ; i < N ; i++){
cin>> num;
numbers[num]++;
}
for(int i = 0 ; i< 100; i++){
for(int j = 0 ; j < numbers[i]; j++ )
cout<<i<<" ";
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
d7e53b259b5006cdda6475063486f0f65060be64 | a6b64925fdfa968e78b34f1f201aae56e882e18a | /Server/MainDll/common/AudioManager.h | 20620a3adbfc188c70e7b72444673799b87193ad | [] | no_license | nickwu1220/PCRemote | 5bfe9641da2497e7656018fc441cebcf4a784c49 | 6e326a72f3a0b3d61446abee359eb6ac1aa61720 | refs/heads/master | 2016-09-05T14:51:28.284403 | 2014-09-01T09:43:21 | 2014-09-01T09:43:21 | 18,865,903 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 876 | h | // AudioManager.h: interface for the CAudioManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_AUDIOMANAGER_H__8EB9310D_AEFB_40C5_A4E7_6EE4603CBC69__INCLUDED_)
#define AFX_AUDIOMANAGER_H__8EB9310D_AEFB_40C5_A4E7_6EE4603CBC69__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Manager.h"
#include "..\..\..\common\Audio.h"
class CAudioManager : public CManager
{
public:
CAudioManager(CClientSocket *pClient);
virtual ~CAudioManager();
int sendRecordBuffer();
virtual void OnReceive(LPBYTE lpBuffer, UINT nSize);
static bool m_bIsWorking;
private:
bool Initialize();
CAudio *m_lpAudio;
HANDLE m_hWorkThread;
static DWORD WINAPI WorkThread(LPVOID lparam);
};
#endif // !defined(AFX_AUDIOMANAGER_H__8EB9310D_AEFB_40C5_A4E7_6EE4603CBC69__INCLUDED_)
| [
"61347219@qq.com"
] | 61347219@qq.com |
9be7f6c7da0d1906ba7724999a9668efb9cad213 | e4516bc1ef2407c524af95f5b6754b3a3c37b3cc | /answers/leetcode/Best Time to Buy and Sell Stock/Best Time to Buy and Sell Stock.cpp | 89b8433b51fe6258b0a37decd79fddbc357737fb | [
"MIT"
] | permissive | FeiZhan/Algo-Collection | 7102732d61f324ffe5509ee48c5015b2a96cd58d | 9ecfe00151aa18e24846e318c8ed7bea9af48a57 | refs/heads/master | 2023-06-10T17:36:53.473372 | 2023-06-02T01:33:59 | 2023-06-02T01:33:59 | 3,762,869 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | cpp | class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (prices.size() < 2)
{
return 0;
}
int max = 0, min = INT_MAX;
for (int i = 0; i < prices.size(); ++ i)
{
if (prices[i] < min)
{
min = prices[i];
}
if (prices[i] - min > max)
{
max = prices[i] - min;
}
}
return max;
}
};
| [
"f.zhan@sap.com"
] | f.zhan@sap.com |
ac44cc91dde5786114a488f6520322dac702204a | bd7d6df13c24221140aee00c58032e9426d35ad5 | /head.h | f5d0baccb01c83ff38f4f5872b3d8f6b302997dc | [] | no_license | xueminglei870123/chargame_fighter | 89434034255c9fe7f1020858b8a09cd74b823e80 | c547d4e76d835fb6801c2b9ceea5d2dffee86543 | refs/heads/master | 2020-08-08T23:47:06.111600 | 2019-10-09T15:13:31 | 2019-10-09T15:13:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | h | #pragma once
#include <cmath>
#include <iomanip>
#include <ctime>
#include <string>
#include <array>
#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <forward_list>
#include <map>
#include <algorithm>
#include <numeric>
#include <iterator>
#include<typeinfo>
#include <windows.h>
#include <conio.h>
#define ROW 26
#define COL 30
#define INF 20
#define CHAR1 "@"
#define CHAR2 "X"
#define LIFE1 10
#define LIFE2 100
#define BU1 "*"
#define BU2 "^"
| [
"noreply@github.com"
] | noreply@github.com |
3f4a2a99363ed3fb4ab8b1c9b10561e2d8bacecc | 4ddfbbf1874f26eb25ce09b5444482ed9c7d0a02 | /apollo/modules/drivers/ydlidar/driver/ydlidar_driver_component.h | aa70866e36a6764b74165704f173cbc93c296d72 | [
"Apache-2.0"
] | permissive | YDLIDAR/ydlidar_apollo_driver | 9bdbcdfd6d0c5526fbde624b242ae26938408dc7 | 2f1f1b75e53450438122937bd1ccc19ba75eaf85 | refs/heads/master | 2023-02-25T00:29:46.319771 | 2021-02-01T07:56:25 | 2021-02-01T07:56:25 | 279,550,359 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,136 | h | /******************************************************************************
* Copyright 2020 EAIBOT. 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.
*****************************************************************************/
#include "cyber/base/concurrent_object_pool.h"
#include "cyber/cyber.h"
#include <src/CYdLidar.h>
#include "modules/common/util/message_util.h"
#include "modules/drivers/ydlidar/proto/config.pb.h"
#include "modules/drivers/proto/pointcloud.pb.h"
#include "modules/drivers/ydlidar/proto/ydlidar.pb.h"
namespace apollo {
namespace drivers {
namespace ydlidar {
using apollo::cyber::Component;
using apollo::cyber::Writer;
using apollo::cyber::base::CCObjectPool;
using apollo::drivers::PointCloud;
class YDLidarDriverComponent : public Component<> {
public:
~YDLidarDriverComponent() {
if (device_thread_->joinable()) {
device_thread_->join();
}
}
bool Init() override;
private:
void scan_data_poll();
volatile bool runing_; ///< device thread is running
std::shared_ptr<std::thread> device_thread_;
std::shared_ptr<apollo::drivers::ydlidar::LidarScan> laser_scan_msg_ = nullptr;
std::shared_ptr<PointCloud> point_cloud_ = nullptr;
std::unique_ptr<CYdLidar> dvr_ = nullptr; ///< driver implementation class
std::shared_ptr<apollo::cyber::Writer<apollo::drivers::ydlidar::LidarScan>>
writer_ = nullptr;
std::shared_ptr<apollo::cyber::Writer<apollo::drivers::PointCloud>> pc_writer_ =
nullptr;
};
CYBER_REGISTER_COMPONENT(YDLidarDriverComponent)
} // namespace ydlidar
} // namespace drivers
} // namespace apollo
| [
"chushuifurong618@126.com"
] | chushuifurong618@126.com |
ab9c53e903eabf83dfd53e9167989d9448691b05 | f54478bdc7ccc93052c3af14bf573d9434f15197 | /src-tex/colorspace.cpp | 07e891a6d744d267f0f1ea63800f745763c46c5a | [
"MIT"
] | permissive | radtek/bengine-gfx | 609669ee8e31ab84b9e757f8dc513086bc8abe7e | e7a6f476ccb85262db8958e39674bc9570956bbe | refs/heads/master | 2022-02-22T22:17:59.880921 | 2018-05-23T05:34:38 | 2018-05-23T05:34:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,650 | cpp | #include "pch.hpp"
#include "tex/colorspace.hpp"
/*!! include 'tex/colorspace' !! 253 */
/* ################# !! GENERATED CODE -- DO NOT MODIFY !! ################# */
namespace be::gfx::tex {
///////////////////////////////////////////////////////////////////////////////
bool is_valid(ColorspaceFamily constant) noexcept {
switch (constant) {
case ColorspaceFamily::none:
case ColorspaceFamily::bt709_linear:
case ColorspaceFamily::bt709:
case ColorspaceFamily::srgb:
case ColorspaceFamily::cie:
return true;
default:
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
const char* colorspace_family_name(ColorspaceFamily constant) noexcept {
switch (constant) {
case ColorspaceFamily::none: return "none";
case ColorspaceFamily::bt709_linear: return "bt709_linear";
case ColorspaceFamily::bt709: return "bt709";
case ColorspaceFamily::srgb: return "srgb";
case ColorspaceFamily::cie: return "cie";
default:
return "?";
}
}
///////////////////////////////////////////////////////////////////////////////
std::array<const ColorspaceFamily, 5> colorspace_family_values() noexcept {
return ::be::EnumTraits<ColorspaceFamily>::values<>();
}
///////////////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& os, ColorspaceFamily constant) {
if (is_valid(constant)) {
os << colorspace_family_name(constant);
} else {
os << static_cast<I64>(static_cast<U8>(constant));
}
return os;
}
///////////////////////////////////////////////////////////////////////////////
bool is_valid(ColorspaceVariant constant) noexcept {
switch (constant) {
case ColorspaceVariant::none:
case ColorspaceVariant::hsl:
case ColorspaceVariant::hsv:
case ColorspaceVariant::ycbcr:
return true;
default:
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
const char* colorspace_variant_name(ColorspaceVariant constant) noexcept {
switch (constant) {
case ColorspaceVariant::none: return "none";
case ColorspaceVariant::hsl: return "hsl";
case ColorspaceVariant::hsv: return "hsv";
case ColorspaceVariant::ycbcr: return "ycbcr";
default:
return "?";
}
}
///////////////////////////////////////////////////////////////////////////////
std::array<const ColorspaceVariant, 4> colorspace_variant_values() noexcept {
return ::be::EnumTraits<ColorspaceVariant>::values<>();
}
///////////////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& os, ColorspaceVariant constant) {
if (is_valid(constant)) {
os << colorspace_variant_name(constant);
} else {
os << static_cast<I64>(static_cast<U8>(constant));
}
return os;
}
///////////////////////////////////////////////////////////////////////////////
bool is_valid(Colorspace constant) noexcept {
switch (constant) {
case Colorspace::unknown:
case Colorspace::linear_other:
case Colorspace::linear_depth_stencil:
case Colorspace::linear_depth:
case Colorspace::linear_stencil:
case Colorspace::bt709_linear_rgb:
case Colorspace::bt709_linear_hsl:
case Colorspace::bt709_linear_hsv:
case Colorspace::bt709_linear_ycbcr:
case Colorspace::bt709_rgb:
case Colorspace::bt709_hsl:
case Colorspace::bt709_hsv:
case Colorspace::bt709_ycbcr:
case Colorspace::srgb:
case Colorspace::srgb_hsl:
case Colorspace::srgb_hsv:
case Colorspace::srgb_ycbcr:
case Colorspace::cie_xyz:
case Colorspace::cie_lab_d65:
case Colorspace::cie_lchab_d65:
case Colorspace::cie_luv_d65:
case Colorspace::cie_lchuv_d65:
case Colorspace::cie_xyy:
return true;
default:
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
const char* colorspace_name(Colorspace constant) noexcept {
switch (constant) {
case Colorspace::unknown: return "unknown";
case Colorspace::linear_other: return "linear_other";
case Colorspace::linear_depth_stencil: return "linear_depth_stencil";
case Colorspace::linear_depth: return "linear_depth";
case Colorspace::linear_stencil: return "linear_stencil";
case Colorspace::bt709_linear_rgb: return "bt709_linear_rgb";
case Colorspace::bt709_linear_hsl: return "bt709_linear_hsl";
case Colorspace::bt709_linear_hsv: return "bt709_linear_hsv";
case Colorspace::bt709_linear_ycbcr: return "bt709_linear_ycbcr";
case Colorspace::bt709_rgb: return "bt709_rgb";
case Colorspace::bt709_hsl: return "bt709_hsl";
case Colorspace::bt709_hsv: return "bt709_hsv";
case Colorspace::bt709_ycbcr: return "bt709_ycbcr";
case Colorspace::srgb: return "srgb";
case Colorspace::srgb_hsl: return "srgb_hsl";
case Colorspace::srgb_hsv: return "srgb_hsv";
case Colorspace::srgb_ycbcr: return "srgb_ycbcr";
case Colorspace::cie_xyz: return "cie_xyz";
case Colorspace::cie_lab_d65: return "cie_lab_d65";
case Colorspace::cie_lchab_d65: return "cie_lchab_d65";
case Colorspace::cie_luv_d65: return "cie_luv_d65";
case Colorspace::cie_lchuv_d65: return "cie_lchuv_d65";
case Colorspace::cie_xyy: return "cie_xyy";
default:
return "?";
}
}
///////////////////////////////////////////////////////////////////////////////
std::array<const Colorspace, 23> colorspace_values() noexcept {
return ::be::EnumTraits<Colorspace>::values<>();
}
///////////////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& os, Colorspace constant) {
if (is_valid(constant)) {
os << colorspace_name(constant);
} else {
os << static_cast<I64>(static_cast<U8>(constant));
}
return os;
}
///////////////////////////////////////////////////////////////////////////////
Colorspace base_colorspace(ColorspaceFamily constant) noexcept {
switch (constant) {
case ColorspaceFamily::none: return Colorspace::linear_other;
case ColorspaceFamily::bt709_linear: return Colorspace::bt709_linear_rgb;
case ColorspaceFamily::bt709: return Colorspace::bt709_rgb;
case ColorspaceFamily::srgb: return Colorspace::srgb;
case ColorspaceFamily::cie: return Colorspace::cie_xyz;
default:
return Colorspace::unknown;
}
}
///////////////////////////////////////////////////////////////////////////////
Colorspace linear_colorspace(ColorspaceFamily constant) noexcept {
switch (constant) {
case ColorspaceFamily::bt709_linear: return Colorspace::bt709_linear_rgb;
case ColorspaceFamily::bt709: return Colorspace::bt709_linear_rgb;
case ColorspaceFamily::srgb: return Colorspace::bt709_linear_rgb;
case ColorspaceFamily::cie: return Colorspace::cie_xyz;
default:
return Colorspace::linear_other;
}
}
///////////////////////////////////////////////////////////////////////////////
bool is_linear(Colorspace constant) noexcept {
switch (constant) {
case Colorspace::linear_other: return true;
case Colorspace::linear_depth_stencil: return true;
case Colorspace::linear_depth: return true;
case Colorspace::linear_stencil: return true;
case Colorspace::bt709_linear_rgb: return true;
case Colorspace::cie_xyz: return true;
default:
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
ColorspaceFamily colorspace_family(Colorspace constant) noexcept {
switch (constant) {
case Colorspace::bt709_linear_rgb: return ColorspaceFamily::bt709_linear;
case Colorspace::bt709_linear_hsl: return ColorspaceFamily::bt709_linear;
case Colorspace::bt709_linear_hsv: return ColorspaceFamily::bt709_linear;
case Colorspace::bt709_linear_ycbcr: return ColorspaceFamily::bt709_linear;
case Colorspace::bt709_rgb: return ColorspaceFamily::bt709;
case Colorspace::bt709_hsl: return ColorspaceFamily::bt709;
case Colorspace::bt709_hsv: return ColorspaceFamily::bt709;
case Colorspace::bt709_ycbcr: return ColorspaceFamily::bt709;
case Colorspace::srgb: return ColorspaceFamily::srgb;
case Colorspace::srgb_hsl: return ColorspaceFamily::srgb;
case Colorspace::srgb_hsv: return ColorspaceFamily::srgb;
case Colorspace::srgb_ycbcr: return ColorspaceFamily::srgb;
case Colorspace::cie_xyz: return ColorspaceFamily::cie;
case Colorspace::cie_lab_d65: return ColorspaceFamily::cie;
case Colorspace::cie_lchab_d65: return ColorspaceFamily::cie;
case Colorspace::cie_luv_d65: return ColorspaceFamily::cie;
case Colorspace::cie_lchuv_d65: return ColorspaceFamily::cie;
case Colorspace::cie_xyy: return ColorspaceFamily::cie;
default:
return ColorspaceFamily::none;
}
}
///////////////////////////////////////////////////////////////////////////////
ColorspaceVariant colorspace_variant(Colorspace constant) noexcept {
switch (constant) {
case Colorspace::bt709_linear_hsl: return ColorspaceVariant::hsl;
case Colorspace::bt709_linear_hsv: return ColorspaceVariant::hsv;
case Colorspace::bt709_linear_ycbcr: return ColorspaceVariant::ycbcr;
case Colorspace::bt709_hsl: return ColorspaceVariant::hsl;
case Colorspace::bt709_hsv: return ColorspaceVariant::hsv;
case Colorspace::bt709_ycbcr: return ColorspaceVariant::ycbcr;
case Colorspace::srgb_hsl: return ColorspaceVariant::hsl;
case Colorspace::srgb_hsv: return ColorspaceVariant::hsv;
case Colorspace::srgb_ycbcr: return ColorspaceVariant::ycbcr;
default:
return ColorspaceVariant::none;
}
}
} // be::gfx::tex
/* ######################### END OF GENERATED CODE ######################### */
| [
"ben@magicmoremagic.com"
] | ben@magicmoremagic.com |
75c6224c229d3dc27f1961f8edc3026594aeaba8 | 9a8f7cc51b9cfd8e76c76258e980603b990740e5 | /Zombie-Escape/src/kinematic.cpp | 2bc57d0668286402f5a181ab772d1d0b57a49afb | [
"MIT"
] | permissive | SakshayMahna/AI-for-Game-Programming | 8ab23e2eea89cfc027ee4ae5bf6aa093eaf1bf06 | de2df8b25b233e6db08971226eece2cab2a7f3ef | refs/heads/main | 2023-08-15T06:06:04.577408 | 2021-10-19T16:50:08 | 2021-10-19T16:50:08 | 409,204,141 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 861 | cpp | #include <cmath>
#include "kinematic.h"
// Kinematic constructor
Kinematic::Kinematic(float i_position[2], float i_velocity[2]) {
position[0] = i_position[0];
position[1] = i_position[1];
velocity[0] = i_velocity[0];
velocity[1] = i_velocity[1];
}
// Kinematic Update
void Kinematic::update(Steering steering, float time) {
// Update position and velocity
position[0] += velocity[0] * time;
position[1] += velocity[1] * time;
velocity[0] += steering.linear[0] * time;
velocity[1] += steering.linear[1] * time;
}
// Kinematic Position Update
void Kinematic::updatePosition(float d_x, float d_y, float mod_x, float mod_y) {
// Update Position
position[0] += d_x;
position[1] += d_y;
// Modulo Update
position[0] = fmod(position[0] + mod_x, mod_x);
position[1] = fmod(position[1] + mod_y, mod_y);
} | [
"sakshum19@gmail.com"
] | sakshum19@gmail.com |
289f33d90f802122861227a301e5f46efad7c919 | ea7509bfdb3b40fb5466017067bb84848418ebca | /gr-howto-12-04-2014/lib/ofdm_chanest_vcvc_impl.h | feaf970a7184716116126ab739b9a58de7524357 | [] | no_license | NinjaComics/github-repository | 6ced3deb82463da293ebf970bf58f537f8d1caff | eda13e0ea63941f9d6f1aa63650a9ee1196f1899 | refs/heads/master | 2020-03-17T19:10:40.745032 | 2014-12-04T16:43:38 | 2014-12-04T16:43:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,634 | h | /* -*- c++ -*- */
/*
* Copyright 2013 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* GNU Radio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef INCLUDED_HOWTO_OFDM_CHANEST_VCVC_IMPL_H
#define INCLUDED_HOWTO_OFDM_CHANEST_VCVC_IMPL_H
#include <howto/ofdm_chanest_vcvc.h>
namespace gr {
namespace howto {
class ofdm_chanest_vcvc_impl : public ofdm_chanest_vcvc
{
private:
int d_fft_len; //! FFT length
int d_n_data_syms; //! Number of data symbols following the sync symbol(s)
int d_n_sync_syms; //! Number of sync symbols (1 or 2)
//! 0 if no noise reduction is done for the initial channel state estimation. Otherwise, the maximum length of the channel delay in samples.
int d_eq_noise_red_len;
//! Is sync_symbol1 if d_n_sync_syms == 1, otherwise sync_symbol2. Used as a reference symbol to estimate the channel.
std::vector<gr_complex> d_ref_sym;
//! If d_n_sync_syms == 2 this is used as a differential correlation vector (called 'v' in [1]).
std::vector<gr_complex> d_corr_v;
//! If d_n_sync_syms == 1 we use this instead of d_corr_v to estimate the coarse freq. offset
std::vector<float> d_known_symbol_diffs;
//! If d_n_sync_syms == 1 we use this instead of d_corr_v to estimate the coarse freq. offset (temp. variable)
std::vector<float> d_new_symbol_diffs;
//! The index of the first carrier with data (index 0 is not DC here, but the lowest frequency)
int d_first_active_carrier;
//! The index of the last carrier with data
int d_last_active_carrier;
//! If true, the channel estimation must be interpolated
bool d_interpolate;
//! Maximum carrier offset (negative value!)
int d_max_neg_carr_offset;
//! Maximum carrier offset (positive value!)
int d_max_pos_carr_offset;
//gr::howto::constellation_sptr d_constellation;
//! Calculate the coarse frequency offset in number of carriers
int get_carr_offset(const gr_complex *sync_sym1, const gr_complex *sync_sym2);
//! Estimate the channel (phase and amplitude offset per carrier)
void get_chan_taps(const gr_complex *sync_sym1, const gr_complex *sync_sym2, int carr_offset, std::vector<gr_complex> &taps);
/*void get_occupied_carriers(
std::vector<gr_complex> &chan_taps,
const gr_complex *frame,
std::vector<int > &occupied_carriers);*/
public:
ofdm_chanest_vcvc_impl(const std::vector<gr_complex> &sync_symbol1, const std::vector<gr_complex> &sync_symbol2, int n_data_symbols, int eq_noise_red_len, int max_carr_offset, bool force_one_sync_symbol);
~ofdm_chanest_vcvc_impl();
void forecast (int noutput_items, gr_vector_int &ninput_items_required);
int general_work(int noutput_items,
gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items);
};
} // namespace howto
} // namespace gr
#endif /* INCLUDED_HOWTO_OFDM_CHANEST_VCVC_IMPL_H */
| [
"chenghanke@gmail.com"
] | chenghanke@gmail.com |
d5762bee591b4419f07eddf7603d02962571fa2e | 5aaec5fe9ecf70f0c38bdc9446430fcdd4e9612e | /TTT3D/main.cpp | effd60aa51c943fa16df16c4ee68f8084e22e366 | [] | no_license | MarkKerner/AI_HW2 | 0494c8ce6c635acb05ce7018161bcefdf734ed45 | 6f122f1bf25bd54cfcbdebeb1c344db1a0753453 | refs/heads/master | 2021-01-17T10:54:51.924712 | 2016-09-28T07:16:36 | 2016-09-28T07:16:36 | 68,802,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,607 | cpp | #include "player.hpp"
#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char **argv)
{
// Parse parameters
bool init = false;
bool verbose = false;
bool fast = false;
for (int i = 1; i < argc; ++i)
{
std::string param(argv[i]);
if (param == "init" || param == "i")
init = true;
else if (param == "verbose" || param == "v")
verbose = true;
else if (param == "fast" || param == "f")
fast = true;
else
{
std::cerr << "Unknown parameter: '" << argv[i] << "'" << std::endl;
return -1;
}
}
// Start the game by sending the starting board without moves if the parameter "init" is given
if (init)
{
std::string message = TICTACTOE3D::GameState().toMessage();
std::cerr << "Sending initial board: '" << message << "'" << std::endl;
std::cout << message << std::endl;
}
TICTACTOE3D::Player player;
std::string input_message;
while (std::getline(std::cin, input_message))
{
// Get game state from standard input
//std::cerr << "Receiving: '" << input_message << "'" << std::endl;
TICTACTOE3D::GameState input_state(input_message);
//See if we would produce the same message
if (input_state.toMessage() != input_message)
{
std::cerr << "*** ERROR! ***" << std::endl;
std::cerr << "Interpreted: '" << input_message << "'" << std::endl;
std::cerr << "As: '" << input_state.toMessage() << "'" << std::endl;
std::cerr << input_state.toString(input_state.getNextPlayer()) << std::endl;
assert(false);
}
// Print the input state
if (verbose)
{
std::cerr << input_state.toMessage() << std::endl;
std::cerr << input_state.toString(input_state.getNextPlayer()) << std::endl;
}
// Quit if this is end of game
if (input_state.getMove().isEOG())
break;
// Deadline is 3 seconds from when we receive the message
TICTACTOE3D::Deadline deadline = TICTACTOE3D::Deadline::now() + (fast ? 0.1 : 3.0);
// Figure out the next move
TICTACTOE3D::GameState output_state = player.play(input_state, deadline);
if (deadline < TICTACTOE3D::Deadline::now()) {
std::cerr << "player timed out " << std::endl;
exit(152);
}
// Check if output state is correct
std::vector<TICTACTOE3D::GameState> output_states;
input_state.findPossibleMoves(output_states);
bool output_state_correct = false;
for (unsigned int i = 0; i < output_states.size(); ++i)
if (output_state.isEqual(output_states[i]))
{
output_state_correct = true;
break;
}
if (!output_state_correct) {
std::cerr << "output state not corrext" << std::endl;
exit(134);
}
// Print the output state
if (verbose)
{
std::cerr << output_state.toMessage() << std::endl;
std::cerr << output_state.toString(input_state.getNextPlayer()) << std::endl;
}
// Send the next move
std::string output_message = output_state.toMessage();
//std::cerr << "Sending: '" << output_message << "'"<< std::endl;
std::cout << output_message << std::endl;
// Quit if this is end of game
if (output_state.getMove().isEOG())
break;
}
}
| [
"mark.kerner@hotmail.com"
] | mark.kerner@hotmail.com |
5e06f63114c7b8a1e98549fe8da71bde1f04bb20 | 9be246df43e02fba30ee2595c8cec14ac2b355d1 | /engine/audio/private/snd_win.cpp | e8d2d1f2cee4e41ff6ec254d6cd2e50f162d1c87 | [] | no_license | Clepoy3/LeakNet | 6bf4c5d5535b3824a350f32352f457d8be87d609 | 8866efcb9b0bf9290b80f7263e2ce2074302640a | refs/heads/master | 2020-05-30T04:53:22.193725 | 2019-04-12T16:06:26 | 2019-04-12T16:06:26 | 189,544,338 | 18 | 5 | null | 2019-05-31T06:59:39 | 2019-05-31T06:59:39 | null | UTF-8 | C++ | false | false | 7,127 | cpp |
#include <windows.h>
#include "tier0/dbg.h"
#include "convar.h"
#include "sound.h"
#include "sound_private.h"
#include "snd_device.h"
#include "snd_dev_direct.h"
#include "snd_dev_wave.h"
#include "snd_sfx.h"
#include "snd_audio_source.h"
#include "voice_sound_engine_interface.h"
#include "snd_channels.h"
#include "snd_wave_source.h"
#include "SoundService.h"
// In other C files.
extern ConVar s_surround;
qboolean snd_firsttime = true;
#if DEAD
// starts at 0 for disabled
static int snd_buffer_count = 0;
static int snd_sent, snd_completed;
#endif
/*
* Global variables. Must be visible to window-procedure function
* so it can unlock and free the data block after it has been played.
*/
IAudioDevice *g_AudioDevice = NULL;
/////////////////////////////////////////////////////////////////////////////////////////////
class CAudioDeviceNull : public IAudioDevice
{
public:
bool IsActive( void ) { return false; }
bool Init( void ) { return true; }
void Shutdown( void ) {}
int GetOutputPosition( void ) { return 0; }
void Pause( void ) {}
void UnPause( void ) {}
float MixDryVolume( void ) { return 0; }
bool Should3DMix( void ) { return false; }
void SetActivation( bool active ) {}
void StopAllSounds( void ) {}
int PaintBegin( int, int ) { return 0; }
void PaintEnd( void ) {}
void ClearBuffer( void ) {}
void UpdateListener( const Vector&, const Vector&, const Vector&, const Vector& ) {}
void MixBegin( int ) {}
void MixUpsample( int sampleCount, int filtertype ) {}
void ChannelReset( int, int, float ) {}
void TransferSamples( int end ) {}
void SpatializeChannel( int volume[4], int master_vol, const Vector& sourceDir, float gain, float dotRight, float dotFront ) {}
void ApplyDSPEffects( int idsp, portable_samplepair_t *pbuffront, portable_samplepair_t *pbufrear, int samplecount ) {}
// return some bogus data here
const char *DeviceName( void ) { return "Audio Disabled"; }
int DeviceChannels( void ) { return 2; }
int DeviceSampleBits( void ) { return 16; }
int DeviceSampleBytes( void ) { return 2; }
int DeviceDmaSpeed( void ) { return SOUND_DMA_SPEED; }
int DeviceSampleCount( void ) { return 0; }
void *DeviceLockBuffer( void ) { return NULL; }
void DeviceUnlockBuffer( void * ) {}
// sink sound data
void Mix8Mono( channel_t *pChannel, char *pData, int outputOffset, int inputOffset, fixedint rateScaleFix, int outCount, int timecompress ) {}
void Mix8Stereo( channel_t *pChannel, char *pData, int outputOffset, int inputOffset, fixedint rateScaleFix, int outCount, int timecompress ) {}
void Mix16Mono( channel_t *pChannel, short *pData, int outputOffset, int inputOffset, fixedint rateScaleFix, int outCount, int timecompress ) {}
void Mix16Stereo( channel_t *pChannel, short *pData, int outputOffset, int inputOffset, fixedint rateScaleFix, int outCount, int timecompress ) {}
};
IAudioDevice *Audio_GetNullDevice( void )
{
// singeton device here
static CAudioDeviceNull nullDevice;
return &nullDevice;
}
/*
==================
S_BlockSound
==================
*/
void S_BlockSound (void)
{
if ( !g_AudioDevice )
return;
g_AudioDevice->Pause();
}
/*
==================
S_UnblockSound
==================
*/
void S_UnblockSound (void)
{
if ( !g_AudioDevice )
return;
g_AudioDevice->UnPause();
}
/*
==============
S_LoadSound
Check to see if wave data is in the cache. If so, return pointer to data.
If not, allocate cache space for wave data, load wave file into temporary heap
space, and dump/convert file data into cache.
==============
*/
CAudioSource *S_LoadSound( CSfxTable *s, channel_t *ch )
{
if ( !s->pSource )
{
// Names that begin with "*" are streaming.
// Skip over the * and create a streamed source
if ( TestSoundChar( s->getname(), CHAR_STREAM ))
{
s->pSource = Audio_CreateStreamedWave( PSkipSoundChars(s->getname()) );
}
else
{
if ( TestSoundChar( s->getname(), CHAR_USERVOX ))
{
s->pSource = Voice_SetupAudioSource(ch->soundsource, ch->entchannel);
}
else
{
// These are loaded into memory directly - skip sound characters
s->pSource = Audio_CreateMemoryWave( PSkipSoundChars(s->getname()) );
}
}
}
if ( !s->pSource )
return NULL;
#if 0 // 44k: UNDONE if hisound is 0, unload any 44khz sounds
if ( s->pSource->IsCached() )
{
if ( hisound.GetInt() == 0 && s->pSource->SampleRate() == SOUND_44k )
{
// this sample was cached at high sample rate:
// discard cached data and reload at new sample rate
// NOTE: this can happen because the hisound cvar
// is initialized from default.cfg AFTER local precaching
if ( TestSoundChar(s->name, CHAR_USERVOX ))
{
DevMsg("S_LoadSound: Freeing voice data prematurely!\n");
}
s->pSource->CacheUnload();
}
}
#endif
// 44k: - UNDONE, if hisound is 0 and wav is 44khz, downsample to 22khz when loading
s->pSource->CacheLoad();
// first time to load? Create the mixer
if ( ch && !ch->pMixer )
{
ch->pMixer = s->pSource->CreateMixer();
if ( !ch->pMixer )
{
return NULL;
}
}
return s->pSource;
}
/*
==================
AutoDetectInit
Try to find a sound device to mix for.
Returns a CAudioNULLDevice if nothing is found.
==================
*/
IAudioDevice *IAudioDevice::AutoDetectInit( bool waveOnly )
{
IAudioDevice *pDevice = NULL;
// JAY: UNDONE: Handle fake sound device here "fakedma"
// if (g_pSoundServices->CheckParm("-simsound"))
// fakedma = true;
if ( waveOnly )
{
pDevice = Audio_CreateWaveDevice();
if ( !pDevice )
goto NULLDEVICE;
}
if ( !pDevice )
{
/* Init DirectSound */
if ( g_pSoundServices->IsDirectSoundSupported() )
{
if (snd_firsttime)
{
pDevice = Audio_CreateDirectSoundDevice();
}
}
}
// if DirectSound didn't succeed in initializing, try to initialize
// waveOut sound, unless DirectSound failed because the hardware is
// already allocated (in which case the user has already chosen not
// to have sound)
// UNDONE: JAY: This doesn't test for the hardware being in use anymore, REVISIT
if ( !pDevice )
{
pDevice = Audio_CreateWaveDevice();
}
NULLDEVICE:
snd_firsttime = false;
if ( !pDevice )
{
if (snd_firsttime)
DevMsg ("No sound device initialized\n");
return Audio_GetNullDevice();
}
return pDevice;
}
/*
==============
SNDDMA_Submit
Send sound to device if buffer isn't really the dma buffer
===============
*/
void SNDDMA_Submit(void)
{
g_AudioDevice->PaintEnd();
}
/*
==============
SNDDMA_Shutdown
Reset the sound device for exiting
===============
*/
void SNDDMA_Shutdown(void)
{
if ( g_AudioDevice != Audio_GetNullDevice() )
{
if ( g_AudioDevice )
{
g_AudioDevice->Shutdown();
}
delete g_AudioDevice;
// the NULL device is always valid
g_AudioDevice = Audio_GetNullDevice();
}
}
| [
"uavxp29@gmail.com"
] | uavxp29@gmail.com |
7c19dad6be9cc64336d2d78d853b6d0328c39589 | 2e395ab976e04bde26e92004b615433a00121c90 | /tree/Nodes/statements/If.h | a1c856c5ba88959f49aa78a57fdea7859348fa7b | [] | no_license | kkvadrat289/Compilers | 1070f0d16c6fff18fc5ede68696d6269c1be6b83 | 2f5e6d79b7f62e4147ce68e1128f89ffc9b83878 | refs/heads/master | 2021-09-16T17:14:03.719943 | 2018-06-22T09:46:07 | 2018-06-22T09:46:07 | 104,876,904 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 628 | h | #ifndef IF_H
#define IF_H
#include "Statement.h"
#include "StatementSeq.h"
class CIf: public IStatement{
public:
CIf(std::shared_ptr<INode> cond_, std::shared_ptr<IStatement> ifTrue_, std::shared_ptr<IStatement> ifFalse_,
Position pos_):
cond(cond_),
ifTrue(ifTrue_),
ifFalse(ifFalse_),
pos(pos_)
{
}
void accept(IVisitor *v) const override;
virtual const Position& GetPosition() const {
return pos;
}
Position pos;
std::shared_ptr<INode> cond;
std::shared_ptr<IStatement> ifTrue;
std::shared_ptr<IStatement> ifFalse;
};
#endif // IF_H
| [
"kkvadrat289@yandex.ru"
] | kkvadrat289@yandex.ru |
6b670ff2d0c0c1e81430ddd835ff433ef8a4a606 | d27bc8dc51cd34aba2556ca4f7a995110e102240 | /Maze/test_4_20/Maze.cpp | 344b3b521f2e0d71a656db8efeee08ec2ef7be47 | [] | no_license | hqy00/Maze | 25144999c48ef7945a4bd76793c0c9d20380213d | 42dbf4abb8a420006fd24eb8154292f7ecb80de1 | refs/heads/master | 2021-06-15T07:06:58.065662 | 2017-04-21T09:54:54 | 2017-04-21T09:54:54 | 88,969,642 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,760 | cpp | //回溯法思想实现迷宫(递归实现),要求如下:
//保存迷宫的地图给成动态的
//迷宫的数据保存在文件中
//可自行添加辅助函数
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include<assert.h>
#define MAX_ROW 10
#define MAX_COL 10
struct Seat//坐标点
{
Seat(int x, int y)
: _x(x)
, _y(y)
{}
int _x;
int _y;
};
// 数据保存到文件
class Maze
{
public:
Maze(int Row, int Col)//将迷宫地图储存完毕
{
FILE* mz = fopen("Map.txt","r");//从.txt文件中读取地图
assert(mz != NULL);
/***************动态创建数组***********************/
//创建保存有每一行地址的空间
_map = new int*[Row];
//创建保存有每一行数据的空间
for(int idx= 0; idx < Row; idx++)
{
_map[idx] = new int[Col];
}
/**************************************************/
for (int i = 0; i < Row; i++)
{
for (int j = 0; j < Col;)
{
//对文件中的每个字符进行获取,如果获取到的字符是我们要的,进行处理保存到数组中,如果不是,那么结束这次循环,读取下一个字符。
char ch = fgetc(mz);
if (ch == '0' || ch == '1')//注意这里是字符,不是数字
{
_map[i][j] = ch-'0';
j++;//一定要注意,因为我是按照矩阵来写的,数与数之间有空格,行与行之间有回车,所以当取到不为‘0’或‘1’的数时,j不会自增
}
}
}
fclose(mz);
}
bool IsPass(const Seat& s)//判断是否为通路,1是通路,0是墙(死路)
{
if(s._x < 0 || s._x >= MAX_ROW ||
s._y < 0 || s._y >= MAX_COL)//为了不使访问的坐标非法,在这里检测到是出口时就返回
return true;
if(1 == _map[s._x][s._y])//是1返回true,是0返回false
return true;
return false;
}
bool PassMaze(Seat s)//将入口点传入
{
if(s._x < 0 || s._x >= MAX_ROW || s._y < 0 || s._y >= MAX_COL)//判断是否为出口
return true;
//判断是否为通路
if(IsPass(s))
{
_map[s._x][s._y] = 2;
Seat front(s._x-1, s._y);//向上
Seat left(s._x, s._y-1); //向左
Seat right(s._x, s._y+1);//向右
Seat down(s._x+1, s._y); //向下
if(PassMaze(front))//递归
{
return true;
}
else if(PassMaze(left))//递归
{
return true;
}
else if(PassMaze(right))//递归
{
return true;
}
else if(PassMaze(down))//递归
{
return true;
}
else
{
_map[s._x][s._y] = 3;
}
}
return false; //开始回溯
}
void PrintMaze()
{
for (int i = 0; i < MAX_ROW; ++i)
{
for (int j = 0; j < MAX_COL;++j)
{
cout<<_map[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
~Maze()//析构(销毁动态开辟的数组)
{
//释放保存有每一行数据的空间
for(int idx=0; idx< MAX_ROW; idx++)
{
delete[] _map[idx];
}
//释放保存有每一行地址的空间
delete[] _map;
}
private:
int** _map;
};
int main()
{
Maze maze(MAX_ROW, MAX_COL);
maze.PrintMaze();
maze.PassMaze(Seat(9, 6));
maze.PrintMaze();
return 0;
}
//最终结果:
//1.成功从入口点走出去了。那么在入口和出口间,有一条由2组成的路。
//2.失败了。那么在入口和出口间,不会出现一条由2组成的路。但会在迷宫里出现一条或多条由三组成的路,这些
//都是找迷宫出口失败后回溯回去的路线,且这些由3组成的路最终都从最初的入口点出去了。
//循环实现迷宫(用栈来实现)
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<stack>
using namespace std;
#include<assert.h>
#define MAX_ROW 10
#define MAX_COL 10
struct Seat//坐标点
{
Seat(int x = 0, int y = 0)
: _x(x)
, _y(y)
{}
int _x;
int _y;
};
// 数据保存到文件
class Maze
{
public:
Maze(int Row, int Col)//将迷宫地图储存完毕
{
FILE* mz = fopen("Map.txt","r");//从.txt文件中读取地图
assert(mz != NULL);
/***************动态创建数组***********************/
//创建保存有每一行地址的空间
_map = new int*[Row];
//创建保存有每一行数据的空间
for(int idx= 0; idx < Row; idx++)
{
_map[idx] = new int[Col];
}
/**************************************************/
for (int i = 0; i < Row; i++)
{
for (int j = 0; j < Col;)
{
//对文件中的每个字符进行获取,如果获取到的字符是我们要的,进行处理保存到数组中,如果不是,那么结束这次循环,读取下一个字符。
char ch = fgetc(mz);
if (ch == '0' || ch == '1')//注意这里是字符,不是数字
{
_map[i][j] = ch-'0';
j++;//一定要注意,因为我是按照矩阵来写的,数与数之间有空格,行与行之间有回车,所以当取到不为‘0’或‘1’的数时,j不会自增
}
}
}
fclose(mz);
}
bool IsPass(const Seat& pos)//判断是否为通路,1是通路,0是墙(死路)
{
if(pos._x < 0 || pos._x >= MAX_ROW ||
pos._y < 0 || pos._y >= MAX_COL)//为了不使访问的坐标非法,在这里检测到是出口时就返回
return true;
if(1 == _map[pos._x][pos._y])//是1返回true,是0返回false
return true;
return false;
}
bool PassMaze(Seat pos)//将入口点传入
{
stack<Seat> s;
s.push(pos);
while(!s.empty())
{
Seat &cur = s.top();
Seat next;
if(cur._x < 0 || cur._x >= MAX_ROW || cur._y < 0 || cur._y >= MAX_COL)//判断是否为出口
return true;
_map[cur._x][cur._y] = 2;//走过的点标记为2
next = cur;//向上
--next._x ;
if(IsPass(next))
{
s.push(next);
continue;
}
next = cur;//向左
--next._y ;
if(IsPass(next))
{
s.push(next);
continue;
}
next = cur;//向右
++next._y ;
if(IsPass(next))
{
s.push(next);
continue;
}
next = cur;//向下
++next._x ;
if(IsPass(next))
{
s.push(next);
continue;
}
//该点附近没有通路
Seat prev = s.top();
_map[prev._x][prev._y] = 3;//退回的标记为3
s.pop();
}
return false;//此迷宫没有通路,此时栈为空
}
void PrintMaze()
{
for (int i = 0; i < MAX_ROW; ++i)
{
for (int j = 0; j < MAX_COL;++j)
{
cout<<_map[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
~Maze()//析构(销毁动态开辟的数组)
{
//释放保存有每一行数据的空间
for(int idx=0; idx< MAX_ROW; idx++)
{
delete[] _map[idx];
}
//释放保存有每一行地址的空间
delete[] _map;
}
private:
int** _map;
};
int main()
{
Maze maze(MAX_ROW, MAX_COL);
maze.PrintMaze();
maze.PassMaze(Seat(9, 6));
maze.PrintMaze();
return 0;
}
| [
"heqingyun0808@126.com"
] | heqingyun0808@126.com |
3f61a2d1c1deb41c4b8425ecd0fbf7db9fc291f5 | 792f2ee67210556f224daf88ef0b9785becadc9b | /atcoder/AGC/035A.cpp | 53d5ffd59d893e4dd75c730fa534e3fe061b1508 | [] | no_license | firiexp/contest_log | e5b345286e7d69ebf2a599d4a81bdb19243ca18d | 6474a7127d3a2fed768ebb62031d5ff30eeeef86 | refs/heads/master | 2021-07-20T01:16:47.869936 | 2020-04-30T03:27:51 | 2020-04-30T03:27:51 | 150,196,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,025 | cpp | #include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <numeric>
#include <bitset>
#include <cmath>
static const int MOD = 1000000007;
using ll = long long;
using u32 = uint32_t;
using namespace std;
template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;
int main() {
int n;
cin >> n;
vector<int> v(n);
for (auto &&i : v) scanf("%d", &i);
sort(v.begin(),v.end());
if(v.back() == 0){
puts("Yes");
return 0;
}else if(n%3){
puts("No");
return 0;
}
map<int, int> m;
for (int i = 0; i < n; ++i) {
m[v[i]]++;
}
int k = 0;
for (auto &&j : m) {
if(j.second%(n/3)){
puts("No");
return 0;
}else {
for (int i = 0; i < j.second/(n/3); ++i) {
k ^= j.first;
}
}
}
puts(k ? "No" : "Yes");
return 0;
} | [
"firiexp@PC.localdomain"
] | firiexp@PC.localdomain |
7c59619e58e92186b33d7f4a634cdc675dabcc3a | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14795/function14795_schedule_28/function14795_schedule_28_wrapper.cpp | 70f94df518c8f0c76bd5ae07bad5c1b134816441 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 858 | cpp | #include "Halide.h"
#include "function14795_schedule_28_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){Halide::Buffer<int32_t> buf0(256, 1024, 256);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14795_schedule_28(buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14795/function14795_schedule_28/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
0a720bd1ed1c459c7a02912fabd0318a86aeffff | d778b98fa6b4a1ddb215510c15bc78c53d9c79e6 | /RtnResources.h | be5bfed9ef1e6e4b470d1fbcf8b36ccc483c9b8e | [] | no_license | antioch44/runawfe-free-notifier-cpp | e2ce590882a6e6a16f29d15abbb34523d5daccf1 | cb8456fb966b6e17abc2b6eb3a1ebc7bafa84e96 | refs/heads/master | 2020-09-12T12:26:14.317726 | 2018-02-18T14:57:00 | 2018-02-18T14:57:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,201 | h | #pragma once
#include <string>
using namespace std;
class RtnResources {
public:
static void Init(const wstring& fileName);
static bool IsDebugLoggingEnabled();
static wstring GetOption(const wstring& propertyName, const wstring& defaultValue);
static string GetOption(const string& propertyName, const string& defaultValue);
static int GetOptionInt(const wstring& propertyName, const int defaultValue);
static wstring GetServerType();
static wstring GetServerVersion();
static wstring GetWebServiceURL(wstring serverType, wstring serverVersion, wstring serviceName);
static wstring GetBrowserStartURL();
static wstring GetLogFile();
static wstring GetApplicationTitle();
/**
* Ask user for login and password or use default
*/
static bool GetUserInputLoginSilenty();
/**
* User default login
*/
static wstring GetUserInputDefaultLogin();
/**
* User default password
*/
static wstring GetUserInputDefaultPassword();
/**
* Get auth type that will be used by client
*/
static wstring GetAuthenticationType();
static wstring GetButtonLoginText();
static wstring GetLabelLoginText();
static wstring GetLabelPasswordText();
static wstring GetLabelLoginTitle();
};
| [
"tarwirdur@ya.ru"
] | tarwirdur@ya.ru |
a535f2b2c5fd1f0d1b62f23c17a7e9dec1f97847 | 20aaa121f46faeb4cea2f2a00064744734a95631 | /mojo/services/gles2/gles2_impl.h | a98a48b8896ef9eadf4b387351596b2148c2d1ea | [
"BSD-3-Clause"
] | permissive | michaelhood/chromium | 5808259fdfbc9ef132056d2d9a48d0449a9c3ea2 | 56a0bba55886e67d75e4b4b6719371e050036ae6 | refs/heads/master | 2021-01-15T12:50:20.116977 | 2013-12-01T17:50:22 | 2013-12-01T17:50:22 | 14,848,303 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MOJO_SERVICES_GLES2_GLES2_IMPL_H_
#define MOJO_SERVICES_GLES2_GLES2_IMPL_H_
#include "base/memory/scoped_ptr.h"
#include "mojo/public/bindings/lib/remote_ptr.h"
#include "mojo/public/system/core_cpp.h"
#include "mojom/gles2.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/size.h"
namespace gpu {
class GLInProcessContext;
}
namespace mojo {
namespace services {
class GLES2Impl : public GLES2Stub {
public:
explicit GLES2Impl(ScopedMessagePipeHandle client);
virtual ~GLES2Impl();
virtual void SwapBuffers() OVERRIDE;
void CreateContext(gfx::AcceleratedWidget widget, const gfx::Size& size);
private:
void OnGLContextLost();
scoped_ptr<gpu::GLInProcessContext> gl_context_;
RemotePtr<GLES2Client> client_;
DISALLOW_COPY_AND_ASSIGN(GLES2Impl);
};
} // namespace services
} // namespace mojo
#endif // MOJO_SERVICES_GLES2_GLES2_IMPL_H_
| [
"abarth@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98"
] | abarth@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98 |
bb10bfb6e57be4f3b0799f25d4b8c81be743b02d | 607c9c9b67f15018c60c9e66dd0ac672013347fb | /src/qt/qrcodedialog.cpp | 9517fde5e99789ead3869e8a962cb9f204649e8c | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | backpocket-foundation/1backpocket | 9dc6a30e3b897663234398023b0c226324b5c2b6 | 40a1aa13b584bf8e04c0bcf45b5a61012e8c3287 | refs/heads/master | 2023-07-07T22:08:12.009159 | 2021-08-16T15:35:08 | 2021-08-16T15:35:08 | 396,411,860 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,313 | cpp | #include "qrcodedialog.h"
#include "ui_qrcodedialog.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include <QPixmap>
#include <QUrl>
#include <qrencode.h>
QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) :
QDialog(parent),
ui(new Ui::QRCodeDialog),
model(0),
address(addr)
{
ui->setupUi(this);
setWindowTitle(QString("%1").arg(address));
ui->chkReqPayment->setVisible(enableReq);
ui->lblAmount->setVisible(enableReq);
ui->lnReqAmount->setVisible(enableReq);
ui->lnLabel->setText(label);
ui->btnSaveAs->setEnabled(false);
genCode();
}
QRCodeDialog::~QRCodeDialog()
{
delete ui;
}
void QRCodeDialog::setModel(OptionsModel *model)
{
this->model = model;
if (model)
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void QRCodeDialog::genCode()
{
QString uri = getURI();
if (uri != "")
{
ui->lblQRCode->setText("");
QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
if (!code)
{
ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
return;
}
myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
myImage.fill(0xffffff);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QRcode_free(code);
ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300));
ui->outUri->setPlainText(uri);
}
}
QString QRCodeDialog::getURI()
{
QString ret = QString("Backpocket:%1").arg(address);
int paramCount = 0;
ui->outUri->clear();
if (ui->chkReqPayment->isChecked())
{
if (ui->lnReqAmount->validate())
{
// even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21)
ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value()));
paramCount++;
}
else
{
ui->btnSaveAs->setEnabled(false);
ui->lblQRCode->setText(tr("The entered amount is invalid, please check."));
return QString("");
}
}
if (!ui->lnLabel->text().isEmpty())
{
QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text()));
ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
paramCount++;
}
if (!ui->lnMessage->text().isEmpty())
{
QString msg(QUrl::toPercentEncoding(ui->lnMessage->text()));
ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
paramCount++;
}
// limit URI length to prevent a DoS against the QR-Code dialog
if (ret.length() > MAX_URI_LENGTH)
{
ui->btnSaveAs->setEnabled(false);
ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
return QString("");
}
ui->btnSaveAs->setEnabled(true);
return ret;
}
void QRCodeDialog::on_lnReqAmount_textChanged()
{
genCode();
}
void QRCodeDialog::on_lnLabel_textChanged()
{
genCode();
}
void QRCodeDialog::on_lnMessage_textChanged()
{
genCode();
}
void QRCodeDialog::on_btnSaveAs_clicked()
{
QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)"));
if (!fn.isEmpty())
myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn);
}
void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked)
{
if (!fChecked)
// if chkReqPayment is not active, don't display lnReqAmount as invalid
ui->lnReqAmount->setValid(true);
genCode();
}
void QRCodeDialog::updateDisplayUnit()
{
if (model)
{
// Update lnReqAmount with the current unit
ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit());
}
}
| [
"smokeandcrypto@gmail.com"
] | smokeandcrypto@gmail.com |
6c6530c574ce6167897d0f403a498a2163c0735a | a9affd2c2723e7a22c5b916c75de791b26612182 | /intercambio.cpp | 87c66f240fddbe4c30aaa97168622409fb8108c8 | [] | no_license | Josedm92/UD3 | 17e513b3748bf33c3801be4aa955ef2124612fbd | 01c49a3c577be1cc1e794ac8ab5cf16dae7d2208 | refs/heads/master | 2021-01-10T16:39:13.763364 | 2015-12-14T12:41:14 | 2015-12-14T12:41:14 | 47,365,221 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,168 | cpp | //Programa que los valores de dos números usando una función.
#include <iostream> //Incluimos librería iostream que permite la entrada por teclado y la salida por pantalla.
using namespace std; //Sentencia obligatoria.
//Creación de la función.
void intercambio(int &num1, int &num2){
int aux;
aux = num1;
num1 = num2;
num2=aux;
}
//Inicio del programa.
int main() {
int num1=0, num2=0; //Declaración de variables
//Pedimos dos números por pantalla.
cout << "Introduce el primer número: ";
cin >> num1;
cout << "Introduce el segundo número: ";
cin >> num2;
//Sacamos por pantalla el valor inicial de ambos números
cout << "\nInicialmente el primer número vale: " << num1 << endl;
cout << "Inicialmente el segundo número vale: " << num2 << endl;
//Llamamos a la función para intercambiar el valor de ambos números.
intercambio(num1,num2);
//Sacamos por pantalla el valor de los números tras el intercambio.
cout << "\nDespués del intercambio el primer número vale: " << num1 << endl;
cout << "Después del intercambio el segundo número vale: " << num2 << endl;
}
| [
"josedm92@gmail.com"
] | josedm92@gmail.com |
9bc22ed59af7a3dc3bedf757b5e936ed6df81fc0 | 4e5d07a9eb881defd7923a4575809259522bd25f | /atcoder/abc/211-220/214/c.cpp | f85f0c56bf62a324861240481776bea2d012d6f6 | [] | no_license | kt117/ProCom | c81e6c55c3f4b329c79755f43e8154e297328174 | c5547429560100728cf15a8a8a696aa8c6c0317b | refs/heads/master | 2022-05-06T15:41:01.639231 | 2022-04-09T17:23:21 | 2022-04-09T17:23:21 | 254,284,537 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 715 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
const ll MOD = 1e9+7;
const ll INF = 1e18;
#define rep(i,m,n) for(ll i = (m); i <= (n); i++)
#define zep(i,m,n) for(ll i = (m); i < (n); i++)
#define rrep(i,m,n) for(ll i = (m); i >= (n); i--)
#define print(x) cout << (x) << endl;
#define printa(x,m,n) for(int i = (m); i <= n; i++){cout << (x[i]) << " ";} cout<<endl;
int main(){
cin.tie(0); ios::sync_with_stdio(false);
ll n; cin >> n;
ll s[n]; zep(i, 0, n)cin >> s[i];
ll t[n]; zep(i, 0, n)cin >> t[i];
zep(i, 0, 3 * n){
t[(i + 1) % n] = min(t[(i + 1) % n], t[i % n] + s[i % n]);
}
zep(i, 0, n)print(t[i])
return 0;
} | [
"k.tohyama17@gmail.com"
] | k.tohyama17@gmail.com |
1b1f69640ec22ce529d0de2c1b855cf802971267 | b78f8189953687abe8a3ea5c0d9aee56aeae31ca | /Mashiro/Graphics/src/RenderTarget.cpp | 6b0d264c8d3c5cec445731a0b657df8ea885efcb | [] | no_license | peterkinalex/Yoserusu | 97c6249643ef66f108c92401a254eb51a6e1c576 | 63abdb523fede1b6ff58cf029364bceaedbb510f | refs/heads/master | 2020-12-28T19:57:24.277082 | 2014-06-01T09:21:39 | 2014-06-01T09:58:51 | 58,017,800 | 1 | 1 | null | 2016-05-04T02:48:40 | 2016-05-04T02:48:40 | null | UTF-8 | C++ | false | false | 638 | cpp | #include "Mashiro/Mashiro.h"
#include "Mashiro/Graphics/RenderTarget.h"
#include "Mashiro/Graphics/src/RenderTargetImpl.h"
#include "Mashiro/Graphics/src/GraphicsManagerImpl.h"
namespace Mashiro{
namespace Graphics{
RenderTarget RenderTarget::create( int w, int h, RenderFormat textureFormat ){
RenderTarget r;
r.mImpl = NEW Impl( w, h, textureFormat, gManagerImpl->dxDevice() );
return r;
}
void RenderTarget::targetTexture(const char* name) {
ASSERT( mImpl && "Graphics::VertexBuffer : This is empty Object" );
mImpl->targetTexture( name );
}
#define TYPE RenderTarget
#include "Mashiro/Base/Impl/ReferenceTypeTemplate.h"
}
} | [
"marisa.love0925@gmail.com"
] | marisa.love0925@gmail.com |
602c0f6cc6eb908a87ffd679b6e7571be73a652a | 11dcefc3768cc67f6563f7e0e4713bae740cad63 | /suntlee/week1/star8.cpp | 22d9c62ae6b05c166a58773bed413aaa054439da | [] | no_license | 42somoim/42somoim1 | dac54edee33aadf1a17f60768446e5faf07ed952 | 039e00085290d048a7345bcec7db797e4c7330d2 | refs/heads/master | 2023-05-06T13:07:01.242428 | 2021-05-28T12:07:45 | 2021-05-28T12:07:45 | 280,406,020 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 534 | cpp | #include <iostream>
int main()
{
int n;
std::cin >> n;
for (int i = 0; i < n; i++){
for (int j = 0; j < i + 1; j++)
std::cout << '*';
for (int j = 0; j < 2 * (n - i - 1); j++)
std::cout << ' ';
for (int j = 0; j < i + 1; j++)
std::cout << '*';
std::cout << '\n';
}
for (int i = n - 2; i >= 0; i--){
for (int j = 0; j < i + 1; j++)
std::cout << '*';
for (int j = 0; j < 2 * (n - i - 1); j++)
std::cout << ' ';
for (int j = 0; j < i + 1; j++)
std::cout << '*';
std::cout << '\n';
}
return 0;
}
| [
"suntlee@c5r5s5.42seoul.kr"
] | suntlee@c5r5s5.42seoul.kr |
442cbc4e7242aca630cbd017377bcea8ebc81d14 | d778ba8c334b7ad84b57a0ce186d9f470ee0c02d | /Project4/Project4/client.cpp | 731fd22899c477f43408e4c2c1835df568de29d3 | [] | no_license | kevin7600/CSCI420Graphics | 9a3bcc067f13614da6f12eded7b0ea6df34fc546 | 7e64e2666ba3ff3e0c0cd045134475940c4d7e7a | refs/heads/master | 2021-06-27T17:01:52.257018 | 2017-09-19T04:36:52 | 2017-09-19T04:36:52 | 104,026,155 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,063 | cpp | #include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
struct sockaddr_in{
int sin_family;
int sin_port;
int sin_adrr;
int sin_zero[8];
};
int socket(int family, int type, int protocal){
}
int connect(int socket, int server_addr, int length){
}
int send(int socket, string message, int length,bool flag){
}
int recv(int socket, buffr, length, flag){
}
int close(int socket){
}
int main{
int sock;
if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
ERR_EXIT("socket");
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT_NUMBER);
servaddr.sin_addr.s_addr = inet_addr(IP_ADDR);
if (connect(sock, (struct sockaddr*) &servaddr, sizeof(servaddr)) < 0){
ERR_EXIT("connect");
}
while (true){
cout << "HI" << endl;
}
//communicate with server
send(sock, sendbuf, strlen(sendbuf), 0);
recv(sock, recvbuf, sizeof(recvbuf), 0);
close(sock);
return 0;
} | [
"tankevin@usc.edu"
] | tankevin@usc.edu |
f944d9bfdcf2c779939a3df182c6e5fa3bef07d4 | 77bcf677a137a207e5a8699e5f0d936e6be0f311 | /tests.cpp | b7ac7d89cfb6e421fc0fda5003baf6ec3c04bcb0 | [] | no_license | Lissee/Base64 | ba3d2c2d279d1327c5be22e696a51e169714384a | 6dbfaa89a2da4e8e251e0a0ecb598cdb0f98e997 | refs/heads/main | 2023-02-12T15:46:42.607560 | 2021-01-13T04:54:07 | 2021-01-13T04:54:07 | 329,197,593 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,442 | cpp | #include <iostream>
#include "gtest/gtest.h"
#include "main.h"
TEST(input, inputs){
string inp = "Hello word!";
testing::internal::CaptureStdout();
Codding(Base64Table, inp);
EXPECT_EQ(testing::internal::GetCapturedStdout(), "SGVsbG8gd29yZCE=");
string inp_1 = "ABQWERTYUIOP{}ASDFGHJKL:ZXCVBNM?!1234567890+-/";
testing::internal::CaptureStdout();
Codding(Base64Table, inp_1);
EXPECT_EQ(testing::internal::GetCapturedStdout(), "QUJRV0VSVFlVSU9Qe31BU0RGR0hKS0w6WlhDVkJOTT8hMTIzNDU2Nzg5MCstLw==");
string inp_2 = "Ny kak-to tak:)";
testing::internal::CaptureStdout();
Codding(Base64Table, inp_2);
EXPECT_EQ(testing::internal::GetCapturedStdout(), "Tnkga2FrLXRvIHRhazop");
string inp_3 = "1. Crocodile is longer than green Proof: crocodile is long both on top and bottom, and green is only on top.";
testing::internal::CaptureStdout();
Codding(Base64Table, inp_3);
EXPECT_EQ(testing::internal::GetCapturedStdout(), "MS4gQ3JvY29kaWxlIGlzIGxvbmdlciB0aGFuIGdyZWVuIFByb29mOiBjcm9jb2RpbGUgaXMgbG9uZyBib3RoIG9uIHRvcCBhbmQgYm90dG9tLCBhbmQgZ3JlZW4gaXMgb25seSBvbiB0b3Au");
}
TEST(out, outputs){
string inp = "SGVsbG8gd29ybGQ=";
testing::internal::CaptureStdout();
Decodding(Base64Table, inp);
EXPECT_EQ(testing::internal::GetCapturedStdout(), "Hello world");
string inp_1 = "QUJRV0VSVFlVSU9Qe31BU0RGR0hKS0w6WlhDVkJOTT8hMTIzNDU2Nzg5MCstLw==";
//testing::internal::CaptureStdout();
std::string expected = "ABQWERTYUIOP{}ASDFGHJKL:ZXCVBNM?!1234567890+-/";
Decodding(Base64Table, inp_1);
EXPECT_EQ(testing::internal::GetCapturedStdout(), "ABQWERTYUIOP{}ASDFGHJKL:ZXCVBNM?!1234567890+-/");
string inp_2 = "QSB2aSBwb3N0YXZpdGUgbW5lIHphY2hldD86KQ==";
testing::internal::CaptureStdout();
Decodding(Base64Table, inp_2);
EXPECT_EQ(testing::internal::GetCapturedStdout(), "A vi postavite mne zachet?:)");
string inp_3 = "MS4gQ3JvY29kaWxlIGlzIGxvbmdlciB0aGFuIGdyZWVuIFByb29mOiBjcm9jb2RpbGUgaXMgbG9uZyBib3RoIG9uIHRvcCBhbmQgYm90dG9tLCBhbmQgZ3JlZW4gaXMgb25seSBvbiB0b3Au)";
testing::internal::CaptureStdout();
Decodding(Base64Table, inp_3);
EXPECT_EQ(testing::internal::GetCapturedStdout(), "1. Crocodile is longer than green Proof: crocodile is long both on top and bottom, and green is only on top.");
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| [
"kositcyna.am@students.dvfu.ru"
] | kositcyna.am@students.dvfu.ru |
bcea0f44e4552fde574fb3898d44780944f66406 | cc42472c51d1ca5f2e27106612e2919f3d3799f2 | /src/httprpc.cpp | 1b65a18a2af6021a2c857d913a0e58fa7f807839 | [
"MIT"
] | permissive | OBLMFGJE/CarbonZero | 53b743559f7d5f6ebeedb9d0a29652d38f654a2f | c2981581287101c33915df09aa4348a74a3547f3 | refs/heads/master | 2022-01-10T06:36:47.325778 | 2019-06-23T03:52:23 | 2019-06-23T03:52:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,915 | cpp | // Copyright (c) 2015-2017 The Bitcoin Core developers
// Copyright (c) 2017 The CarbonZero developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "httprpc.h"
#include "base58.h"
#include "chainparams.h"
#include "httpserver.h"
#include "rpc/protocol.h"
#include "rpc/server.h"
#include "random.h"
#include "sync.h"
#include "util.h"
#include "utilstrencodings.h"
#include "ui_interface.h"
#include <boost/algorithm/string.hpp> // boost::trim
/** Simple one-shot callback timer to be used by the RPC mechanism to e.g.
* re-lock the wellet.
*/
class HTTPRPCTimer : public RPCTimerBase
{
public:
HTTPRPCTimer(struct event_base* eventBase, boost::function<void(void)>& func, int64_t millis) :
ev(eventBase, false, func)
{
struct timeval tv;
tv.tv_sec = millis/1000;
tv.tv_usec = (millis%1000)*1000;
ev.trigger(&tv);
}
private:
HTTPEvent ev;
};
class HTTPRPCTimerInterface : public RPCTimerInterface
{
public:
HTTPRPCTimerInterface(struct event_base* base) : base(base)
{
}
const char* Name()
{
return "HTTP";
}
RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis)
{
return new HTTPRPCTimer(base, func, millis);
}
private:
struct event_base* base;
};
/* Pre-base64-encoded authentication token */
static std::string strRPCUserColonPass;
/* Stored RPC timer interface (for unregistration) */
static HTTPRPCTimerInterface* httpRPCTimerInterface = 0;
static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST)
nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND)
nStatus = HTTP_NOT_FOUND;
std::string strReply = JSONRPCReply(NullUniValue, objError, id);
req->WriteHeader("Content-Type", "application/json");
req->WriteReply(nStatus, strReply);
}
static bool RPCAuthorized(const std::string& strAuth)
{
if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
return false;
if (strAuth.substr(0, 6) != "Basic ")
return false;
std::string strUserPass64 = strAuth.substr(6);
boost::trim(strUserPass64);
std::string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)
{
// JSONRPC handles only POST
if (req->GetRequestMethod() != HTTPRequest::POST) {
req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
return false;
}
// Check authorization
std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
if (!authHeader.first) {
req->WriteReply(HTTP_UNAUTHORIZED);
return false;
}
if (!RPCAuthorized(authHeader.second)) {
LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", req->GetPeer().ToString());
/* Deter brute-forcing
If this results in a DoS the user really
shouldn't have their RPC port exposed. */
MilliSleep(250);
req->WriteReply(HTTP_UNAUTHORIZED);
return false;
}
JSONRequest jreq;
try {
// Parse request
UniValue valRequest;
if (!valRequest.read(req->ReadBody()))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
std::string strReply;
// singleton request
if (valRequest.isObject()) {
jreq.parse(valRequest);
UniValue result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, NullUniValue, jreq.id);
// array of requests
} else if (valRequest.isArray())
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
req->WriteHeader("Content-Type", "application/json");
req->WriteReply(HTTP_OK, strReply);
} catch (const UniValue& objError) {
JSONErrorReply(req, objError, jreq.id);
return false;
} catch (const std::exception& e) {
JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
return false;
}
return true;
}
static bool InitRPCAuthentication()
{
if (mapArgs["-rpcpassword"] == "")
{
LogPrintf("No rpcpassword set - using random cookie authentication\n");
if (!GenerateAuthCookie(&strRPCUserColonPass)) {
uiInterface.ThreadSafeMessageBox(
_("Error: A fatal internal error occurred, see debug.log for details"), // Same message as AbortNode
"", CClientUIInterface::MSG_ERROR);
return false;
}
} else {
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
}
return true;
}
bool StartHTTPRPC()
{
LogPrint("rpc", "Starting HTTP RPC server\n");
if (!InitRPCAuthentication())
return false;
RegisterHTTPHandler("/", true, HTTPReq_JSONRPC);
assert(EventBase());
httpRPCTimerInterface = new HTTPRPCTimerInterface(EventBase());
RPCRegisterTimerInterface(httpRPCTimerInterface);
return true;
}
void InterruptHTTPRPC()
{
LogPrint("rpc", "Interrupting HTTP RPC server\n");
}
void StopHTTPRPC()
{
LogPrint("rpc", "Stopping HTTP RPC server\n");
UnregisterHTTPHandler("/", true);
if (httpRPCTimerInterface) {
RPCUnregisterTimerInterface(httpRPCTimerInterface);
delete httpRPCTimerInterface;
httpRPCTimerInterface = 0;
}
}
| [
"root@ip-172-31-30-236.ec2.internal"
] | root@ip-172-31-30-236.ec2.internal |
b65f24346b5793f63386ff9e9425a55ef4ae0d86 | 6e3b592de89cb3e7d594993c784e7059bdb2a9ae | /Source/AllProjects/Drivers/MQTT/Test/MQTTTest.cpp | 094f589b2def6537330e0cacd662db120e921f21 | [
"MIT"
] | permissive | jjzhang166/CQC | 9aae1b5ffeddde2c87fafc3bb4bd6e3c7a98a1c2 | 8933efb5d51b3c0cb43afe1220cdc86187389f93 | refs/heads/master | 2023-08-28T04:13:32.013199 | 2021-04-16T14:41:21 | 2021-04-16T14:41:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,899 | cpp | //
// FILE NAME: MQTTTest.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 02/09/2019
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// We need a little test program to help test out the MQTT driver by publishing
// some values to the test server that we can then set up the server to subscribe to.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $Log$
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CIDEncode.hpp"
#include "CIDSock.hpp"
#include "CIDSChan.hpp"
#include "CQCKit.hpp"
#include "CQCMQTT.hpp"
#include "MQTTSh.hpp"
// ---------------------------------------------------------------------------
// Forward references
// ---------------------------------------------------------------------------
tCIDLib::EExitCodes eMainThreadFunc(TThread& thrThis, tCIDLib::TVoid* pData);
// ---------------------------------------------------------------------------
// Do the magic main module code
// ---------------------------------------------------------------------------
CIDLib_MainModule(TThread(L"MQTTTestMainThread", eMainThreadFunc))
tCIDLib::TCard2 c2NextPacketId = 1;
TInConsole conIn(kCIDLib::True, 16);
TOutConsole conOut;
tCIDLib::TEncodedTime enctNextPing;
TMQTTInMsg msgWaitRep(2048);
TTextFileOutStream strmTrace;
TCIDSockStreamBasedDataSrc* pcdsMQTT;
TTime tmTrace;
static tCIDLib::TVoid SendMsg(TMQTTOutMsg& msgToSend)
{
msgToSend.SendOn(*pcdsMQTT);
msgToSend.LogTo(strmTrace, tmTrace);
}
// To process async msgs
static tCIDLib::TVoid ProcessMsg(TMQTTInMsg& msgNew)
{
if (msgNew.ePacketType() == tCQCMQTT::EPacketTypes::Publish)
{
//
// If it's a publish msg, and the QOS is 1, we need to ack it. If it's
// QOS 2 we need to send a received msg
//
if (msgNew.eExtractPubQOS() == tCQCMQTT::EQOSLevs::Q1)
{
TMQTTOutMsg msgAck(16);
msgAck.BuildPubAckMsg(msgNew.c2PacketId());
SendMsg(msgAck);
}
else if (msgNew.eExtractPubQOS() == tCQCMQTT::EQOSLevs::Q2)
{
TMQTTOutMsg msgAck(16);
msgAck.BuildPubRecMsg(msgNew.c2PacketId());
SendMsg(msgAck);
}
}
else if (msgNew.ePacketType() == tCQCMQTT::EPacketTypes::PubRel)
{
//
// We don't bother to check whether we have such a pending publish
// for this little test
//
TMQTTOutMsg msgAck(16);
msgAck.BuildPubCompMsg(msgNew.c2PacketId());
SendMsg(msgAck);
}
}
static tCIDLib::TBoolean
bWaitReply( const tCQCMQTT::EPacketTypes eWaitType
, const tCIDLib::TCard2 c2WaitId
, TMQTTInMsg& msgToFill
, const tCIDLib::TCard4 c4WaitMSs)
{
tCIDLib::TEncodedTime enctCur = TTime::enctNow();
tCIDLib::TEncodedTime enctEnd = enctCur + (c4WaitMSs * kCIDLib::enctOneMilliSec);
tCIDLib::TBoolean bRet = kCIDLib::False;
while (!bRet && (enctCur < enctEnd))
{
// For for up to the remaining time for data
if (pcdsMQTT->bDataAvail(enctEnd))
{
msgToFill.ParseFrom(*pcdsMQTT);
msgToFill.LogTo(strmTrace, tmTrace);
enctNextPing = TTime::enctNowPlusSecs(45);
//
// If either they aren't waiting for any particular type or we
// got the one they were waiting for, return true.
//
bRet = (eWaitType == tCQCMQTT::EPacketTypes::Count)
|| msgToFill.bIsThisMsg(eWaitType, c2WaitId);
// Process it either way
ProcessMsg(msgToFill);
}
enctCur = TTime::enctNow();
}
return bRet;
}
//
// Does a publish operation with a binary value. We expect to get a topic, a
// value which has to be convertable to an integer, and a number of bytes (1, 2, 4).
// Float values have to be sent as text.
//
// pubbin Sensors/Sensor10 [signed|unsigned] 133 2 [big|little]
//
// You can optionally indicate the endianness. If not indicated it is big since
// MQTT is normally big.
//
static tCIDLib::TVoid DoBinPublish(const tCIDLib::TStrList& colParms)
{
tCIDLib::TInt8 i8Val;
tCIDLib::TCard4 c4Bytes;
if ((colParms.c4ElemCount() < 5)
|| (colParms.c4ElemCount() > 6)
|| !colParms[4].bToCard4(c4Bytes, tCIDLib::ERadices::Dec)
|| ((c4Bytes != 1) && (c4Bytes != 2) && (c4Bytes != 4))
|| !colParms[3].bToInt8(i8Val, tCIDLib::ERadices::Auto)
|| (!colParms[2].bCompareI(L"signed") && !colParms[2].bCompareI(L"unsigned")))
{
conOut << L"\n Form is: PubBin [topic] [signed|unsigned] [int value] [bytes]\n"
<< L" where bytes is 1, 2 or 4.\n\n"
<< L" An optional final parameter of [big|little] can be passed to indicate\n"
<< L" the endianness. Defaults to big if not indicated.\n"
<< kCIDLib::EndLn;
return;
}
// If we got an explicit endianness get that, else big
tCIDLib::TBoolean bBigEndian = kCIDLib::True;
if (colParms.c4ElemCount() == 6)
{
if (colParms[5].bCompareI(L"big"))
bBigEndian = kCIDLib::True;
else if (colParms[5].bCompareI(L"little"))
bBigEndian = kCIDLib::False;
else
{
conOut << L"The last parameter must be big or little" << kCIDLib::NewEndLn;
return;
}
}
//
// We need to create the binary payload, so create a stream and set its
// endianness based on the above. That will insure it gets set up to correctly
// write out the payload we want.
//
TBinMBufOutStream strmTar(16UL);
if (bBigEndian)
strmTar.eEndianMode(tCIDLib::EEndianModes::Big);
else
strmTar.eEndianMode(tCIDLib::EEndianModes::Little);
// For convenience get the signed flag to a bool
const tCIDLib::TBoolean bSigned = colParms[2].bCompareI(L"signed");
//
// Based on the foramt, set up the min/max values and format out the new
// value cast to its actual type. We go ahead and stream it out even though
// we might reject it as out of range below, since that is get's us where
// we want to be with the last fuss.
//
tCIDLib::TInt8 i8MinVal = 0;
tCIDLib::TInt8 i8MaxVal;
if (bSigned)
{
if (c4Bytes == 1)
{
i8MinVal = kCIDLib::i1MinInt;
i8MaxVal = kCIDLib::i1MaxInt;
strmTar << tCIDLib::TInt1(i8Val);
}
else if (c4Bytes == 2)
{
i8MinVal = kCIDLib::i2MinInt;
i8MaxVal = kCIDLib::i2MaxInt;
strmTar << tCIDLib::TInt2(i8Val);
}
else if (c4Bytes == 4)
{
i8MinVal = kCIDLib::i4MinInt;
i8MaxVal = kCIDLib::i4MaxInt;
strmTar << tCIDLib::TInt4(i8Val);
}
}
else
{
if (c4Bytes == 1)
{
i8MaxVal = kCIDLib::c1MaxCard;
strmTar << tCIDLib::TCard1(i8Val);
}
else if (c4Bytes == 2)
{
i8MaxVal = kCIDLib::c2MaxCard;
strmTar << tCIDLib::TCard2(i8Val);
}
else if (c4Bytes == 4)
{
i8MaxVal = kCIDLib::c4MaxCard;
strmTar << tCIDLib::TCard4(i8Val);
}
}
strmTar.Flush();
// If the value is out of range, reject it
if ((i8Val < i8MinVal) || (i8Val > i8MaxVal))
{
conOut << L"\n The value is too large for its format"
<< kCIDLib::NewEndLn;
return;
}
// Set up the publish msg
TMQTTOutMsg msgPub(256);
msgPub.BuildPublishMsg
(
colParms[1]
, tCQCMQTT::EQOSLevs::Q1
, kCIDLib::True
, c2NextPacketId++
, strmTar.mbufData()
, strmTar.c4CurSize()
);
SendMsg(msgPub);
// It was set up for Q0, so we should just get a pub ack
const tCIDLib::TBoolean bRes = bWaitReply
(
tCQCMQTT::EPacketTypes::PubAck, msgPub.c2PacketId(), msgWaitRep, 2500
);
if (bRes)
conOut << L"Got ack for publish request";
else
conOut << L"No ack for publish request!";
conOut << kCIDLib::NewLn;
}
//
// Does a publish operation with a text string. We expect to get a topic, an encoding,
// and a string to send. We send it as binary format, just the encoded bytes of the text.
//
// pubbintext [encoding] Sensors/Temp1 45.1
// pubbintext [encoding] Lights/Kitchen on
//
static tCIDLib::TVoid DoBinTextPublish(const tCIDLib::TStrList& colParms)
{
if (colParms.c4ElemCount() != 4)
{
conOut << L"\n Form is: PubBinText [encoding] [topic] [value]" << kCIDLib::EndLn;
return;
}
// Try to create a converter for the requested encoding
TTextConverter* pcvtEncode = facCIDEncode().ptcvtMake(colParms[1]);
if (!pcvtEncode)
{
conOut << L"The encoding '" << colParms[1] << L"' is not supported"
<< kCIDLib::NewLn;
return;
}
TJanitor<TTextConverter> janCvt(pcvtEncode);
// It might be multi-line, so replace any \n characters with new lines
TString strExpText(colParms[3]);
tCIDLib::TCard4 c4At(0);
strExpText.bReplaceSubStr(L"\\n", L"\n", c4At, kCIDLib::True);
// Now let's try to transcode it, do a liberal guess at space needed
THeapBuf mbufText(strExpText.c4Length() * 2);
tCIDLib::TCard4 c4PLBytes;
pcvtEncode->c4ConvertTo(strExpText, mbufText, c4PLBytes);
// Seemed to work so let's send it
TMQTTOutMsg msgPub(c4PLBytes + colParms[2].c4Length() + 64);
msgPub.BuildPublishMsg
(
colParms[2]
, tCQCMQTT::EQOSLevs::Q1
, kCIDLib::True
, c2NextPacketId++
, mbufText
, c4PLBytes
);
SendMsg(msgPub);
// It was set up for Q0, so we should just get a pub ack
const tCIDLib::TBoolean bRes = bWaitReply
(
tCQCMQTT::EPacketTypes::PubAck, msgPub.c2PacketId(), msgWaitRep, 2500
);
if (bRes)
conOut << L"Got ack for publish request";
else
conOut << L"No ack for publish request!";
conOut << kCIDLib::NewLn;
}
//
// Does a publish operation with a text string. We expect to get a topic and a
// string to publish to the topic. We send the text as standard MQTT text format.
//
// pubtext Sensors/Temp1 45.1
// pubtext Lights/Kitchen on
//
static tCIDLib::TVoid DoTextPublish(const tCIDLib::TStrList& colParms)
{
if (colParms.c4ElemCount() != 3)
{
conOut << L"\n Form is: PubText [topic] [value]" << kCIDLib::EndLn;
return;
}
// It might be multi-line, so replace any \n characters with new lines
TString strExpText(colParms[2]);
tCIDLib::TCard4 c4At(0);
strExpText.bReplaceSubStr(L"\\n", L"\n", c4At, kCIDLib::True);
TMQTTOutMsg msgPub(256);
msgPub.BuildPublishMsg
(
colParms[1]
, tCQCMQTT::EQOSLevs::Q1
, kCIDLib::True
, c2NextPacketId++
, strExpText
);
SendMsg(msgPub);
// It was set up for Q0, so we should just get a pub ack
const tCIDLib::TBoolean bRes = bWaitReply
(
tCQCMQTT::EPacketTypes::PubAck, msgPub.c2PacketId(), msgWaitRep, 2500
);
if (bRes)
conOut << L"Got ack for publish request";
else
conOut << L"No ack for publish request!";
conOut << kCIDLib::NewLn;
}
//
// Does a subscribe operation. We expect to get a topic filter and associated
// QOS value.
//
static tCIDLib::TVoid DoSubscribe(const tCIDLib::TStrList& colParms)
{
if (colParms.c4ElemCount() != 3)
{
conOut << L"Publish form is: Subscribe [topicfilter] [QOS]" << kCIDLib::EndLn;
return;
}
// Make sure the QOS can be converted
tCQCMQTT::EQOSLevs eQOS = tCQCMQTT::eXlatEQOSLevs(colParms[2]);
if (eQOS == tCQCMQTT::EQOSLevs::Count)
{
conOut << L"Invalid QOS" << kCIDLib::EndLn;
return;
}
tCQCMQTT::TTopicList colTopics(1);
colTopics.objAdd(TMQTTTopicInfo(colParms[1], eQOS));
TMQTTOutMsg msgSub(256);
msgSub.BuildSubscribeMsg(colTopics, c2NextPacketId++);
SendMsg(msgSub);
const tCIDLib::TBoolean bRes = bWaitReply
(
tCQCMQTT::EPacketTypes::SubAck, msgSub.c2PacketId(), msgWaitRep, 2500
);
if (bRes)
{
if (msgWaitRep.c1CodeAt(0) == 0x80)
conOut << L"Got a failure code";
else
conOut << L"Got ack for subscribe, at QOS level " << msgWaitRep.c1CodeAt(0);
}
else
{
conOut << L"No ack for subscribe request!";
}
conOut << kCIDLib::NewLn;
}
//
// This is passed as an idle time callback to the console so that we can
// handle keep alive msgs. And we also check for asyncs and process those.
//
static tCIDLib::TVoid IdleCallback(TObject* const)
{
if (TTime::enctNow() > enctNextPing)
{
enctNextPing = TTime::enctNowPlusSecs(45);
TMQTTOutMsg msgPing(8);
msgPing.BuildPingReqMsg();
SendMsg(msgPing);
}
else
{
if (pcdsMQTT->bDataAvailMS(1))
{
TMQTTInMsg msgAsync(2048);
bWaitReply(tCQCMQTT::EPacketTypes::Count, 0, msgAsync, 5);
}
}
}
// -----------------------------------------------------------------------------
// Program entry point
// -----------------------------------------------------------------------------
tCIDLib::EExitCodes eMainThreadFunc(TThread& thrThis, tCIDLib::TVoid*)
{
// We have to let our calling thread go first
thrThis.Sync();
// Get the standard CQC environmental info
TString strFailReason;
if (!facCQCKit().bLoadEnvInfo(strFailReason, kCIDLib::False))
return tCIDLib::EExitCodes::BadEnvironment;
try
{
// Create an output stream for a msg trace
tmTrace.strDefaultFormat(TTime::strMMDD_24HHMMSS());
TPathStr pathTrace = facCQCKit().strServerDataDir();
pathTrace.AddLevel(L"MQTT");
pathTrace.AddLevel(L"MQTTTestTrace");
pathTrace.AppendExt(L".Txt");
strmTrace.Open
(
pathTrace
, tCIDLib::ECreateActs::CreateAlways
, tCIDLib::EFilePerms::Default
, tCIDLib::EFileFlags::SequentialScan
, tCIDLib::EAccessModes::Write
);
// First we need to create the data source and initialize it
TIPEndPoint ipepTar(L"test.mosquitto.org", 1883, tCIDSock::EAddrTypes::Unspec);
pcdsMQTT = new TCIDSockStreamDataSrc(ipepTar);
pcdsMQTT->Initialize(TTime::enctNowPlusSecs(3));
// And let's send a connect msg and wait for the ack
{
TMQTTOutMsg msgConn(256);
msgConn.BuildConnectMsg
(
L"CQCMQTTTester"
, kCIDLib::True
, 60
, TString::strEmpty()
, TString::strEmpty()
);
SendMsg(msgConn);
enctNextPing = TTime::enctNowPlusSecs(45);
}
// Packet id won't be used here since conn ack doesn't have one
if (!bWaitReply(tCQCMQTT::EPacketTypes::ConnAck, 0, msgWaitRep, 2500))
{
conOut << L"Never got a connection ack" << kCIDLib::EndLn;
return tCIDLib::EExitCodes::Normal;
}
//
// Looks reasonable so enter the user command loop. But we still have to
// wake up periodically and send a keep alive. We use the idle time
// callback of the input console line reader to do this.
//
tCIDLib::TStrList colParms;
TString strCurLn;
while (kCIDLib::True)
{
conOut << L"> " << kCIDLib::FlushIt;
conIn.c4ReadLine(strCurLn, IdleCallback, nullptr);
strCurLn.StripWhitespace();
// Watch for the exit command
if (strCurLn.bCompareI(L"exit"))
break;
// Parse it as a command line
if (!TExternalProcess::c4BreakOutParms(strCurLn, colParms))
{
conOut << L"Invalid command" << kCIDLib::EndLn;
}
else
{
try
{
if (colParms[0].bCompareI(L"pubbin"))
{
DoBinPublish(colParms);
}
else if (colParms[0].bCompareI(L"pubbintext"))
{
DoBinTextPublish(colParms);
}
else if (colParms[0].bCompareI(L"pubtext"))
{
DoTextPublish(colParms);
}
else if (colParms[0].bCompareI(L"subscribe"))
{
DoSubscribe(colParms);
}
else
{
conOut << L"Unknown command: " << colParms[0]
<< kCIDLib::EndLn;
}
}
catch(const TError& errToCatch)
{
conOut << L"An error occurred:\n" << errToCatch
<< kCIDLib::NewEndLn;
}
}
}
// And let's disconnect
TMQTTOutMsg msgDisconn(8);
msgDisconn.BuildDisconnectMsg();
SendMsg(msgDisconn);
// Close the data source
pcdsMQTT->Terminate(TTime::enctNowPlusSecs(2), kCIDLib::True);
delete pcdsMQTT;
}
// Catch any CIDLib runtime errors
catch(const TError& errToCatch)
{
conOut << L"\nA CIDLib runtime error occured during processing. Error:\n"
<< errToCatch << kCIDLib::NewLn << kCIDLib::EndLn;
return tCIDLib::EExitCodes::RuntimeError;
}
//
// Kernel errors should never propogate out of CIDLib, but test for
// them here just in case.
//
catch(const TKrnlError& kerrToCatch)
{
conOut << L"\nA kernel error occured during processing.\nError="
<< kerrToCatch.errcId() << kCIDLib::NewLn << kCIDLib::EndLn;
return tCIDLib::EExitCodes::FatalError;
}
// Catch a general exception
catch(...)
{
conOut << L"\nA general exception occured during processing"
<< kCIDLib::NewLn << kCIDLib::EndLn;
return tCIDLib::EExitCodes::SystemException;
}
return tCIDLib::EExitCodes::Normal;
}
| [
"droddey@charmedquark.com"
] | droddey@charmedquark.com |
b123202e154e1f07a9ff972679143183aeec3296 | 81b9b8ae0e9cc6cf320a95cf373594599d81fe12 | /Components/ErrorList/ErrorList.cpp | f98a8643b3f44dd109060e6443f2241487bec6a3 | [] | no_license | mouchtaris/delta-linux | 1041b9dcc549bda2858dcedbc61087bb73817415 | cca8bd3c1646957cb3203191bb03e80d52f30631 | HEAD | 2016-09-01T19:28:43.257785 | 2014-09-02T05:00:54 | 2014-09-02T05:00:54 | 23,297,561 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,135 | cpp | /**
* ErrorList.cpp
*
* -- IDE Console Output --
*
* List control component for compilation error/warning.
*
* Themistoklis Bourdenas <themis@ics.forth.gr>
* June 2007
*/
#include "ErrorList.h"
#include "StringUtils.h"
#include "PropertyUtils.h"
#include "ImageList.h"
#include "Call.h"
#include "ComponentRegistry.h"
#include "BitmapRegistry.h"
#include "UndefineAllWin32Shit.h"
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#ifndef NO_VLD
#include <vld.h>
#endif
#include "Icons/error.xpm"
#include "Icons/warning.xpm"
namespace ide
{
//-------------------------------------------------------//
//---- Custom Events ------------------------------------//
BEGIN_EVENT_TABLE(ErrorList, ItemListCtrl)
EVT_LIST_ITEM_ACTIVATED(wxID_ANY, ErrorList::onItemActivated)
END_EVENT_TABLE();
//-------------------------------------------------------//
//---- class ErrorList ----------------------------------//
COMPONENT_METADATA(
ErrorList,
_("Errors"),
_("Error list report for the Delta compiler"),
_T("Themistoklis Bourdenas <themis@ics.forth.gr>"),
_T("alpha")
);
IMPLEMENT_WX_COMPONENT_(ErrorList, ItemListCtrl, DockableComponent);
//-----------------------------------------------------------------------
COMPONENT_SET_PROPERTIES_FUNCTION(ErrorList, table)
{
conf::EnumStringProperty* docking = const_cast<conf::EnumStringProperty*>(
conf::safe_prop_cast<const conf::EnumStringProperty>(
table.GetProperty("docking")
)
);
if (docking)
docking->SetOption(5);
}
//-----------------------------------------------------------------------
ErrorList::ErrorList(void)
: counter(0)
{
}
//-----------------------------------------------------------------------
ErrorList::~ErrorList(void)
{
}
//-----------------------------------------------------------------------
wxWindow* ErrorList::GenerateWindow(wxWindow* parent)
{
Create(parent, wxLC_REPORT | wxLC_SINGLE_SEL);
ImageList* images = new ImageList(16,16);
images->Add(_T("Error"), BitmapRegistry::Instance().Get(_T("error")));
images->Add(_T("Warning"), BitmapRegistry::Instance().Get(_T("warning")));
ItemListCtrl::AssignImageList(images, wxIMAGE_LIST_SMALL);
ItemListCtrl::InsertColumn(0, String(), wxLIST_FORMAT_LEFT, 25);
ItemListCtrl::InsertColumn(1, _T("#"), wxLIST_FORMAT_LEFT, 25);
ItemListCtrl::InsertColumn(2, _T("Description"), wxLIST_FORMAT_LEFT, 300);
ItemListCtrl::InsertColumn(3, _T("File"), wxLIST_FORMAT_LEFT, 200);
ItemListCtrl::InsertColumn(4, _T("Line"), wxLIST_FORMAT_LEFT, 50);
//wxTextAttr style = GetDefaultStyle();
//style.SetFont(wxFont(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
//SetDefaultStyle(style);
return this;
}
//-----------------------------------------------------------------------
wxWindow* ErrorList::GetWindow(void)
{
return this;
}
//-----------------------------------------------------------------------
EXPORTED_STATIC(ErrorList, void, Initialize, (void))
{
BitmapRegistry::Instance().Insert(_T("error"), error_xpm);
BitmapRegistry::Instance().Insert(_T("warning"), warning_xpm);
}
//-----------------------------------------------------------------------
EXPORTED_STATIC(ErrorList, void, CleanUp, (void))
{
//BitmapRegistry::Instance().Remove(_T("error"));
//BitmapRegistry::Instance().Remove(_T("warning"));
}
//-----------------------------------------------------------------------
EXPORTED_FUNCTION(ErrorList, void, Append, (const String& type, const String& content, const String& file, uint line))
{
if (type == _T("Error") || type == _T("Warning"))
{
int imageIndex = static_cast<ImageList*>(GetImageList(wxIMAGE_LIST_SMALL))->ResolveImageIndex(type);
assert(imageIndex != -1);
long id = ItemListCtrl::InsertItem(GetItemCount(), imageIndex);
ItemListCtrl::SetItem(id, 1, util::std2str(boost::lexical_cast<std::string>(++counter)));
ItemListCtrl::SetItem(id, 2, content);
ItemListCtrl::SetItem(id, 3, file);
ItemListCtrl::SetItem(id, 4, util::std2str(boost::lexical_cast<std::string>(line)));
}
}
//-----------------------------------------------------------------------
EXPORTED_FUNCTION(ErrorList, void, Clear, (void))
{
ItemListCtrl::DeleteAllItems();
counter = 0;
}
//-----------------------------------------------------------------------
EXPORTED_CMD_STATIC(ErrorList, View, _("/{10}View/{100}Error List\tCtrl+Shift+R"), MT_MAIN, "")
{
EnsureVisibility(s_classId);
}
//-----------------------------------------------------------------------
EXPORTED_SLOT_MEMBER(ErrorList, void, OnWorkspaceLoaded, (const Handle& workspace, const String& uri),
"WorkspaceLoaded")
{
Clear();
}
//-----------------------------------------------------------------------
EXPORTED_SLOT_MEMBER(ErrorList, void, OnWorkStarted, (const std::string workspace, const Handle& root,
const String& task), "WorkStarted")
{
Clear();
}
//-----------------------------------------------------------------------
EXPORTED_SLOT_MEMBER(ErrorList, void, OnCompilationMessage, (const std::string& caller, const UIntList& buildId,
const String& type, const String& content, const String& file, uint line), "CompilationMessage")
{
Append(type, content, file, line);
}
//-----------------------------------------------------------------------
void ErrorList::onItemActivated(wxListEvent& event)
{
String filename;
uint lineno;
wxListItem info;
info.m_itemId = event.GetIndex();
info.m_mask = wxLIST_MASK_TEXT;
info.m_col = 3;
if (GetItem(info))
filename = info.GetText();
info.m_col = 4;
if (GetItem(info))
lineno = boost::lexical_cast<uint>(info.GetText());
Call<void (const String&, int)>(this, "DeltaVM", "GotoSymbolicDocument")(filename, lineno);
}
//-----------------------------------------------------------------------
}
| [
"lilis@09f5c9fd-6ff0-f344-b9e4-4de1b5e69ea1"
] | lilis@09f5c9fd-6ff0-f344-b9e4-4de1b5e69ea1 |
972a6d0fd7b515ac0be07d29ad752faebeb036ef | 4abd8793f2f2cb52fe02837c67e39dfef74b5715 | /mgroovyank/Day 90/Max Rectangle in Binary MatrixI.cpp | 3efa5f130bc596206948d08aa63c5ca056d9c5d2 | [] | no_license | Devang-25/100DaysOfCode | bdab847655490b4421454b4693cfcd6ddc3d4ff5 | 4e3d632be1ecd3b235c03ac593a4ea8ec9562e56 | refs/heads/master | 2021-05-25T12:50:19.956945 | 2020-04-06T17:49:02 | 2020-04-06T17:49:02 | 253,761,487 | 1 | 1 | null | 2020-12-18T18:33:29 | 2020-04-07T10:31:32 | null | UTF-8 | C++ | false | false | 1,170 | cpp | // https://www.interviewbit.com/problems/max-rectangle-in-binary-matrix/
// Time Complexity: O(N^4)
int Solution::maximalRectangle(vector<vector<int> > &A) {
int n = A.size();
int m = A[0].size();
int dp[n][m][n][m];
memset(dp, -1, sizeof(dp));
int area = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
for(int k=i;k<n;k++){
for(int l=j;l<m;l++){
if(i == k && j == l){
dp[i][j][k][l] = (A[i][j] == 1) ? 1 : 0;
area = max(area, dp[i][j][k][l]);
continue;
}
int t1=1, t2=1;
if(l-1>=j){
t1 = dp[i][j][k][l-1];
}
if(k-1>=i){
t2 = dp[i][j][k-1][l];
}
dp[i][j][k][l] = ((t1 == 1) && (t2 == 1) && (A[k][l] == 1)) ? 1 : 0;
if(dp[i][j][k][l] == 1){
area = max(area, (l-j+1)*(k-i+1));
}
}
}
}
}
return area;
}
| [
"noreply@github.com"
] | noreply@github.com |
c6472f4a481add8fde99b50c15a02d3a961e5862 | e773931bdeb9317a5ff7c7e2e6b1012b2645642a | /chromeos/components/diagnostics_ui/backend/telemetry_log_unittest.cc | 18d464dc13bc89cdb823483ab84d238d72b11cf9 | [
"BSD-3-Clause"
] | permissive | SelyanKab/chromium | 21780bcaf7a21d67e3a4fe902aa8fd5d653b374b | ee248e9797404ad1cfcafdc3c0a58729b0f8f88d | refs/heads/master | 2023-03-14T15:02:38.903591 | 2021-03-10T10:21:05 | 2021-03-10T10:21:05 | 234,272,861 | 0 | 0 | BSD-3-Clause | 2020-01-16T08:36:12 | 2020-01-16T08:36:12 | null | UTF-8 | C++ | false | false | 4,626 | cc | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/components/diagnostics_ui/backend/telemetry_log.h"
#include "base/strings/string_number_conversions.h"
#include "chromeos/components/diagnostics_ui/backend/log_test_helpers.h"
#include "chromeos/components/diagnostics_ui/mojom/system_data_provider.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
namespace diagnostics {
namespace {
mojom::SystemInfoPtr CreateSystemInfoPtr(const std::string& board_name,
const std::string& marketing_name,
const std::string& cpu_model,
uint32_t total_memory_kib,
uint16_t cpu_threads_count,
uint32_t cpu_max_clock_speed_khz,
bool has_battery,
const std::string& milestone_version) {
auto version_info = mojom::VersionInfo::New(milestone_version);
auto device_capabilities = mojom::DeviceCapabilities::New(has_battery);
auto system_info = mojom::SystemInfo::New(
board_name, marketing_name, cpu_model, total_memory_kib,
cpu_threads_count, cpu_max_clock_speed_khz, std::move(version_info),
std::move(device_capabilities));
return system_info;
}
} // namespace
class TelemetryLogTest : public testing::Test {
public:
TelemetryLogTest() = default;
~TelemetryLogTest() override = default;
};
TEST_F(TelemetryLogTest, DetailedLogContents) {
const std::string expected_board_name = "board_name";
const std::string expected_marketing_name = "marketing_name";
const std::string expected_cpu_model = "cpu_model";
const uint32_t expected_total_memory_kib = 1234;
const uint16_t expected_cpu_threads_count = 5678;
const uint32_t expected_cpu_max_clock_speed_khz = 91011;
const bool expected_has_battery = true;
const std::string expected_milestone_version = "M99";
mojom::SystemInfoPtr test_info = CreateSystemInfoPtr(
expected_board_name, expected_marketing_name, expected_cpu_model,
expected_total_memory_kib, expected_cpu_threads_count,
expected_cpu_max_clock_speed_khz, expected_has_battery,
expected_milestone_version);
TelemetryLog log;
log.UpdateSystemInfo(test_info.Clone());
const std::string log_as_string = log.GetContents();
const std::vector<std::string> log_lines = GetLogLines(log_as_string);
// Expect one title line and 8 content lines.
EXPECT_EQ(9u, log_lines.size());
EXPECT_EQ("Board Name: " + expected_board_name, log_lines[1]);
EXPECT_EQ("Marketing Name: " + expected_marketing_name, log_lines[2]);
EXPECT_EQ("CpuModel Name: " + expected_cpu_model, log_lines[3]);
EXPECT_EQ(
"Total Memory (kib): " + base::NumberToString(expected_total_memory_kib),
log_lines[4]);
EXPECT_EQ(
"Thread Count: " + base::NumberToString(expected_cpu_threads_count),
log_lines[5]);
EXPECT_EQ("Cpu Max Clock Speed (kHz): " +
base::NumberToString(expected_cpu_max_clock_speed_khz),
log_lines[6]);
EXPECT_EQ("Milestone Version: " + expected_milestone_version, log_lines[7]);
EXPECT_EQ("Has Battery: " + base::NumberToString(expected_has_battery),
log_lines[8]);
}
TEST_F(TelemetryLogTest, ChangeContents) {
const std::string expected_board_name = "board_name";
const std::string expected_marketing_name = "marketing_name";
const std::string expected_cpu_model = "cpu_model";
const uint32_t expected_total_memory_kib = 1234;
const uint16_t expected_cpu_threads_count = 5678;
const uint32_t expected_cpu_max_clock_speed_khz = 91011;
const bool expected_has_battery = true;
const std::string expected_milestone_version = "M99";
mojom::SystemInfoPtr test_info = CreateSystemInfoPtr(
expected_board_name, expected_marketing_name, expected_cpu_model,
expected_total_memory_kib, expected_cpu_threads_count,
expected_cpu_max_clock_speed_khz, expected_has_battery,
expected_milestone_version);
TelemetryLog log;
log.UpdateSystemInfo(test_info.Clone());
test_info->board_name = "new board_name";
log.UpdateSystemInfo(test_info.Clone());
const std::string log_as_string = log.GetContents();
const std::vector<std::string> log_lines = GetLogLines(log_as_string);
EXPECT_EQ("Board Name: new board_name", log_lines[1]);
}
} // namespace diagnostics
} // namespace chromeos
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
8f9626d47e7968f1ee67983ce305a6cd2b808929 | d43e1ec775f194c2dd6d45007c50ed999571bd5d | /Contests/NAIPC/2019/It's a Mod, Mod, Mod, Mod World/mod.cpp | ac4cfd87e3596a1e8bb847ff4cbbc4b8579c0a54 | [] | no_license | marcoskwkm/code | 842fd498ec625b25f361b435f0bca843b8d81967 | 636866a7ee28f9f24da62c5dcf93dc1bce7a496e | refs/heads/master | 2022-10-28T16:40:50.710771 | 2022-09-24T20:10:59 | 2022-09-24T20:10:59 | 57,255,944 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 734 | cpp | #include <bits/stdc++.h>
using namespace std;
#define debug(args...) fprintf(stderr,args)
typedef long long lint;
typedef pair<int, int> pii;
typedef pair<lint, lint> pll;
typedef tuple<int, int, int> tiii;
const int INF = 0x3f3f3f3f;
const lint LINF = 0x3f3f3f3f3f3f3f3fll;
lint solve(lint p, lint q, lint n) {
lint qq = p / q;
lint ans = n * (n + 1) / 2 * qq;
p %= q;
if (!p) return ans;
lint m = n * p / q;
return ans + n * m - solve(q, p, m) + n / q;
}
int main() {
int t;
for (cin >> t; t--;) {
lint p, q, n;
scanf("%lld%lld%lld", &p, &q, &n);
lint d = __gcd(p, q);
printf("%lld\n", n * (n + 1) / 2 * p - q * solve(p / d, q / d, n));
}
return 0;
}
| [
"marcoskwkm@gmail.com"
] | marcoskwkm@gmail.com |
9f74f7b53d72308e6517f090e54154e4ef730549 | 9dd7799dffb2c9d27b8988d50bc9f96cdbc6d1a2 | /DispIdStructTable.cpp | a58af82ecb8f8778ddffd6b51830de0e0962b349 | [] | no_license | lwyoo/DisplayIDGen | a6f1751cb3eeb419d5d1fc240012042fc474a830 | cc1aefe82bf785fc42e954b5b9a9fe3fb6fa7e4a | refs/heads/master | 2022-07-29T02:04:29.390193 | 2020-05-25T02:38:31 | 2020-05-25T02:38:31 | 265,779,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,033 | cpp | #include "DispIdStructTable.h"
namespace cluster {
namespace dispID {
stDispID tableID[] = {
{eDispId_12VBatteryReset, McuServiceType::EnumEventID::eDispId_RENAME_12VBatteryReset, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_2StepESC_Off, McuServiceType::EnumEventID::eDispId_RENAME_2StepESC_Off, McuServiceType::GroupLevel::eDispId_Group_2_Mini},
{eDispId_2WD_Mode, McuServiceType::EnumEventID::eDispId_RENAME_2WD_Mode, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_4WD_Onoff, McuServiceType::EnumEventID::eDispId_RENAME_4WD_Onoff, McuServiceType::GroupLevel::eDispId_Group_2_Mini},
{eDispId_AAF_Fail, McuServiceType::EnumEventID::eDispId_RENAME_AAF_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_ADAS_SettingMode, McuServiceType::EnumEventID::eDispId_RENAME_ADAS_SettingMode, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_AHB_Check, McuServiceType::EnumEventID::eDispId_RENAME_AHB_Check, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_AHB_CheckStop, McuServiceType::EnumEventID::eDispId_RENAME_AHB_CheckStop, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_AV_Mode, McuServiceType::EnumEventID::eDispId_RENAME_AV_Mode, McuServiceType::GroupLevel::eDispId_Group_2_Mini},
{eDispId_AirCleaning_Onoff, McuServiceType::EnumEventID::eDispId_RENAME_AirCleaning_Onoff, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_Attention_Assist, McuServiceType::EnumEventID::eDispId_RENAME_Attention_Assist, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_AuxBattSaverPlus, McuServiceType::EnumEventID::eDispId_RENAME_AuxBattSaverPlus, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_BCA_Blockage, McuServiceType::EnumEventID::eDispId_RENAME_BCA_Blockage, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_BCA_Fail, McuServiceType::EnumEventID::eDispId_RENAME_BCA_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_BCA_R, McuServiceType::EnumEventID::eDispId_RENAME_BCA_R, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_BCA_R_PLUS, McuServiceType::EnumEventID::eDispId_RENAME_BCA_R_PLUS, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_BCM_Warning_Engine, McuServiceType::EnumEventID::eDispId_RENAME_BCM_Warning_Engine, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_BCM_Warning_P, McuServiceType::EnumEventID::eDispId_RENAME_BCM_Warning_P, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_BCW_Blockage, McuServiceType::EnumEventID::eDispId_RENAME_BCW_Blockage, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_BCW_Fail, McuServiceType::EnumEventID::eDispId_RENAME_BCW_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_BCW_Mirror_Fail, McuServiceType::EnumEventID::eDispId_RENAME_BCW_Mirror_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_BCW_Off_Noti, McuServiceType::EnumEventID::eDispId_RENAME_BCW_Off_Noti, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_BCW_Onoff, McuServiceType::EnumEventID::eDispId_RENAME_BCW_Onoff, McuServiceType::GroupLevel::eDispId_Group_2_Mini},
{eDispId_BCW_Warn, McuServiceType::EnumEventID::eDispId_RENAME_BCW_Warn, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_BVM, McuServiceType::EnumEventID::eDispId_RENAME_BVM, McuServiceType::GroupLevel::eDispId_Group_2_Exception},
{eDispId_Batt_HighTemp, McuServiceType::EnumEventID::eDispId_RENAME_Batt_HighTemp, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_Batt_LowTemp, McuServiceType::EnumEventID::eDispId_RENAME_Batt_LowTemp, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_Batt_LowTemp_IgnOff, McuServiceType::EnumEventID::eDispId_RENAME_Batt_LowTemp_IgnOff, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_BatteryDischargeWarning, McuServiceType::EnumEventID::eDispId_RENAME_BatteryDischargeWarning, McuServiceType::GroupLevel::eDispId_Group_6},
{eDispId_CSCD_ModeChanged_Full, McuServiceType::EnumEventID::eDispId_RENAME_CSCD_ModeChanged_Full, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_CSCD_ModeChanged_Mini, McuServiceType::EnumEventID::eDispId_RENAME_CSCD_ModeChanged_Mini, McuServiceType::GroupLevel::eDispId_Group_2_Mini},
{eDispId_CSCD_Mode_AutoChange, McuServiceType::EnumEventID::eDispId_RENAME_CSCD_Mode_AutoChange, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_ChargeDoor_Open, McuServiceType::EnumEventID::eDispId_RENAME_ChargeDoor_Open, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_ChargeDoor_OpenMoving, McuServiceType::EnumEventID::eDispId_RENAME_ChargeDoor_OpenMoving, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_Charging_Alarm, McuServiceType::EnumEventID::eDispId_RENAME_Charging_Alarm, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_Check48VePT, McuServiceType::EnumEventID::eDispId_RENAME_Check48VePT, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_CheckBrake_ABSESC, McuServiceType::EnumEventID::eDispId_RENAME_CheckBrake_ABSESC, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_CheckBrake_BrakeFluid, McuServiceType::EnumEventID::eDispId_RENAME_CheckBrake_BrakeFluid, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_CheckBrake_VacuumPump, McuServiceType::EnumEventID::eDispId_RENAME_CheckBrake_VacuumPump, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_CheckDiffGear, McuServiceType::EnumEventID::eDispId_RENAME_CheckDiffGear, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_CheckHev, McuServiceType::EnumEventID::eDispId_RENAME_CheckHev, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_CheckHevEngine, McuServiceType::EnumEventID::eDispId_RENAME_CheckHevEngine, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_CheckHevNoStart, McuServiceType::EnumEventID::eDispId_RENAME_CheckHevNoStart, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_CheckPattern, McuServiceType::EnumEventID::eDispId_RENAME_CheckPattern, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_CheckPowerSupply, McuServiceType::EnumEventID::eDispId_RENAME_CheckPowerSupply, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_CheckRearSeatAlarm, McuServiceType::EnumEventID::eDispId_RENAME_CheckRearSeatAlarm, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_CheckTireDiff, McuServiceType::EnumEventID::eDispId_RENAME_CheckTireDiff, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_CoolingWater_Refill, McuServiceType::EnumEventID::eDispId_RENAME_CoolingWater_Refill, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_DAW_Fail, McuServiceType::EnumEventID::eDispId_RENAME_DAW_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_DBC_Cancel, McuServiceType::EnumEventID::eDispId_RENAME_DBC_Cancel, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_DBC_Onoff, McuServiceType::EnumEventID::eDispId_RENAME_DBC_Onoff, McuServiceType::GroupLevel::eDispId_Group_2_Mini},
{eDispId_DCT_Cooling, McuServiceType::EnumEventID::eDispId_RENAME_DCT_Cooling, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_DCT_CoolingFinish, McuServiceType::EnumEventID::eDispId_RENAME_DCT_CoolingFinish, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_DCT_HighTemp, McuServiceType::EnumEventID::eDispId_RENAME_DCT_HighTemp, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_DCT_HillHold, McuServiceType::EnumEventID::eDispId_RENAME_DCT_HillHold, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_DCT_LimpHome, McuServiceType::EnumEventID::eDispId_RENAME_DCT_LimpHome, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_DCT_OverHeat, McuServiceType::EnumEventID::eDispId_RENAME_DCT_OverHeat, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_DMS_Fail, McuServiceType::EnumEventID::eDispId_RENAME_DMS_Fail, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_DPF_Fail, McuServiceType::EnumEventID::eDispId_RENAME_DPF_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_DayLightLamp_Fail, McuServiceType::EnumEventID::eDispId_RENAME_DayLightLamp_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_DoorHood_Moving_Open, McuServiceType::EnumEventID::eDispId_RENAME_DoorHood_Moving_Open, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_DoorTrunkHood_Stopped_Open, McuServiceType::EnumEventID::eDispId_RENAME_DoorTrunkHood_Stopped_Open, McuServiceType::GroupLevel::eDispId_Group_8},
{eDispId_DriveMode_Error, McuServiceType::EnumEventID::eDispId_RENAME_DriveMode_Error, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_DriveMode_Full, McuServiceType::EnumEventID::eDispId_RENAME_DriveMode_Full, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_DriveMode_Mini, McuServiceType::EnumEventID::eDispId_RENAME_DriveMode_Mini, McuServiceType::GroupLevel::eDispId_Group_2_Mini},
{eDispId_DynamicBendingLamp_Fail, McuServiceType::EnumEventID::eDispId_RENAME_DynamicBendingLamp_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_ECS_Fail, McuServiceType::EnumEventID::eDispId_RENAME_ECS_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_EMS_SafetyFunction, McuServiceType::EnumEventID::eDispId_RENAME_EMS_SafetyFunction, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_EOL_Error, McuServiceType::EnumEventID::eDispId_RENAME_EOL_Error, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_EPB_Infinite, McuServiceType::EnumEventID::eDispId_RENAME_EPB_Infinite, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_EVSystem_Check, McuServiceType::EnumEventID::eDispId_RENAME_EVSystem_Check, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_EV_Ready, McuServiceType::EnumEventID::eDispId_RENAME_EV_Ready, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_Engine_AutoStop, McuServiceType::EnumEventID::eDispId_RENAME_Engine_AutoStop, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_Engine_HighTemp, McuServiceType::EnumEventID::eDispId_RENAME_Engine_HighTemp, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_ExhaustGas_TestMode, McuServiceType::EnumEventID::eDispId_RENAME_ExhaustGas_TestMode, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_ExtFastCharge_Fail, McuServiceType::EnumEventID::eDispId_RENAME_ExtFastCharge_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_ExtSlowCharge_Fail, McuServiceType::EnumEventID::eDispId_RENAME_ExtSlowCharge_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_FCA_Blockage, McuServiceType::EnumEventID::eDispId_RENAME_FCA_Blockage, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_FCA_Fail, McuServiceType::EnumEventID::eDispId_RENAME_FCA_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_FCA_LO, McuServiceType::EnumEventID::eDispId_RENAME_FCA_LO, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_FCA_LS, McuServiceType::EnumEventID::eDispId_RENAME_FCA_LS, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_FCA_Warn, McuServiceType::EnumEventID::eDispId_RENAME_FCA_Warn, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_FCA_Warn_byScc, McuServiceType::EnumEventID::eDispId_RENAME_FCA_Warn_byScc, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_FCA_wESA, McuServiceType::EnumEventID::eDispId_RENAME_FCA_wESA, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_FCEV_FuelCellFCEVCoolantShortage, McuServiceType::EnumEventID::eDispId_RENAME_FCEV_FuelCellFCEVCoolantShortage, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_FCEV_Regenerate, McuServiceType::EnumEventID::eDispId_RENAME_FCEV_Regenerate, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_FactoryScreen, McuServiceType::EnumEventID::eDispId_RENAME_FactoryScreen, McuServiceType::GroupLevel::eDispId_Group_6},
{eDispId_FlexSteer, McuServiceType::EnumEventID::eDispId_RENAME_FlexSteer, McuServiceType::GroupLevel::eDispId_Group_2_Mini},
{eDispId_FogLamp_Fail, McuServiceType::EnumEventID::eDispId_RENAME_FogLamp_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_FrontWiper, McuServiceType::EnumEventID::eDispId_RENAME_FrontWiper, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_FuelRunOut, McuServiceType::EnumEventID::eDispId_RENAME_FuelRunOut, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_Gear_Engaged_IgnOff, McuServiceType::EnumEventID::eDispId_RENAME_Gear_Engaged_IgnOff, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_Gear_Engaged_IgnOn, McuServiceType::EnumEventID::eDispId_RENAME_Gear_Engaged_IgnOn, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_Goodbye, McuServiceType::EnumEventID::eDispId_RENAME_Goodbye, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_GroupTab, McuServiceType::EnumEventID::eDispId_RENAME_GroupTab, McuServiceType::GroupLevel::eDispId_Group_8},
{eDispId_HBA_Fail, McuServiceType::EnumEventID::eDispId_RENAME_HBA_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_HDA2_Check, McuServiceType::EnumEventID::eDispId_RENAME_HDA2_Check, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_HDA2_Guide, McuServiceType::EnumEventID::eDispId_RENAME_HDA2_Guide, McuServiceType::GroupLevel::eDispId_Group_3},
{eDispId_HDA2_ON_REQ, McuServiceType::EnumEventID::eDispId_RENAME_HDA2_ON_REQ, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_HDA_Cancel, McuServiceType::EnumEventID::eDispId_RENAME_HDA_Cancel, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_HDA_Check, McuServiceType::EnumEventID::eDispId_RENAME_HDA_Check, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_HDA_HDAMode, McuServiceType::EnumEventID::eDispId_RENAME_HDA_HDAMode, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_HDA_HandsOff1, McuServiceType::EnumEventID::eDispId_RENAME_HDA_HandsOff1, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_HDA_HandsOff2, McuServiceType::EnumEventID::eDispId_RENAME_HDA_HandsOff2, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_HDA_ON_REQ, McuServiceType::EnumEventID::eDispId_RENAME_HDA_ON_REQ, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_HDA_SCCMode, McuServiceType::EnumEventID::eDispId_RENAME_HDA_SCCMode, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_Haptic_Fail, McuServiceType::EnumEventID::eDispId_RENAME_Haptic_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_HeadLamp_Bifunc_Fail, McuServiceType::EnumEventID::eDispId_RENAME_HeadLamp_Bifunc_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_HeadLamp_High_Fail, McuServiceType::EnumEventID::eDispId_RENAME_HeadLamp_High_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_HeadLamp_Low_Fail, McuServiceType::EnumEventID::eDispId_RENAME_HeadLamp_Low_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_Headlamp_Off, McuServiceType::EnumEventID::eDispId_RENAME_Headlamp_Off, McuServiceType::GroupLevel::eDispId_Group_2_Mini},
{eDispId_Heated_Wire_Cancel, McuServiceType::EnumEventID::eDispId_RENAME_Heated_Wire_Cancel, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_HighMountedStopLamp_Fail, McuServiceType::EnumEventID::eDispId_RENAME_HighMountedStopLamp_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_IMS_Full, McuServiceType::EnumEventID::eDispId_RENAME_IMS_Full, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_IMS_Mini, McuServiceType::EnumEventID::eDispId_RENAME_IMS_Mini, McuServiceType::GroupLevel::eDispId_Group_2_Mini},
{eDispId_ISG_CancelBrakeClutch, McuServiceType::EnumEventID::eDispId_RENAME_ISG_CancelBrakeClutch, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_ISG_Start, McuServiceType::EnumEventID::eDispId_RENAME_ISG_Start, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_ISLW_Blockage, McuServiceType::EnumEventID::eDispId_RENAME_ISLW_Blockage, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_ISLW_Fail, McuServiceType::EnumEventID::eDispId_RENAME_ISLW_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_IceWarning, McuServiceType::EnumEventID::eDispId_RENAME_IceWarning, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_InverterCoolant_Refill, McuServiceType::EnumEventID::eDispId_RENAME_InverterCoolant_Refill, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_LEDHeadLamp_Fail, McuServiceType::EnumEventID::eDispId_RENAME_LEDHeadLamp_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_LKAS_Cancel, McuServiceType::EnumEventID::eDispId_RENAME_LKAS_Cancel, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_LKAS_Fail, McuServiceType::EnumEventID::eDispId_RENAME_LKAS_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_LKAS_HandsOn_Lv1, McuServiceType::EnumEventID::eDispId_RENAME_LKAS_HandsOn_Lv1, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_LKAS_HandsOn_Lv2, McuServiceType::EnumEventID::eDispId_RENAME_LKAS_HandsOn_Lv2, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_LKAS_HandsOn_Lv2_Sound, McuServiceType::EnumEventID::eDispId_RENAME_LKAS_HandsOn_Lv2_Sound, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_LeadVehicleDeparted, McuServiceType::EnumEventID::eDispId_RENAME_LeadVehicleDeparted, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_LicensePlateLamp_Fail, McuServiceType::EnumEventID::eDispId_RENAME_LicensePlateLamp_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_Light, McuServiceType::EnumEventID::eDispId_RENAME_Light, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_LowBatToPGear, McuServiceType::EnumEventID::eDispId_RENAME_LowBatToPGear, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_LowBatt_Lv1, McuServiceType::EnumEventID::eDispId_RENAME_LowBatt_Lv1, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_LowBatt_Lv2, McuServiceType::EnumEventID::eDispId_RENAME_LowBatt_Lv2, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_LowEngineOil, McuServiceType::EnumEventID::eDispId_RENAME_LowEngineOil, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_LowFuel, McuServiceType::EnumEventID::eDispId_RENAME_LowFuel, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_LowWasher, McuServiceType::EnumEventID::eDispId_RENAME_LowWasher, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_MDPS, McuServiceType::EnumEventID::eDispId_RENAME_MDPS, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_Max, McuServiceType::EnumEventID::eDispId_RENAME_Max, McuServiceType::GroupLevel::eDispId_Group_8},
{eDispId_NCC, McuServiceType::EnumEventID::eDispId_RENAME_NCC, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_NormalChargeError, McuServiceType::EnumEventID::eDispId_RENAME_NormalChargeError, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_OilFilter_Check, McuServiceType::EnumEventID::eDispId_RENAME_OilFilter_Check, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_PA, McuServiceType::EnumEventID::eDispId_RENAME_PA, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_PAS_Fail, McuServiceType::EnumEventID::eDispId_RENAME_PAS_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_PA_Fail, McuServiceType::EnumEventID::eDispId_RENAME_PA_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_PA_ModeChange, McuServiceType::EnumEventID::eDispId_RENAME_PA_ModeChange, McuServiceType::GroupLevel::eDispId_Group_3},
{eDispId_PHEVFuelTank_Charging, McuServiceType::EnumEventID::eDispId_RENAME_PHEVFuelTank_Charging, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_PHEVFuelTank_CheckOrOpen, McuServiceType::EnumEventID::eDispId_RENAME_PHEVFuelTank_CheckOrOpen, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_PHEVFuelTank_WaitOrFuel, McuServiceType::EnumEventID::eDispId_RENAME_PHEVFuelTank_WaitOrFuel, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_PSB_Fail, McuServiceType::EnumEventID::eDispId_RENAME_PSB_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_ParasiticCurrent, McuServiceType::EnumEventID::eDispId_RENAME_ParasiticCurrent, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_ParkingSystem_Group1, McuServiceType::EnumEventID::eDispId_RENAME_ParkingSystem_Group1, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_ParkingSystem_Group4, McuServiceType::EnumEventID::eDispId_RENAME_ParkingSystem_Group4, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_PositionLamp_Fail, McuServiceType::EnumEventID::eDispId_RENAME_PositionLamp_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_PowerDown, McuServiceType::EnumEventID::eDispId_RENAME_PowerDown, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_PowerLimit, McuServiceType::EnumEventID::eDispId_RENAME_PowerLimit, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_RCCW_Blockage, McuServiceType::EnumEventID::eDispId_RENAME_RCCW_Blockage, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_RCCW_Fail, McuServiceType::EnumEventID::eDispId_RENAME_RCCW_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_RearSeatAlarm_Alarm, McuServiceType::EnumEventID::eDispId_RENAME_RearSeatAlarm_Alarm, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_RearSeatAlarm_Clear, McuServiceType::EnumEventID::eDispId_RENAME_RearSeatAlarm_Clear, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_RearWiper, McuServiceType::EnumEventID::eDispId_RENAME_RearWiper, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_Refuel, McuServiceType::EnumEventID::eDispId_RENAME_Refuel, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_RegenBrakeSystem_Fail, McuServiceType::EnumEventID::eDispId_RENAME_RegenBrakeSystem_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_RegenerateFail, McuServiceType::EnumEventID::eDispId_RENAME_RegenerateFail, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_RemainChargeTime, McuServiceType::EnumEventID::eDispId_RENAME_RemainChargeTime, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_Remove_Charge, McuServiceType::EnumEventID::eDispId_RENAME_Remove_Charge, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_Rheostat, McuServiceType::EnumEventID::eDispId_RENAME_Rheostat, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_SBW_LVR_Fail, McuServiceType::EnumEventID::eDispId_RENAME_SBW_LVR_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_SBW_LVR_Fail_IgnOff, McuServiceType::EnumEventID::eDispId_RENAME_SBW_LVR_Fail_IgnOff, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_SBW_ShiftFail, McuServiceType::EnumEventID::eDispId_RENAME_SBW_ShiftFail, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_SBW_VCU1_Warn, McuServiceType::EnumEventID::eDispId_RENAME_SBW_VCU1_Warn, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_SBW_VCU2_Warn_IgnOff, McuServiceType::EnumEventID::eDispId_RENAME_SBW_VCU2_Warn_IgnOff, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_SBW_VCU2_Warn_IgnOn, McuServiceType::EnumEventID::eDispId_RENAME_SBW_VCU2_Warn_IgnOn, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_SBW_scuNMode_IgnOff, McuServiceType::EnumEventID::eDispId_RENAME_SBW_scuNMode_IgnOff, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_SBW_scuNMode_IgnOn, McuServiceType::EnumEventID::eDispId_RENAME_SBW_scuNMode_IgnOn, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_SCC_Blockage, McuServiceType::EnumEventID::eDispId_RENAME_SCC_Blockage, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_SCC_Distance_Full, McuServiceType::EnumEventID::eDispId_RENAME_SCC_Distance_Full, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_SCC_HDA2_AutoReduce, McuServiceType::EnumEventID::eDispId_RENAME_SCC_HDA2_AutoReduce, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_SCC_ModeChange, McuServiceType::EnumEventID::eDispId_RENAME_SCC_ModeChange, McuServiceType::GroupLevel::eDispId_Group_2_Mini},
{eDispId_SCC_NSCC, McuServiceType::EnumEventID::eDispId_RENAME_SCC_NSCC, McuServiceType::GroupLevel::eDispId_Group_3},
{eDispId_SCC_Popup, McuServiceType::EnumEventID::eDispId_RENAME_SCC_Popup, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_SCC_SwitchControl, McuServiceType::EnumEventID::eDispId_RENAME_SCC_SwitchControl, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_SCC_SystemFail, McuServiceType::EnumEventID::eDispId_RENAME_SCC_SystemFail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_SCUOverHeat, McuServiceType::EnumEventID::eDispId_RENAME_SCUOverHeat, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_SEA_IgnOff, McuServiceType::EnumEventID::eDispId_RENAME_SEA_IgnOff, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_SEA_IgnOn, McuServiceType::EnumEventID::eDispId_RENAME_SEA_IgnOn, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_SEA_Operation_fail, McuServiceType::EnumEventID::eDispId_RENAME_SEA_Operation_fail, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_SEA_Operation_noti, McuServiceType::EnumEventID::eDispId_RENAME_SEA_Operation_noti, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_SMK_ExceptParking, McuServiceType::EnumEventID::eDispId_RENAME_SMK_ExceptParking, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_SMK_P_IgnOff, McuServiceType::EnumEventID::eDispId_RENAME_SMK_P_IgnOff, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_SMK_P_IgnOn, McuServiceType::EnumEventID::eDispId_RENAME_SMK_P_IgnOn, McuServiceType::GroupLevel::eDispId_Group_5},
{eDispId_ScreenOff, McuServiceType::EnumEventID::eDispId_RENAME_ScreenOff, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_Service_Reminder, McuServiceType::EnumEventID::eDispId_RENAME_Service_Reminder, McuServiceType::GroupLevel::eDispId_Group_6},
{eDispId_Shift_P_ToCharge, McuServiceType::EnumEventID::eDispId_RENAME_Shift_P_ToCharge, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_StaticBendingLamp_Fail, McuServiceType::EnumEventID::eDispId_RENAME_StaticBendingLamp_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_StopLamp_Fail, McuServiceType::EnumEventID::eDispId_RENAME_StopLamp_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_StopToChargeBattery, McuServiceType::EnumEventID::eDispId_RENAME_StopToChargeBattery, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_SunroofWindowHood_Open, McuServiceType::EnumEventID::eDispId_RENAME_SunroofWindowHood_Open, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_System_Check, McuServiceType::EnumEventID::eDispId_RENAME_System_Check, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_TCF, McuServiceType::EnumEventID::eDispId_RENAME_TCF, McuServiceType::GroupLevel::eDispId_Group_6},
{eDispId_TPMS_SavedNoti, McuServiceType::EnumEventID::eDispId_RENAME_TPMS_SavedNoti, McuServiceType::GroupLevel::eDispId_Group_2_Full},
{eDispId_TPMS_Virgin, McuServiceType::EnumEventID::eDispId_RENAME_TPMS_Virgin, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_TPMS_Warn, McuServiceType::EnumEventID::eDispId_RENAME_TPMS_Warn, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_TPMS_Warn_Inform, McuServiceType::EnumEventID::eDispId_RENAME_TPMS_Warn_Inform, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_TailLamp_Fail, McuServiceType::EnumEventID::eDispId_RENAME_TailLamp_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_TurnSignalLamp_Fail, McuServiceType::EnumEventID::eDispId_RENAME_TurnSignalLamp_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_UREA_Abnormal1_Check1_Stop, McuServiceType::EnumEventID::eDispId_RENAME_UREA_Abnormal1_Check1_Stop, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_UREA_Abnormal2_Check2, McuServiceType::EnumEventID::eDispId_RENAME_UREA_Abnormal2_Check2, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_UREA_Abnormal3_Check3, McuServiceType::EnumEventID::eDispId_RENAME_UREA_Abnormal3_Check3, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_UREA_Shortage1, McuServiceType::EnumEventID::eDispId_RENAME_UREA_Shortage1, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_UREA_Shortage2_3, McuServiceType::EnumEventID::eDispId_RENAME_UREA_Shortage2_3, McuServiceType::GroupLevel::eDispId_Group_4},
{eDispId_UREA_Shortage4, McuServiceType::EnumEventID::eDispId_RENAME_UREA_Shortage4, McuServiceType::GroupLevel::eDispId_Group_1},
{eDispId_UpdateMode, McuServiceType::EnumEventID::eDispId_RENAME_UpdateMode, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_VESS_Fail, McuServiceType::EnumEventID::eDispId_RENAME_VESS_Fail, McuServiceType::GroupLevel::eDispId_Group_7},
{eDispId_Welcome, McuServiceType::EnumEventID::eDispId_RENAME_Welcome, McuServiceType::GroupLevel::eDispId_Group_0},
{eDispId_Wireless_Charger, McuServiceType::EnumEventID::eDispId_RENAME_Wireless_Charger, McuServiceType::GroupLevel::eDispId_Group_0},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_Accessory), McuServiceType::EnumEventID::eDispId_RENAME_Custom_Accessory, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_Close_Popup), McuServiceType::EnumEventID::eDispId_RENAME_Custom_Close_Popup, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_Digital_SpeedMeter), McuServiceType::EnumEventID::eDispId_RENAME_Custom_Digital_SpeedMeter, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_Max), McuServiceType::EnumEventID::eDispId_RENAME_Custom_Max, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_PA_Tab_Info), McuServiceType::EnumEventID::eDispId_RENAME_Custom_PA_Tab_Info, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_PTG_Speed_Change_Fail), McuServiceType::EnumEventID::eDispId_RENAME_Custom_PTG_Speed_Change_Fail, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_Service_Interval_Save), McuServiceType::EnumEventID::eDispId_RENAME_Custom_Service_Interval_Save, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_Service_Interval_Save_Complete), McuServiceType::EnumEventID::eDispId_RENAME_Custom_Service_Interval_Save_Complete, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_Service_Interval_Setting), McuServiceType::EnumEventID::eDispId_RENAME_Custom_Service_Interval_Setting, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Help_Message), McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Help_Message, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_On_Driving), McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_On_Driving, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Park_Assist_Volume), McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Park_Assist_Volume, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_PowerTrunk_Activate), McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_PowerTrunk_Activate, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Reset_Compolete), McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Reset_Compolete, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Reset_Save), McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Reset_Save, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Service_Interval_reset), McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Service_Interval_reset, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Service_Workshop), McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Service_Workshop, McuServiceType::GroupLevel::eDispId_Group_Custom},
{static_cast<int>(McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Voice_Guidance_Volume), McuServiceType::EnumEventID::eDispId_RENAME_Custom_USM_Voice_Guidance_Volume, McuServiceType::GroupLevel::eDispId_Group_Custom}
};
int size_table = sizeof(tableID) / sizeof(tableID[0]);
}
}
| [
"lywoo@ivisolution.com"
] | lywoo@ivisolution.com |
0dbc4a1dee9e64d4f016f87606751547c9323beb | d83724c96fe82d41bf0e22370ee869febd50e8a3 | /ipp-UIC.7.1.1.013/sources/signal-processing/application/ippsdemo/src/RunMinMax.cpp | 5b91cce4bec1ff255e09d06401ca9d2fb6bbfe79 | [] | no_license | vinnie38170/klImageCore | e06b79b61d51d0952a4dca68ad23e40daeff40c3 | 3514aef281f635c7f48699dbfe2a1844f142e03f | refs/heads/master | 2021-01-20T23:03:52.131054 | 2014-07-12T17:52:39 | 2014-07-12T17:52:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,353 | cpp | /*
//
// INTEL CORPORATION PROPRIETARY INFORMATION
// This software is supplied under the terms of a license agreement or
// nondisclosure agreement with Intel Corporation and may not be copied
// or disclosed except in accordance with the terms of that agreement.
// Copyright(c) 1999-2012 Intel Corporation. All Rights Reserved.
//
*/
// RunMinMax.cpp : implementation of the CRunMinMax class.
// CRunMinMax class processes vectors by ippSP functions listed in
// CallIppFunction member function.
// See CRun & CippsRun classes for more information.
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ippsdemo.h"
#include "RunMinMax.h"
#include "ParmMinMaxDlg.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CRunMinMax::CRunMinMax()
{
}
CRunMinMax::~CRunMinMax()
{
}
BOOL CRunMinMax::Open(CFunc func)
{
if (!CippsRun::Open(func)) return FALSE;
m_UsedVectors = VEC_SRC;
(m_value[0]).Init(func,argDST);
(m_value[1]).Init(func,argDST);
return TRUE;
}
void CRunMinMax::UpdateData(CParamDlg* parmDlg, BOOL save)
{
CippsRun::UpdateData(parmDlg,save);
CParmMinMaxDlg *pDlg = (CParmMinMaxDlg*)parmDlg;
if (save) {
CString sType = m_Func.TypeName();
if (pDlg->m_IsIdx)
m_Func = "ippsMinMaxIndx_" + sType;
else
m_Func = "ippsMinMax_" + sType;
for (int i=0; i<2; i++)
m_value[i].Init(m_Func,argDST);
} else {
pDlg->m_IsIdx = m_Func.Found("Indx");
for (int i=0; i<2; i++) {
pDlg->m_IdxStr[i].Format("%d", m_index[i]);
m_value[i].Get(pDlg->m_ReStr[i], pDlg->m_ImStr[i]);
}
}
}
BOOL CRunMinMax::CallIpp(BOOL bMessage)
{
CParmMinMaxDlg dlg(this);
UpdateData(&dlg,FALSE);
if (dlg.DoModal() != IDOK) return TRUE;
UpdateData(&dlg);
return TRUE;
}
void CRunMinMax::SetValues(CParmMinMaxDlg* pDlg)
{
UpdateData(pDlg);
PrepareParameters();
CippsRun::CallIpp();
Timing();
SetHistory();
UpdateData(pDlg,FALSE);
}
IppStatus CRunMinMax::CallIppFunction()
{
FUNC_CALL(ippsMinMax_64f,((Ipp64f*)pSrc, len, (Ipp64f*)(m_value[0]), (Ipp64f*)(m_value[1])))
FUNC_CALL(ippsMinMax_32f,((Ipp32f*)pSrc, len, (Ipp32f*)(m_value[0]), (Ipp32f*)(m_value[1])))
FUNC_CALL(ippsMinMax_32s,((Ipp32s*)pSrc, len, (Ipp32s*)(m_value[0]), (Ipp32s*)(m_value[1])))
FUNC_CALL(ippsMinMax_32u,((Ipp32u*)pSrc, len, (Ipp32u*)(m_value[0]), (Ipp32u*)(m_value[1])))
FUNC_CALL(ippsMinMax_16s,((Ipp16s*)pSrc, len, (Ipp16s*)(m_value[0]), (Ipp16s*)(m_value[1])))
FUNC_CALL(ippsMinMax_16u,((Ipp16u*)pSrc, len, (Ipp16u*)(m_value[0]), (Ipp16u*)(m_value[1])))
FUNC_CALL(ippsMinMax_8u, ((Ipp8u*) pSrc, len, (Ipp8u*) (m_value[0]), (Ipp8u*) (m_value[1])))
FUNC_CALL(ippsMinMaxIndx_64f,((Ipp64f*)pSrc, len, (Ipp64f*)(m_value[0]), m_index + 0,
(Ipp64f*)(m_value[1]), m_index + 1))
FUNC_CALL(ippsMinMaxIndx_32f,((Ipp32f*)pSrc, len, (Ipp32f*)(m_value[0]), m_index + 0,
(Ipp32f*)(m_value[1]), m_index + 1))
FUNC_CALL(ippsMinMaxIndx_32s,((Ipp32s*)pSrc, len, (Ipp32s*)(m_value[0]), m_index + 0,
(Ipp32s*)(m_value[1]), m_index + 1))
FUNC_CALL(ippsMinMaxIndx_32u,((Ipp32u*)pSrc, len, (Ipp32u*)(m_value[0]), m_index + 0,
(Ipp32u*)(m_value[1]), m_index + 1))
FUNC_CALL(ippsMinMaxIndx_16s,((Ipp16s*)pSrc, len, (Ipp16s*)(m_value[0]), m_index + 0,
(Ipp16s*)(m_value[1]), m_index + 1))
FUNC_CALL(ippsMinMaxIndx_16u,((Ipp16u*)pSrc, len, (Ipp16u*)(m_value[0]), m_index + 0,
(Ipp16u*)(m_value[1]), m_index + 1))
FUNC_CALL(ippsMinMaxIndx_8u, ((Ipp8u*) pSrc, len, (Ipp8u*) (m_value[0]), m_index + 0,
(Ipp8u*) (m_value[1]), m_index + 1))
return stsNoFunction;
}
| [
"wavescholar@gmail.com"
] | wavescholar@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.