Skip to content

Tensor template class created #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Tensor template class created #6

wants to merge 2 commits into from

Conversation

Blinkop
Copy link
Collaborator

@Blinkop Blinkop commented Sep 13, 2018

No description provided.

Copy link
Owner

@sandyre sandyre left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поправимс, и будем смотреть дальше, что там по логике. Но общие замечания сразу скажу - все типы, которые являются составными (например, vector), передавать в функции по конст рефе.

void data_release()
{
if (!_is_shallow_copy)
delete[] _data;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут тема такая. По коду много где зовется data_release, допускаю, что на одном тензоре может позваться несколько раз. Первый раз delete норм вызовется, на втором сегфолтнется. Посему, здесь надо сделать следующее:
if (!_is_shallow_copy && _data)
{
delete[] _data;
_data = nullptr
}

using dimensions = std::vector<size_t>;

private:
T* _data = nullptr;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай-ка в конструкторе инитить, а то странно выглядит.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

И я бы даже заменил это на vector. Тогда и не надо никаких data_release, а просто _data.clear(). Меньше шансов облажаться где-нибудь и сделать утечку памяти, а выигрыша по скорости все равно почти нет.


rhs._data = nullptr;
rhs._number_elements = 0;
rhs._dims = {};
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_dims.clear() выглядит пологичнее, имхо
хотя разницы в принципе нет

return result;
}

Tensor operator+(const Tensor& rhs) const
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут вот не понял, почему две перегрузки для сложения. Хватит перегрузки для const-reference, потому что rvalue объект неявно легко преобразуется к const-ref. В противном случае, в перегрузке что сверху всегда будет происходить лишнее копирование. И логика у них почему-то разная..

return result;
}

Tensor operator*(const Tensor& rhs) const
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

То же самое, что для оператора+

return result;
}

Tensor operator[](int index)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот тут не понятно, я всегда буду получать копию. Тензор не модифицируем? Тогда ок.
И все индексы нужно передавать по size_t.

Tensor operator[](int index)
{
auto new_dimensions = _dims;
new_dimensions.erase(new_dimensions.begin());
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Создал вектор, и потом удалил первый элемент, и таким образом вызвал перемещение всех объектов влево. Очень дорого. Есть конструктор вектора из пары итераторов, в твоем случае будет как раз
dimensions new_dims(_dims.begin() + 1, _dims.end()). Но надо бы проверять, что _dims не пустой.

return Tensor(new_dimensions, data_offset);
}

const Tensor operator[](int index) const
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В целом, перегрузка возвращающая конст объект лишена смысла. Достаточно возвращать просто объект, что с ним там дальше делать будут - не дело этого инстанса класса.

// Linear algebra
void transpose()
{
auto tmp = _dims[0];
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

проверка на пустоту вектора? или он гарантированно не пустой? пахнет сегфолтом


private:
// sub-tensor ctor
Tensor(const dimensions& dims, T* data_start_address)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше передать const T*, чисто для читабельности.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants